Posts Tagged ‘symfony’

How to render choice fields individually with Symfony2 Forms

Thursday, April 12th, 2012

Hi there again.  I wanted to share a little trick I found by chance using Symfony2.  But first a little story behind it.

I built a Symfon2 site using the BETA version about a year ago.  Some forms had very specific code to display checkboxes and radio buttons.  At that time you could simply render them yourself by hand putting the right html and names. Everything worked like a sharm.  Yesterday I decided it was time to update that old instalation into the latest 2.0.12 version.  The update wasn’t hard, but once I got into the forms one thing came up.  The form_rest tag was now aware of all the fields that weren’t rendered using form_widget and so it printed them all at the end.  So I ended up with two of each of those fields. The pretty stylish and well-positioned ones and the ugly ones at the end of the form.  So it became time to do it the right way using the form_widget. But when I got to the choice field I noticed it would be very hard to re-style everything using Symfony’s markup. So I wondered… could I just render each radiobutton independently?  And to my surprise the answer is YES!!!!! Here’s how:

{{ form_widget( form.mychoicefield.value1 ) }}

For each value you have, you can just append it to the first parameter of form_widget and it will render ONLY that value.  Notice that in order for this to work you need to add the expaded option when building the form.   I guess this works because inside it creates every value as a subfield of the choice.