Cloning object after getting data from a form in Symfony2

馋奶兔 提交于 2020-01-02 07:21:11

问题


I'm sure I'm missing something very basic here.

I have a form, and when the user updates the fields of the form I don't want to update the underlying entity but want to create a new entity with the new values.

To clone Doctrine entities I followed the indication here.

So my code is (let's say I want to clone the object with id=3:

    $id = 3;
    $storedBI = $this->getDoctrine()
                     ->getRepository('AppBundle:BenefitItem')
                     ->find($id);
    $form = $this->createForm(new BenefitItemFormType(), $storedBI);

    $form->handleRequest($request);

    if ($form->isValid())
        {
            $em = $this->getDoctrine()->getManager();  
            $newBI = clone $form->getData();
            $em->persist($newBI);
            $em->flush();
        }

It simply does not work. It properly creates a new object with the new data passed from the form (which is ok), but also updates the "old" stored object with the same new data.

Any idea?


回答1:


You have to clone your object during the form creation:

$form = $this->createForm(new BenefitItemFormType(), clone $storedBI);

If this does not work, try to detach your cloned object first.



来源:https://stackoverflow.com/questions/29264467/cloning-object-after-getting-data-from-a-form-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!