php - Symfony2 : Change dropdown values based on another field value

标签 php forms symfony

我正在使用 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 设置,然后就可以开始了。只需确保键是项目值,值是应向用户显示的内容。

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,
));

在 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,
));

关于php - Symfony2 : Change dropdown values based on another field value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45761180/

相关文章:

php - 生成连续的引用号

php - Doctrine - Query One-To-Many, Unidirectional with Join Table association from inverse side

symfony - 用作 Symfony 参数的非标量 ENV

php - 使用表单更改 CSS

从数据库检索时php标签数据不执行

forms - 可用性:即使焦点未设置在 OK/DONE 按钮上,是否应按 ENTER 键关闭向导窗体?

javascript - 如何中断表单发布,直到按下确认按钮?

jquery - 如何在提交 html 表单时打开 jQuery 模态窗口

php - 使用 F12 工具时信息加倍

php - Zend 的多个数据库