如何在`collection`字段Symfony 2.1中将选项传递给CustomType?

时间:2022-02-11 06:48:28

I have SuperType Form for Entity Super.

我有实体超级SuperType表格。

In this form I have a collection field of ChildType Form types for Entity Child

在这个表单中,我有一个Entity Child的ChildType表单类型的集合字段

class SuperType:

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:

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
  ));
}

How can I change the my_custom_option value only for this SuperType form?

如何仅为此SuperType表单更改my_custom_option值?

Of course, what I've tried passing this option via constructor doesn't work.

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

2 个解决方案

#1


32  

You can pass an array of options to your childType as follows:

您可以将一组选项传递给childType,如下所示:

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

}

#2


12  

In Symfony 3, this is called entry_options.

在Symfony 3中,这称为entry_options。

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

#1


32  

You can pass an array of options to your childType as follows:

您可以将一组选项传递给childType,如下所示:

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

}

#2


12  

In Symfony 3, this is called entry_options.

在Symfony 3中,这称为entry_options。

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