如何在symfony2表单中生成多个复选框

时间:2012-07-13 07:49:17

标签: php symfony

我想在Symfony表单中显示预定义数组的复选框。用户应该能够选择多个,但我无法做到。

这是我的代码:

public function buildForm(FormBuilder $builder, array $options)
{
    $roles = array('role1', 'role2', 'role3');
    $builder
        ->add('name')
        ->add('roles', 'checkbox', $roles)
    ;
}

2 个答案:

答案 0 :(得分:8)

请参阅choice type reference

public function buildForm(FormBuilder $builder, array $options)
{
    $roles = ['role1', 'role2', 'role3'];

    $builder
        ->add('name')
        ->add('roles', 'choice', [
            'choices' => $roles,
            'multiple' => true,
            'expanded' => true
        ])
    ;
}

答案 1 :(得分:4)

您可以改为使用choice字段:

public function buildForm(FormBuilder $builder, array $options)
{        
    $roles = array("role1","role2","role3");
    $builder
        ->add('name')
        ->add('roles', 'choice', array(
            'choices' => $roles,
            'multiple' => true,
            'expanded' => true,
        ))    
    ;
}

查看文档,了解如何使用此字段类型的复选框,选择或单选按钮:http://symfony.com/doc/current/reference/forms/types/choice.html#forms-reference-choice-tags