Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Delete record from table

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');
}
like image 711
g1bbles Avatar asked Mar 16 '23 18:03

g1bbles


1 Answers

$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.

like image 77
djoosi Avatar answered Mar 27 '23 16:03

djoosi