symfony - 如何使用symfony2.0设置默认选中filter_checkbox选择字段?

标签 symfony filter checkbox

标题几乎说明了一切,但这里是我的代码片段来说明我正在尝试做的事情。

这是表单类型

//[...]
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/

相关文章:

list - Ansible Jinja2 过滤器

google-sheets - 使用条件过滤列 Google 表格

java - 瓦丁 : Filtering output on the table

复选框状态在剑道网格分页时消失

php - 如何在 Symfony 表单字段上使用 setAttribute

php - 在 Symfony 的控制台命令中使用事件监听器

symfony - 为什么 Symfony2 验证属性 Path 值在方括号中?

Symfony2 - 在 Sonata Admin 的元素列表中提供默认过滤器

asp.net - 如何记住每次翻页之间选定的复选框

android - 在android中选择listview的所有复选框