How do I delete an entity from symfony2

2019-02-02 02:17发布

问题:

My first symfony2 project is a list of guests (invited in an event) stored in a database. I have

  • created the entity class Guest with all variables for them (id, name, address, phone number etc.)
  • created the schema in the mysql db
  • created a route for "adding a guest" to a twig template
  • created a formType

and finally a "createGuest" method in the Controller and everything works fine.

I can't manage to remove a guest from the database. I have read every tutorial in the web, including the official Symfony2 book; all that it says is :

Deleting an Object

Deleting an object is very similar, but requires a call to the remove() method of the entity manager:

$em->remove($product);
$em->flush();

It does not say anything more than that (even the "Update an object" section is missing documentation) on how to connect the controller deleteAction($id) with the twig template. What I want to do is to list all guests with a viewGuests action and a viewGuests twig template, having a delete icon next to every row, which you should click to delete an entry. Simple, but I cannot find any documentation and do not know where to start from.

public function deleteGuestAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $guest = $em->getRepository('GuestBundle:Guest')->find($id);

        if (!$guest) {
            throw $this->createNotFoundException('No guest found for id '.$id);
        }

        $em->remove($guest);
        $em->flush();

        return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
    }

回答1:

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}) }}



回答2:

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();
            }
        }


回答3:

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.