I'm using Symfony 2.3
I have a form, in which a user selects a state and a city(both with dropdowns).
It works as expected, however I would live to show cities based on a selected state by the user. Basically the form works like this:
Page 1: User selects a state
Page 2: User selects a city (In this point, the State field is locked, and cannot be changed. User can only change cities)
So how can I get from the database the State value, and then use it on Page 2 to display only the cities of that state, without using Ajax.
State form:
->add('state', 'entity', array(
"label" => 'Name of the state(*): ',
'class' => 'PrincipalBundle:State',
"attr" => array('class' => 'control-group', 'style' => 'width: 50%', 'rows' => '1'),
"property"=>"statename"))
Here's the city form:
->add('city', 'entity', array(
"label" => 'City Name (*): ',
'class' => 'PrincipalBundle:Cities',
"attr" => array('class' => 'control-group', 'style' => 'width: 50%', 'rows' => '1'),
"property"=>"cityname"))
I cannot use a event listener. I tried to follow the docs, but I got this error:
The 'choices_as_values' is not declared
I think it is due to the version of Symfony. I cannot upgrade version either, at least not yet.
You definitely can use an event listener. It seems like your only error is regarding choices_as_values. That was introduced in 2.7 to mimic how choices used to work. In Symfony 2.7 the keys/values flipped for how the choices array works, so they added choices_as_values for backwards compatibility (you set it to true to function in the old way).
All you need to do is remove the choices_as_values setting and you should be good to go. Just make sure that the keys are the item value and the values are what should display to the user.
In Symfony 2.3:
$builder->add('gender', 'choice', array(
'choices' => array('m' => 'Male', 'f' => 'Female'),
));
Equivalent Symfony 2.7:
$builder->add('genre', 'choice', array(
'choices' => array('m' => 'Male', 'f' => 'Female'),
'choices_as_values' => false,
));
Also equivalent in Symfony 2.7:
$builder->add('genre', 'choice', array(
'choices' => array('Male' => 'm', 'Female' => 'f'),
'choices_as_values' => true,
));
Equivalent in Symfony 3.0:
$builder->add('genre', 'choice', array(
'choices' => array('Male' => 'm', 'Female' => 'f'),
'choices_as_values' => true,
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With