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

半城伤御伤魂 提交于 2019-12-01 07:17:05

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.

Thanks to this answer, I found a better solution. You can use Doctrine's orphan removal feature:

class Gallery
{
    //...    

    /**
     * @ORM\OneToMany(targetEntity="Photo", mappedBy="gallery", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    private $photos;

    //...

    public function removePhotos($photo)
    {
        $this->photos->remove($photo);
        $photo->setGallery(null);
    }
}
Amadu Bah

Form collection in symfony2 is quite straightforward, it does almost all the work for you. Basically you just need add a collection type and set allow_add, allow_delete flags and add a small JavaScript code. Have a look at the cookbook example

I'm using this solution...

In the controler:

$em = $this->getDoctrine()->getManager();
$enity->removeElements($em);

//Add all your elements again in order to update entity collection.
$entity->addElement($element) ...
....
$em->persist($entity);
$em->flush();

In the entity:

public function removeElements($em)
{
    $elements = $this->elements;

    foreach ($elements as $element) {
        $this->elements->removeElement($element);
        $em->remove($element);
        $em->persist($this);
    }

}

For me it works and it shows less code and I don't have to use the orphanRemoval feature.

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