使用 FormTypeExtensions 修改字段选项


Modifying field options using FormTypeExtensions

我知道在使用 FormEvents 构建表单后没有干净的方法来执行此操作,但是有没有办法在完全构建表单之前使用 FormTypeExtensionInterface::buildForm 将传递给表单的选项进行维护?

例如:当以

表单设置另一个选项时,我将使用它将多个选项设置为特定值,例如:当选项"helper"设置为 true 时,将"label"选项设置为"帮助程序"并将"disabled"选项设置为true

因此,您可以做的是在创建表单时将选项传递给表单。 例如,在控制器中:

$form = $this->createForm(new YourFormType(), null, array('helper' => true));

然后在buildForm函数中:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('myfield', null, array(
            'label'    => ($options['helper']) ? 'helper' : 'mylabel',
            'disabled' => ($options['helper']) ? true : false,
        ))
    ;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'helper' => false,
    ));
}

唯一的问题是,这是整个表单的全局选项。 您的意思是您希望每个字段都使用此选项吗?