symfony2使用arraycollection形式多选select

问题描述:

我想创建一个窗体来编辑我的用户。 用户和角色ManyToMany。 在UserUsers实体我有一个$角色变量,它是ArrayCollectionsymfony2使用arraycollection形式多选select

public function __construct() 
{ 
    $this->roles = new ArrayCollection(); 
} 

在我的形式,我想通过多选表单元素将角色添加到我的用户。 在我的用户形式:

public function buildForm(FormBuilderInterface $builder, array $options) { 
    $builder->add('username') 
      ->add('password', 'repeated', array( 
        'type' => 'password', 
        'mapped' => false, 
        'required' => false, 
        'first_options' => array( 
          'label' => 'Password'), 
        'second_options' => array( 
          'label' => 'Repeat Password'))) 
      ->add('roles', 'choice', array( 
        'mapped' => false, 
        'multiple' => true)); 
} 

现在我的多个选择是空的。

如果我把映射到真实的,我得到一个错误信息:

UserRoles could not be converted to int in...

我已经尝试了很多方法,但我不能正确地解决这个问题。

+0

你在$ roles ArrayCollection中有什么类型? – redbirdo 2013-05-09 13:11:47

+0

$ roles中的所有元素ArrayCollection是一个实体(UserRoles)。 – lordjancso 2013-05-09 14:26:49

+0

对于实体的选择,你应该使用专用的选择字段类型“实体”(http://symfony.com/doc/current/reference/forms/types/entity.html)。对于一个例子看到我的答案类似的问题 - http://stackoverflow.com/questions/13519961/symfony-2-form-create-user-and-add-group/13521462#13521462 – redbirdo 2013-05-09 15:50:08

对于实体应该使用专用的选择字段类型“实体”的选择(参见Symfony的手册entity field type)。举个例子,看看我对similar question的回答。 如果您还有其他错误,您可能也会对Role Interface and Manage Roles有帮助。

,因为我不喜欢它的fosuserbundle:

 $builder->add('roles', 'choice', array(
     'multiple' => true, 
     'choices' => array(
      'ROLE_USER' => 'User', 
      'ROLE_AUTHOR' => 'Autor', 
      'ROLE_MODERATOR' => 'Moderator', 
      'ROLE_ADMIN' => 'Admin' 
     ), 
     'label' => 'Rollen', 
     'required' => true 
    )); 
+0

这将是很好的,但我将角色存储在数据库中,当我打开用户进行编辑,我想选择分配给当前用户的角色。 – lordjancso 2013-05-09 13:54:35

+0

我已经理解了,我强烈建议使用FOSUserBundle - 由于安全性。在那里你可以存储多个角色给用户。这是你想要的结局。 – stwe 2013-05-09 14:50:12