Symfony 2.6 - display a selection box (radio, checkbox) by name

How can I display a separate field (one field for a radio / flag) in Twig in Symfony 2.6?

Say I have a simple form:

class TransportType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('transport', 'choice', array( 'choices' => array( 'road' => 'Car/bus', 'train' => 'Train', ), 'expanded' => true, 'multiple' => false )); } 

In previous versions of Symfony2, I could just use:

 {{ form_widget(form.transport.road) }} {{ form_widget(form.transport.train) }} 

to display individual switches, but it no longer works. I know I can use:

 {{ form_widget(form.transport[0]) }} {{ form_widget(form.transport[1]) }} 

but it is less flexible. Of course, I can iterate over the collection and check the name, but this seems like unnecessary trouble. Is there an easier way?

I tried offsetGet (which should be return a child by name ), but it also only works with array index.

+8
php symfony twig symfony-forms
source share
3 answers

Try the following:

 {% for key, transportItem in form.transport.children %} {{ form_widget(transportItem) }} {% endfor %} 
+8
source share

It seems like this is not possible in recent versions of Symfony (i.e.>> = 2.6). I remember in previous versions, when the form builder displayed an array of choices , it generated the following options:

 <select> <option value="road">Car/Bus</option> <option value="train">Train</option> </select> 

This, however, has been changed in recent versions to the following:

 <select> <option value="0">Car/Bus</option> <option value="1">Train</option> </select> 

Then the selected option will be normalized, and then you will get the expected value that you set in the FormType class. You can learn more about normalization here .

Also, if you write {{ debug(form.transport) }} in Symfony> = 2.6, you can see an array of forms / fields and what you can use from it.

0
source share

With Symfony 2.7, you can set the name of form forms through the choice_name option.

0
source share

All Articles