How do I delete an entity from symfony2 How do I delete an entity from symfony2 symfony symfony

How do I delete an entity from symfony2


Symfony is smart and knows how to make the find() by itself :

public function deleteGuestAction(Guest $guest){    if (!$guest) {        throw $this->createNotFoundException('No guest found');    }    $em = $this->getDoctrine()->getEntityManager();    $em->remove($guest);    $em->flush();    return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));}

To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}


DELETE FROM ... WHERE id=...;

protected function templateRemove($id){            $em = $this->getDoctrine()->getManager();            $entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));            if ($entity != null){                $em->remove($entity);                $em->flush();            }        }


From what I understand, you struggle with what to put into your template.

I'll show an example:

<ul>    {% for guest in guests %}    <li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>    {% endfor %}</ul>

Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.