Accessing specific choices directly from ChoiceType element in Twig
php, symfony
Solution
I've faced a similar situation and solved it this way :
<li>
{{ form_widget(form.myRadioField.children[0]) }}
</li>
<li>
{{ form_widget(form.myRadioField.children[1]) }}
</li>
This is in no way clean, re-usable, best-practice code but it works.
Problem
My project requires me to rebuild the functionality of a large system while retaining the database structure (for historical billing reasons). I started with Symfony 2.0.x and have started the upgrade process to Symfony 2.1.2. Previously, I was able to directly access a radio group's (multiple = false, expanded = true) individual options in Twig using dot notation. For example, in my form I defined the element akin to this: ``` $builder->add('settings_group', 'choice', array( 'choices' => array( 'existing' => 'A pre-existing setting group', 'override' => 'Specify an override instead' ), 'multiple' => false, 'expanded' => true, 'property_path' => false ) ); ``` In my Twig template, my markup was like so: ``` <ul> <li> {{ form_widget(form.settings_group.existing) }} [ .. dropdown ..] </li> <li> {{ form_widget(form.settings_group.override) }} [ .. text input .. ] </li> </ul> ``` It worked perfectly for what I needed to do, as the radio buttons "existing" or "override" would determine which fields were persisted and which were reset when the entity was saved. Specifically, my problem arises because I want to manually separate the radio buttons and output various other form fields before the next radio button. It is a recurring pattern in a number of forms in this system, based on the existing functionality and database. After upgrading to Symfony 2.1, this is no longer possible and I get an error: Method "existing" for object "Symfony\Component\Form\FormView" does not exist I've tried various possibility including .get() and iterating over .choices() [which ends up giving me ChoiceView objects that I cannot then output using form_widget()]. I've tried making a custom Type encapsulating one radio button plus the associated setting fields, but then due to the way the element names are created I cannot have them be mutually exclusive. I also tried making a more complex Type representing both options and associated fields, but once again was unable to access and render a specific choice in the type's template. Ideally, I hope for something in the API that I've simply overlooked and can find/replace and get it working. Otherwise, advice on (or a link to) a more Symfony-friendly approach to doing this would be appreciated.