如何设置为默认选中symfony2.0的filter_checkbox选项字段?

时间:2013-02-21 23:28:06

标签: symfony filter checkbox choice

标题几乎说明了所有内容,但这里有一些代码来说明我正在尝试做的事情。

这是表格类型

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

由于

3 个答案:

答案 0 :(得分:3)

我按@bentidyin 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

谢谢大家

答案 1 :(得分:0)

您可以在控制器中执行此操作:

$activityFilter = new ActivityFilter();
$activityFilter->setFilterCheckbox(1);
$form = $this->createForm(new ActivityFilterType(), $activityFilter);
...

顺便说一句:你不应该为你的属性命名filter_checkbox,而应该更具体地说明存储的内容。例如,在这种情况下为sexFilter

答案 2 :(得分:0)

如果您有复选框数组,则必须将“数据”设置为要检查的复选框值的数组。像那样:

'data' =>array(0,1,2),'choices'=>array(0=>'Permitem Acesso Livre', 1=>'Exigem Cadastro', 2=>'Cobram Mensalidades ou Taxas')

就是这样。