标题几乎说明了一切,但这里是我的代码片段来说明我正在尝试做的事情。
这是表单类型
//[...]
class ActivityFilterType extends AbstractType
{
//[...]
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('filter_checkbox', 'choice', array(
'label' => $this->translator->trans('form.label.sexFilter'),
'choices' => array(1 => ucfirst($this->translator->transChoice('sex.female', 2)), 2 => ucfirst($this->translator->transChoice('sex.male', 2))),
'multiple' => true,
'expanded' => true,
'required' => false,
'empty_value' => false,
/*
// those ones didn't make it
'attr' => array( 1=>array('checked' => 'checked'), 2=>array('checked' => 'checked') ),
'preferred_choices' => array(1, 2),
*/
));
}
//[...]
}
以及表单模板
<div class="filter-message">
<div class="select-group">
{{ form_label(form.filter_dropdown) }}
<div class="input control-group filter" >
{{ form_widget(form.filter_dropdown) }}
</div>
</div>
<div class="checkbox">
{{ form_label(form.filter_checkbox) }}
{{ form_widget(form.filter_checkbox, {'attr':{'checked':checked}}) }}
<!-- that didn't do it neither -->
</div>
</div>
谢谢
最佳答案
我关注了@bentidy回答in a previous post @Squazic 指向这里。很简单
所以对我来说,因为我希望默认情况下选中两个性别复选框,所以我必须将数据参数添加为数组(它接受单个值和数组)。
事情是这样的:
//[...]
class ActivityFilterType extends AbstractType
{
//[...]
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('filter_checkbox', 'choice', array(
'label' => $this->translator->trans('form.label.sexFilter'),
'choices' => array(1 => ucfirst($this->translator->transChoice('sex.female', 2)), 2 => ucfirst($this->translator->transChoice('sex.male', 2))),
'multiple' => true,
'expanded' => true,
'required' => false,
'empty_value' => false,
'data' => array(1,2) // female value is 1 and male value is 2
));
}
//[...]
}
这是相关文档:http://symfony.com/doc/2.0/reference/forms/types/field.html
谢谢大家
关于symfony - 如何使用symfony2.0设置默认选中filter_checkbox选择字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15014215/