Search code examples
phpformssymfonydoctrine-ormsymfony-forms

Symfony2 form collection: How to remove entity from a collection?


I try to remove entities from a collection but it doesn't work.

I think I have a mistake somewhere, but I don't know where.

Here the code from my updateAction:

    $em = $this->getDoctrine()->getEntityManager();

    $entity = new Person();

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Person entity.');
    }

    $editForm   = $this->createForm(new PersonType(), $entity);
    $deleteForm = $this->createDeleteForm($id);

    $request = $this->getRequest();

    $editForm->bindRequest($request);

    if ($editForm->isValid()) {
        $entity = $editForm->getData();

        $em->persist($entity);
        foreach($entity->getAddresses() as $address)
        {               
            $em->persist($address);
        }
        $em->flush();                                 

        return $this->redirect($this->generateUrl('person_show', array('id' => $id)));
    }

    return $this->render('AppPersonBundle:Person:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),

    );

Note that to remove my entity I remove the div from the html.

I mean I remove <div id="myapp_personbundle_persontype_address_4"> for example.

Is it the right way?


Solution

  • For now, i do :

        [...]        
        $editForm   = $this->createForm(new PersonType(), $entity);
        $deleteForm = $this->createDeleteForm($id);
    
        $previousCollections = array(
            'addresses' => $entity->getAddresses(),
        );        
    
        $request = $this->getRequest();
        $editForm->bindRequest($request);
    
        if ($editForm->isValid()) {
            $entity = $editForm->getData();
    
            $this->deleteCollections($em, $previousCollections, $entity);
    
            $em->persist($entity);
            foreach($entity->getAddresses() as $address)
            {               
                $em->persist($address);
            }
            $em->flush();                                 
    
            return $this->redirect($this->generateUrl('person_show', array('id' => $id)));
        }
        [...]
    }
    
    private function deleteCollections($em, $init, $final)
    {
        if (empty($init)) {
            return;
        }
    
        if (!$final->getAddresses() instanceof \Doctrine\ORM\PersistentCollection) {
            foreach ($init['addresses'] as $addr) {
                $em->remove($addr);
            }
        }
    }
    

    And I hope a solution will be found one day with https://github.com/symfony/symfony/issues/1540, but it slow to be found.