3

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?

Community
  • 1
  • 1
Sergio Negri
  • 2,023
  • 2
  • 16
  • 38

1 Answers1

3

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.

Benjamin Paap
  • 2,744
  • 2
  • 21
  • 33
  • Hi @Benjamin Paap, some complication arose (you can have a look at a detailed explanation here http://stackoverflow.com/questions/29347310/symfony2-cloning-entities-with-collections-and-entity-field-type ). Maybe you can help. Thank you immensely! – Sergio Negri Mar 30 '15 at 16:15