我正在使用 Symfony 2.3
我有一个表单,用户可以在其中选择州和城市(均带有下拉菜单)。
它按预期工作,但我会根据用户选择的州显示城市。表单基本上是这样工作的:
第1页:用户选择状态
第2页:用户选择城市 (此时State字段被锁定,无法更改,用户只能更改城市)
那么我如何从数据库中获取州值,然后在第 2 页上使用它来仅显示该州的城市,而不使用 Ajax。
状态形式:
->add('state', 'entity', array(
"label" => 'Name of the state(*): ',
'class' => 'PrincipalBundle:State',
"attr" => array('class' => 'control-group', 'style' => 'width: 50%', 'rows' => '1'),
"property"=>"statename"))
这是城市形式:
->add('city', 'entity', array(
"label" => 'City Name (*): ',
'class' => 'PrincipalBundle:Cities',
"attr" => array('class' => 'control-group', 'style' => 'width: 50%', 'rows' => '1'),
"property"=>"cityname"))
我不能使用事件监听器。我试图按照文档进行操作,但出现此错误:
The 'choices_as_values' is not declared
我认为这是由于 Symfony 的版本。我也不能升级版本,至少现在还不能。
最佳答案
您绝对可以使用事件监听器。似乎您唯一的错误是关于 choices_as_values
。那是 introduced in 2.7模仿 choices
过去的工作方式。 In Symfony 2.7 the keys/values flipped对于 choices
数组的工作方式,他们添加了 choices_as_values
以实现向后兼容性(将其设置为 true
以旧方式运行)。
您需要做的就是删除 choices_as_values
设置,然后就可以开始了。只需确保键是项目值,值是应向用户显示的内容。
$builder->add('gender', 'choice', array(
'choices' => array('m' => 'Male', 'f' => 'Female'),
));
$builder->add('genre', 'choice', array(
'choices' => array('m' => 'Male', 'f' => 'Female'),
'choices_as_values' => false,
));
在 Symfony 2.7 中也是等价的:
$builder->add('genre', 'choice', array(
'choices' => array('Male' => 'm', 'Female' => 'f'),
'choices_as_values' => true,
));
$builder->add('genre', 'choice', array(
'choices' => array('Male' => 'm', 'Female' => 'f'),
'choices_as_values' => true,
));
关于php - Symfony2 : Change dropdown values based on another field value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45761180/