Symfony 2保存了ManyToMany单向关联

时间:2015-10-14 09:58:39

标签: forms symfony save roles

我有3个实体:

用户(基于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,
        ))
    ;
}

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

但是现在我想要保存/更新它。

我在群组实体中定义的manytomany group_id to 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();
}

如何保存这样的表格?

1 个答案:

答案 0 :(得分: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;
}

在GroupType中,by_reference为false

现在工作完美:)