2

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

这是表单类型

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

谢谢

4

3 回答 3

3

我在@Squazic指出的上一篇文章中关注了@bentidy的回答。这很简单

所以对我来说,因为我希望默认选中两个性别复选框,所以我必须将 data 参数添加为数组(它同时接受单个值和数组)。

它是这样的:

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

多谢你们

于 2013-03-01T23:25:10.430 回答
0

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

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

顺便说一句:你不应该命名你的属性filter_checkbox,而是让它更具体地存储什么。例如sexFilter在这种情况下。

于 2013-02-22T09:59:11.673 回答
0

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

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

就是这样。

于 2013-09-03T02:40:11.780 回答