为多个设置为 true 的 symfony 选择字段设置默认数据
Posted
技术标签:
【中文标题】为多个设置为 true 的 symfony 选择字段设置默认数据【英文标题】:set default data for symfony choice field with multiple set to true 【发布时间】:2015-09-24 13:58:42 【问题描述】:我正在尝试使用复选框呈现一个选择字段,并且我希望在编辑模式下,这具有用户先前检查的数据,这意味着一种设置默认数据的方法。下面的代码不起作用。有人可以帮忙吗?谢谢
$days = array("monday" => "monday","tuesday" => "tuesday");
$builder->add('channels', 'choice', array(
'choices' => array(
'days' => $days,
),
'multiple' => true,
'expanded' => true,
'required' => true,
'data' => array("choices" => array("days" => array("monday")))
));
【问题讨论】:
【参考方案1】:删除数据数组中的choices
键:
$builder->add(
'channels',
'choice',
array(
...
'data' => array("monday")
)
);
【讨论】:
您的解决方案抛出以下异常:“注意:数组到字符串的转换在 /xxx/xxx/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList /ChoiceList.php 第 457 行"【参考方案2】:这个对我有用(Symfony 2.3.x):
$days = array("monday" => "Monday","tuesday" => "Tuesday","wednesday" => "wednesday","thursday" => "thursday");
$builder->add('channels', 'choice', array(
'choices' => array(
'days' => $days,
),
'multiple' => true,
'expanded' => true,
'required' => true,
'data' => array("wednesday","thursday","tuesday")
));
注意:使用键索引来设置数据而不是值。 “星期二”在这里不会像“星期二”那样起作用。
【讨论】:
在 Symfony v3.3 中仍然有效(当与常规 v3.3 语法一起使用时)。 Tnx。【参考方案3】:我认为这应该可行:
$builder->add(
'channels',
'choice',
array(
...
'data' => array("monday"),
)
)
【讨论】:
试试'data' => array('monday'=>'Monday','tuesday'=>'Tuesday')
它给了我同样的结果
我已经意识到它正在工作我只是在我使用包含多个元素的数组进行测试时忘记了变量中的某些内容。 CiTNOH也在解释它以上是关于为多个设置为 true 的 symfony 选择字段设置默认数据的主要内容,如果未能解决你的问题,请参考以下文章