2012-08-11 51 views
2

我有一个用户注册表单(管理员使用),我想包括角色的选择。我已经成功添加以下代码角色的下拉列表中我buildForm功能:如何在symfony2表单域中启用多项选择:集合

$builder 
     ->add('roles', 'collection', array(
      'type' => 'choice', 
      'options' => array(
       'choices' => array(
        'ROLE_CONTENT' => 'Innehåll', 
        'ROLE_LAYOUT'  => 'Skärmlayout', 
        'ROLE_VIDEO' => 'Videouppladdning', 
        'ROLE_ADMIN' => 'Administratör', 
       ), 
      ), 
    )); 

现在,我想这是一个multichoice或复选框,而不是一个下拉列表,但我似乎无法找到一种方式,似乎是一件足够简单的事情,或者我错过了这种字段类型的工作原理,难道它不会采取多种选择?

回答

6

你不这里不需要collection类型。将“多”设置为truechoice类型将输出一个集合就好了。

$builder 
    ->add('roles', 'choice', array(
     'expanded' => true, 
     'multiple' => true, 
     'choices' => array(
      'ROLE_CONTENT' => 'Innehåll', 
      'ROLE_LAYOUT' => 'Skärmlayout', 
      'ROLE_VIDEO' => 'Videouppladdning', 
      'ROLE_ADMIN' => 'Administratör', 
     ), 
    )) 
; 
0

目前,您正在使用collection作为choice类型,这意味着您可以使用expanded and multiple options来呈现所需的四种元素类型中的任意一种。

+0

这是不正确的。 Collection扩展了FormType,而不是ChoiceType。 http://symfony.com/doc/current/reference/forms/types/collection.html – mmoreram 2016-12-19 12:49:45

0

展开的作品很好,给了我单选按钮,但我想要复选框。

这适用于收音机:

$builder 
     ->add('roles', 'collection', array(
      'type' => 'choice', 
      'options' => array(
       'expanded' => true, 
       'choices' => array(
        'ROLE_CONTENT' => 'Innehåll', 
        'ROLE_LAYOUT'  => 'Skärmlayout', 
        'ROLE_VIDEO' => 'Videouppladdning', 
        'ROLE_ADMIN' => 'Administratör', 
       ), 
      ), 
    )); 

如果我把这个然而,抛出阵‘‘串’给“错误”类型的预计说法’:

$builder 
     ->add('roles', 'collection', array(
      'type' => 'choice', 
      'options' => array(
       'expanded' => true, 
       'multiple' => true, 
       'choices' => array(
        'ROLE_CONTENT' => 'Innehåll', 
        'ROLE_LAYOUT'  => 'Skärmlayout', 
        'ROLE_VIDEO' => 'Videouppladdning', 
        'ROLE_ADMIN' => 'Administratör', 
       ), 
      ), 
    ));