Symfony Forms持久存在多个EntityType

时间:2018-02-21 19:06:56

标签: symfony symfony-forms

我从ManytoMany(普通)和ManytoOne持续存在没有问题,但是,我不理解从OnetoMany和ManytoMany(Reversed)持久保存实体的正确方法。

以下是一个例子:

ExampleEntity:

...
/**
 * @var ArrayCollection $myentities
 *
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Myentity", mappedBy="exampleentity", cascade={"persist"})
 */
private $myentities;

// getters/setters
/*
public function addMyentity(Myentity $myentitie)
public function removeMyentity(Myentity $myentitie)
public function getMyentities()
public function setMyentities(ArrayCollection $myentities)
*/
...

表格:

...
->add('myentities', 'Symfony\Bridge\Doctrine\Form\Type\EntityType', array(
    'class'         => 'AppBundle\Entity\Myentity',
    'multiple'    => true
))
...

控制器:

...
if ($form->handleRequest($request)->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($exampleentity);
        $em->flush();
    }
}
...

所以这就是问题,从不调用添加和删除函数,因此所有“$ myentities”永远不会持续存在。

我尝试使用“by_reference => false”更新我的表单,但没有记录EntityType(还会创建其他错误)。

我尝试更改我的控制器,但在编辑期间如何检测哪一个被选中(简单)以及哪些未被选中(不容易或未优化)?

学说不应该简化这些任务吗?

2 个答案:

答案 0 :(得分:1)

万一有人偶然发现相同问题的解决方案:

您需要具有适当的设置者/获取者:

class MyEntity
{
    /**
     * @var Groupe[]|ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Groupe", mappedBy="otherEntity")
     */
    protected $notifyGroupsOnNewMail;

    public function addNotifyGroupsOnNewMail(Groupe $notifyGroupsOnNewMail): self
    {
        if (!$this->notifyGroupsOnNewMail->contains($notifyGroupsOnNewMail))
        {
            $this->notifyGroupsOnNewMail[] = $notifyGroupsOnNewMail;
            $notifyGroupsOnNewMail->setMyEntity($this);
        }

        return $this;
    }

    public function removeNotifyGroupsOnNewMail(Groupe $notifyGroupsOnNewMail): self
    {
        if ($this->notifyGroupsOnNewMail->contains($notifyGroupsOnNewMail))
        {
            $this->notifyGroupsOnNewMail->removeElement($notifyGroupsOnNewMail);
            // set the owning side to null (unless already changed)
            if ($notifyGroupsOnNewMail->getMyEntity() === $this)
            {
                $notifyGroupsOnNewMail->setMyEntity(null);
            }
        }

        return $this;
    }
}

但是您的表单中还包含'by_reference'=>假,否则将不会调用您的setter,因此尝试从reverse side保留将不会保存任何内容:

            ->add('notifyGroupsOnNewMail', EntityType::class, [
                'class'    => Groupe::class,
                'required' => false,
                'multiple' => true,
                'by_reference' => false
            ])

答案 1 :(得分:0)

您是否检查过邮件请求期间是否已将已添加的子元素发送到服务器? 如果您使用的是form prototype,则可能需要检查输入索引。