首先,向大家致以2016年新年最美好的祝愿!
我正面临着一个我自己无法解决的问题。
我正在开发一个Silex (~1.3)应用程序。我在域类上编写了简单的CRUDs代码。我还创建了一些Type表单,以便能够修改我的基本域类。在这种情况下,我必须在一个State中管理Country的概念。每个类都是特定的类,State有一个Country属性。
在我的表单中,我声明了一些文本字段,以及一个能够选择国家的Choice字段(表单类在下面复制)。
我的问题是,当我试图用下面的控制器修改现有的State时,文本字段name、code、unloc都填充了来自数据库的数据,而不是选项country或hub (控制器类在下面复制)。
请注意,我不是使用Doctrine,而是一个自制的(相当基本的) DAO。
这是我的代码和一些信息:
发布于 2016-01-11 15:54:59
我设法找到了一个解决方案(可能不是最好的,但它有效)。
我的理解是:我们将对象作为choices,使用它作为值,然后使用闭包获取ids和labels,而不是自己做工作,给表单提供“现成的”数据。
有更干净的方法吗?
$obj = $this->countryDAO->findAll ();
$list = array ();
foreach ( $obj as $value ) {
$list [$value->getId ()] = $value;
}
$builder->add ( 'country', 'choice', array (
'choices' => $list,
'choices_as_values' => true,
'choice_label' => function ($value) {
return $value->getName ();
},
'choice_value' => function ($value) {
// you mightwant to check for null here, is your form concern
// a attribute that can be null, as the closure appear to be called
// on the attribute, and not only on the $obj contents;
return $value->getId ();
},
'placeholder' => 'Select a country'
) );发布于 2016-01-07 10:03:20
假设选择没有被来自DB的数据填充,因为country和hub id没有传输到ChoiceList。
$choices = array();
foreach ($countries as $value) {
$choices[$value->getId()] = $value->getName();
}
$builder->add('country', 'choice', array(
'choices' => $choices
));发布于 2016-01-11 16:00:23
将这一行添加到您的选择选项:'choices_as_values' => true,
激活新的选择类型API http://symfony.com/doc/current/reference/forms/types/choice.html#example-usage是非常必要的。
https://stackoverflow.com/questions/34594451
复制相似问题