2013-05-09 25 views
3

我想創建一個窗體來編輯我的用戶。 用戶和角色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

回答

0

,因爲我不喜歡它的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