2015-10-14 94 views
0

我有3個實體:Symfony的2保存多對多單向關聯

用戶(基於fosuserbundle)

集團

組(虛擬得到所有組)

角色

當我生成形式一切工作正常:

GroupsType:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('groups', 'collection', array('type' => new GroupType($this->ExistingRoles))) 
     ; 
} 

GroupType:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('name') 
     ->add('groupRoles', 'entity', array(
     'class' => 'AppBundle:Role', 
     'property' => 'role', 
     'multiple' => true, 
     'expanded' => true, 
     'property' => 'name', 
     'required' => false, 
     'by_reference' => true, 
     )) 
    ; 
} 

我必須跟所有組和複選框選中每個組的形式。

但現在我想保存/更新此。

我多對多GROUP_ID的列表ROLE_ID我在組實體定義:

/** 
* GROUP ManyToMany with ROLE Unidirectional Association 
* @var ArrayCollection 
* @ORM\ManyToMany(targetEntity="Role",inversedBy="group") 
* @ORM\JoinTable(name="group_roles") 
*/ 
protected $groupRoles; 

和角色實體:

/** 
* @ORM\ManyToMany(targetEntity="Group", mappedBy="groupRoles") 
*/ 
private $group; 

我想是這樣的,但不起作用:

$all = $form->getData(); 
$em = $this->getDoctrine()->getEntityManager(); 
foreach($all as $d){ 
    $em->getRepository('AppBundle:Group')->find($d->getId()); 
    $em->persist($d); 
    $em->flush(); 
} 

如何保存這樣的表單?

回答

0

解決

需要改變控制器保存

 $all = $form->getData(); 
     $em = $this->getDoctrine()->getManager(); 
     foreach($all as $d){ 
      $em->persist($d); 
     } 
     $em->flush(); 

在組實體:

在角色實體
public function setgroupRoles($roles) 
{ 
    $this->groupRoles = $roles; 


    return $this; 
} 

/** 
* Add group 
* 
* @param \AppBundle\Entity\Group $group 
* @return Role 
*/ 
public function addGroup(\AppBundle\Entity\Group $group) 
{ 
    $this->group[] = $group; 
    $group->groupRoles($group); 
    return $this; 
} 

In GroupType by_reference to false

現在工作都完美:)