I have a button in my twig that I want to be able to delete a record from a table with.When I hit the delete button the page reloads but no record is deleted.
here is my twig
<h1>Admin Area - The football blog</h1>
 <table class="zebra">
 <thead> 
     <tr>
      <th>Title</th>
        <th>Date</th>       
        <th>Action</th>
     </tr>
   </thead> 
   <tbody> 
     <tr>
     {% for entity in adminentities %}
        <td>{{entity.postTitle}}</td>
        <td>{{ entity.postDescription }} </td>      
        <td> <a href="{{ path('deletepost', { 'id': entity.id })     }}">Delete</a> || Edit</td>
      </tr>
     {% endfor %}
     </tbody> 
 </table>
Here is my controller.
  /**
 * @Route("/posted/admin", name="deletepost")
 * @Template()
 */
public function admindeleteAction($id)
{
   $em = $this->getDoctrine()->getEntityManager();
   $adminentities = $em->getRepository('BlogBundle:posted')
                       ->findOneBy(array('post'=>$post->getId(),     'id'=>$id));
   $em->remove($adminentities);
    $em->persist($adminentities);
       $em->flush();                                                     
   return $this->render('BlogBundle:Default:admin.html.twig');
}
                $em->persist($adminentities); // This line will persist you entity again. 
So you can just delete this line and I think it's ok.. In addition, if you keep this line, the id of your entity changes each time you press delete button
Finally, your code will look like :
public function admindeleteAction($id)
{
   $em = $this->getDoctrine()->getEntityManager();
   $adminentities = $em->getRepository('BlogBundle:posted')->find($id);
   $em->remove($adminentities);
   $em->flush();   
   return $this->render('BlogBundle:Default:admin.html.twig');
}
Or you can directly pass your entity to the method (check the syntax for your situation) :
public function admindeleteAction(Posted $posted)
{
   $em = $this->getDoctrine()->getEntityManager();
   $em->remove($posted);
   $em->flush();   
   return $this->render('BlogBundle:Default:admin.html.twig');
}
And the param in TWIG is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With