Symfony2 Delete record from table

12,725
$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.

Share:
12,725
g1bbles
Author by

g1bbles

Updated on June 04, 2022

Comments

  • g1bbles
    g1bbles almost 2 years

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