In a Symfony2 website I’m trying to make a form with 2 (or 3) dropdown lists with a dependency like Country > Region > City. And that city is a field of the element I’m editing with the form. The idea is to fill the lists depending on selections.
I’ve followed the tutorial with form events here : http://aulatic.16mb.com/wordpress/2011/08/symfony2-dynamic-forms-an-event-driven-approach/
(which is based on webb-on-the-web .com/?p=5)
The issue I have: it all works but when I use the form to edit the element, the city is selected correctly (from DB) but the Country and Region dropdown lists are prefilled and left on ‘select a value’. I don’t know if it was supposed to work with the tutorial as it is.
The question : how can I make these lists selected? I’m trying to add a POST_SET_DATA event but I can’t find a way to select the value in the form field.
Here’s the form class : http://pastebin.com/PpWkHxC3 (note that instead of city it’s : Field > Topic and topic is a field of a Lesson which the form edits).
I almost had it. If anybody else ever needs this here’s what needs to be added to make this solution work perfectly when editing an existing item :
Edit: since symfony 2.1, the POST_SET_DATA event is called before the children are added to the form, causing all the get(‘region’) to raise an exception.
The solution is to create this field in the POST_SET_DATA and not in the buildForm() :
Note that you need to add the $factory to the ‘use’ of the closure handling the event :
Here is the whole form class: