2

(Symfony-newbie here), I have some basic code that updates fields in DB.

public function editAction(Request $request, $id)
{
 
    
    $em = $this->getDoctrine()->getManager();
    $testowanie = $em->getRepository('TestowanieBundle:Test')->findOneBy(array('id' => $testowanieId));
     
    $form = $this->createForm(TestowanieType::class, $testowanie);
 
    $form->handleRequest($request);
 
 
    if ($form->isSubmitted() && $form->isValid()) {
 
        $em->persist($testowanie);
 
        $em->flush();
        return $this->redirectToRoute('...');
    }

This function gets data from row in DB and overwrites it, but I want to insert a copy with new id based on data currently saved in DB.

TeslaX93
  • 117
  • 1
  • 11
  • You have to select the original entity then use the setters and persist the entity as usual. The easiest way without a doubt, to see this in action would be to generate a crud controller from the cli to see how symfony does it as standard. – Doug Jul 24 '17 at 05:52

1 Answers1

2

How to re-save the entity as another row in Doctrine 2

As stated in this post, you should either reset the id or just use the Clone keyword like this:

if ($form->isSubmitted() && $form->isValid()) {
    $new_entity = clone $testowanie;
    $em->persist($new_entity);
    $em->flush();
    return $this->redirectToRoute('...');
}
davidbonachera
  • 4,416
  • 1
  • 21
  • 29