2015-03-13 16 views
1
刪除記錄

我在我的樹枝中有一個按鈕,我希望能夠從表中刪除記錄。當我點擊刪除按鈕頁面重新加載但沒有記錄被刪除。Symfony2從表

這裏是我的樹枝

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

回答

2
$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中的參數是一樣的。

+0

我應該在哪裏添加這個?在我調用flush方法之前,我已經堅持了它。沖水後? – g1bbles 2015-03-13 15:53:51

+0

你不必堅持實體,只需刪除並刷新它。 – djoosi 2015-03-13 15:54:33

+0

嗯我已經刪除了堅持行,但它仍然無法正常工作。有什麼建議麼? – g1bbles 2015-03-13 16:20:01