2012-03-15 65 views
16

我在symfony中創建了2個實體:多對多關係中的用戶和角色。這意味着每個用戶都可以擁有更多角色,並可以爲許多用戶設置角色。symfony2多對多表格複選框

用戶等級:

/** 
    * @ORM\Entity 
    * @ORM\Table(name="JEP_User") 
    * @ORM\Entity(repositoryClass="Chrchel\JepBundle\Repository\UserRepository") 
    */ 
class User implements AdvancedUserInterface { 

/** 
* @ORM\Id() 
* @ORM\Column(name="id",type="integer") 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
private $id; 

/** 
* @ORM\Column(name="username",type="string",length=100,unique=true) 
*/ 
private $username; 

/** 
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users") 
* 
*/ 
protected $roles; 

//.... 
} 

角色類:

/** 
* @ORM\Table(name="JEP_Role") 
* @ORM\Entity() 
*/ 
class Role implements RoleInterface { 

/** 
* @ORM\Column(name="id", type="integer") 
* @ORM\Id() 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
protected $id; 

    /** @ORM\Column(name="name", type="string", length=30) */ 
protected $name; 

/** @ORM\Column(name="role", type="string", length=20, unique=true) */ 
protected $role; 

/** @ORM\ManyToMany(targetEntity="User", mappedBy="roles") */ 
protected $users; 
//... 
} 

我無法弄清楚如何譜寫出的Symfony2查詢生成器列出存在的所有角色,並把它添加到年底UserForm的角色可以選擇(作爲複選框)授予用戶的角色。 我試圖用收集像這樣的用戶類型

->add('roles', 'collection',array('label' => 'Role', 'required' => false,'type'=> new RoleType())) 

我從symfony中獲得的最好用文本框行與角色選定的名稱。但這不是,我需要。

回答

30

我用實體類型代替收藏。我收集的東西主要用於創建 a Role對象,並將其分配給User

如果你想只列出所有現有的角色和能夠選擇並將其分配給那麼用戶:

->add('roles', 'entity', array(
    'class' => 'MyBundle:Role', 
    'property'  => 'name', 
    'multiple'  => true 
)); 

編輯:這將使小部件爲多<select>,請參閱entity type呈現爲複選框列表。

+8

將「expanded」選項設置爲「true」以具有複選框列表。你需要在角色模型上實現'__toString()'方法(用於在每個複選框旁邊顯示標籤 – GiDo 2012-03-15 17:10:13

+1

我發現我必須向User實體添加另一個方法才能將角色作爲Collection返回,而不是as一個數組 - getRolesAsCollection。 – 2012-04-18 10:36:57

+2

你如何調用這個特定的'getRolesAsCollection'和where? – 2012-05-24 19:15:27

6

@ user1041880:如果您使用symfony的安全功能(這需要個EUSER的角色,作爲一個數組),你可以做這樣的:

->add('rolesAsCollection', 'entity', array(
    'class' => 'MyBundle:Role', 
    'property'  => 'name', 
    'multiple'  => true 
)); 

而用戶等級:

public function getRolesAsCollection() 
{ 
    return $this->roles; 
} 
5

Symfony3:

在任何人的情況下,使用Symfony3

use Symfony\Bridge\Doctrine\Form\Type\EntityType; 

->add('roles', EntityType::class, array(// <-- EntityType::class is unique to Symfony3 
    'class' => 'AppBundle:Role', 
    'choice_label' => 'name', // <-- choice_label is unique to Symfony3 
    'multiple' => true 
)) 
+0

我有與上面完全相同的格式(Symfony 3:答案4)。'roles'代表的字段已被設置爲ManyToMany。有沒有設置使用ArrayCollection()(也試過沒有)。無論哪種方式,我得到一個錯誤,並不能爲我的生活找出它想要的一些反饋 – LoveFineArt 2017-10-01 21:05:37

+0

我有完全相同的格式如上(Symfony 3:答案4)'角色'表示的字段已被設置爲ManyToMany,我使用ArrayCollection()進行設置(也沒有嘗試過)。無論哪種方式,我都會遇到一個錯誤,並且無法爲我的生活弄清楚。會愛一些fe edback。沒有ArrayCollection:ERROR =「無法轉換屬性路徑的用戶值」:期望一個Doctrine \ Common \ Collections \ Collection對象。「 – LoveFineArt 2017-10-01 21:19:25