2015-10-14 29 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

现在工作都完美:)