【问题标题】:Symfony 4: pass custom data to Form Collection prototypeSymfony 4:将自定义数据传递给表单集合原型
【发布时间】:2019-05-23 21:09:55
【问题描述】:

当 'allow_add' 选项设置为 true 时,CollectionType 字段具有特殊的 'prototype' 变量。该变量可用于渲染原型 html,如下所示:

data-prototype="{{ form_widget(form.collectionfieldname.vars.prototype)|e('html_attr') }}"

看起来“原型”只是使用部分数据构建的集合子 FormView 的一个实例(例如,名称设置为“__name__”,而大多数其他变量留空)。

所有这些魔法发生在哪里?是否可以在构建表单时修改传递给原型视图的数据?例如,我想将“value”变量的默认值从空白更改为“__val__”(在 Twig 模板之外)。

【问题讨论】:

  • 你尝试过 buildView 吗?
  • 看起来我想通了(请参阅下面我自己的答案)。视图是在 CollectionType 类的 buildView 方法中创建的,而原型表单是在同一个类的 buildForm 方法中构建的。

标签: symfony symfony-forms symfony4


【解决方案1】:

回答自己的问题 - “entry_options”设置中定义的值用于构建原型。可以像这样将这些值传递给表单构建器:

$builder
            ->add('email', CollectionType::class, array(
                ...
                'entry_options' => array(
                    'someoption' => 'somevalue',
                ),
                ...
                ))

如果这还不够,可以通过覆盖负责收集选项和构建原型的“CollectionType”类中的“buildForm”方法来修改默认行为:

class CollectionType extends AbstractType
{
    ...

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($options['allow_add'] && $options['prototype']) {
            $prototypeOptions = array_replace(array(
                'required' => $options['required'],
                'label' => $options['prototype_name'].'label__',
            ), $options['entry_options']);

            if (null !== $options['prototype_data']) {
                $prototypeOptions['data'] = $options['prototype_data'];
            }

            $prototype = $builder->create($options['prototype_name'], $options['entry_type'], $prototypeOptions);
            $builder->setAttribute('prototype', $prototype->getForm());
        }

        ...
    }
...
}

【讨论】:

    猜你喜欢
    • 2019-05-25
    • 1970-01-01
    • 2023-03-19
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多