Symfony2从表中删除记录 [英] Symfony2 Delete record from table
本文介绍了Symfony2从表中删除记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个按钮,我想要从表中删除一个记录。当我点击删除按钮的页面重新加载,但没有记录被删除。
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.
这里是我的树枝
<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');
}
推荐答案
$em->persist($adminentities); // This line will persist you entity again.
所以你可以删除这一行,我认为没关系..另外,如果你保持这个行,您的实体的ID每次按删除按钮更改
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');
}
TWIG中的参数是一样的。
And the param in TWIG is the same.
这篇关于Symfony2从表中删除记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文