Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass options to CustomType in `collection` field Symfony 2.1?

I have SuperType Form for Entity Super.

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

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

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

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

like image 342
user1236048 Avatar asked Mar 18 '13 14:03

user1236048


2 Answers

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

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

}
like image 94
Ahmed Siouani Avatar answered Nov 10 '22 13:11

Ahmed Siouani


In Symfony 3, this is called entry_options.

$builder->add('childrens', CollectionType::class, array(
    'entry_type'   => ChildType::class,
    'entry_options'  => array(
        'my_custom_option'  => true
    ),
));
like image 27
Georgij Avatar answered Nov 10 '22 12:11

Georgij