Hey everyone, I’m working on a Symfony project and I’m stuck. I’ve got a form with two dropdown menus: one for countries and another for cities. Here’s what my form looks like right now:
'country' => new sfWidgetFormChoice(array('choices' => CountryPeer::getAll())),
'city' => new sfWidgetFormChoice(array('choices' => CityPeer::getAll())),
What I want to do is make the city dropdown change based on what country is picked. So if someone selects ‘France’, the city dropdown should only show French cities. The tricky part is I don’t want to use any JavaScript for this. Is there a way to do this on the backend with just Symfony? Any help would be awesome!
Although dynamically populating dropdowns on the server side without JavaScript can be challenging, it is possible using Symfony’s form events. In my experience, a suitable approach is to create a custom form type and subscribe to the PRE_SUBMIT event. In the event listener, you check the submitted value for the country field and update the city field’s available options accordingly. This method requires the entire form to be submitted, which means a page reload, but it adheres to the constraint of avoiding client-side scripting while still dynamically updating the form.
hmmm, interesting challenge! have u considered using ajax calls with symfony’s built-in ajax helpers? it might bend ur no-js rule a bit, but could give u that smooth ux without full page reloads. what do u think? any particular reason for avoiding javascript altogether?
hey ryan, ive faced similar issues before. unfortunately, without js, real-time updates are tricky. you could try submitting the form on country selection to refresh the page with filtered cities. it’s not ideal for UX tho. maybe reconsider using a bit of js? it’d make things smoother for sure.