Symfony 2 保存多对多单向关联

Symfony 2 save ManyToMany Unidirectional Association

我有 3 个实体:

用户(基于 fosuserbundle)

群组(虚拟获取所有群组)

角色

当我生成表单时一切正常:

群组类型:

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

群组类型:

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,
        ))
    ;
}

而且我有包含所有组的表单,并为每个组选中了复选框。

但现在我想要save/update这个。

我的manytomany列表group_id到role_id我在Group实体中定义:

/**
 * 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();
}

如何保存这样的表格?

已解决

需要更换控制器保存

        $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;
}

在 GroupType by_reference 中为 false

现在工作完美:)