How to remove an object from symfony2

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

  • created an entity of the Guest class with all the variables for them (identifier, name, address, phone number, etc.).
  • created a schema in mysql db
  • created a route to add a "guest" to the branch template.
  • created formType

and finally, the createGuest method in the controller, and everything works fine.

I will not be able to remove the guest from the database. I read every tutorial on the Internet, including the official Symfony2 book; all he says:

Delete object

Removing an object is very similar, but requires calling the remove () method of the entity manager:

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

It does not say anything (even in the "Refresh Object" section there is no documentation) on how to connect the deleteAction ($ id) controller with the branch template. What I want to do is list all the guests using the viewGuests action and the twig viewGuests template, which has a delete icon next to each line that you have to click to delete the entry. Simple, but I canโ€™t find the documentation and donโ€™t know where to start.

 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')); } 
+42
symfony doctrine
Aug 04 2018-12-12T00:
source share
3 answers

Symfony is smart and knows how to do find() its own:

 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 an identifier to your controller, use {{ path('your_route', {'id': guest.id}) }}

+66
Aug 04 '12 at 16:01
source share
โ€” -

REMOVE 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(); } } 
+4
May 15 '15 at 8:27
source share

From what I understand, you are struggling with what to add to your template.

I will give 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, it iterates over each object inside the guests (you will have to rename it if your collection of objects is called differently!), Shows the name and puts the correct link. The name of the route may vary.

+2
Aug 04 '12 at 17:50
source share



All Articles