Symfony2从表中删除记录

时间:2015-03-13 15:47:40

标签: php symfony doctrine

我的枝条中有一个按钮,我希望能够从表中删除记录。当我点击删除按钮时页面重新加载但没有记录被删除。

这是我的树枝

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

这是我的控制器。

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

1 个答案:

答案 0 :(得分:5)

$em->persist($adminentities); // This line will persist you entity again. 

所以你可以删除这一行,我认为没关系..另外,如果你保留这一行,每次按删除按钮时实体的ID都会改变

最后,您的代码将如下所示:

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

或者您可以直接将您的实体传递给方法(检查您的情况的语法):

public function admindeleteAction(Posted $posted)
{
   $em = $this->getDoctrine()->getEntityManager();

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

   return $this->render('BlogBundle:Default:admin.html.twig');
}

TWIG中的参数是一样的。