如何在“集合”字段Symfony 2.1中将选项传递给CustomType?

2022-08-30 17:03:38

我有实体表格。SuperTypeSuper

在此表单中,我有一个实体的表单类型字段collectionChildTypeChild

class SuperType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('childrens', 'collection', array(
            'type' => new ChildType(null, array('my_custom_option' => true)),  
}

class ChildType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    if ($options['my_custom_option']) {
        $builder->add('my_custom_field', 'textarea'));
    }
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
  $resolver->setDefaults(array(
      ...
      'my_custom_option' => false
  ));
}

如何仅更改此表单的值?my_custom_optionSuperType

当然,我尝试通过构造函数传递此选项的内容不起作用。


答案 1

您可以将选项数组传递给子类型,如下所示:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('childrens', 'collection', array(
            'entry_type' => new ChildType(),  
            'entry_options'  => array(
                'my_custom_option' => true,
            ),
    // ...

}

答案 2

在Symfony 3中,这被称为entry_options

$builder->add('childrens', CollectionType::class, array(
    'entry_type'   => ChildType::class,
    'entry_options'  => array(
        'my_custom_option'  => true
    ),
));

推荐