如何从symfony2中删除一个实体 [英] How do I delete an entity from symfony2
问题描述
我的第一个symfony2项目是存储在数据库中的客人列表(邀请在事件中)。我有
My first symfony2 project is a list of guests (invited in an event) stored in a database. I have
- 创建了具有所有变量的实体类Guest(id,name,address,phone number等)
- 在mysql数据库中创建模式
- 创建了一个添加访客的路线到树枝模板
- 创建一个formType
- created the entity class Guest with all variables for them (id, name, address, phone number etc.)
- created the schema in the mysql db
- created a route for "adding a guest" to a twig template
- created a formType
,最后在Controller中创建一个createGuest方法,一切正常。
and finally a "createGuest" method in the Controller and everything works fine.
我无法从数据库中删除来宾。我已经阅读了网络上的每个教程,包括官方的Symfony2书;它所说的是:
I can't manage to remove a guest from the database. I have read every tutorial in the web, including the official Symfony2 book; all that it says is :
删除对象
删除一个对象非常相似,但需要调用实体管理器的remove()方法:
$em->remove($product);
$em->flush();
它并没有说什么(甚至更新对象部分缺少文档)关于如何连接控制器deleteAction($ id)和树枝模板。我想做的是使用viewGuests操作和viewGuests twig模板列出所有guest虚拟机,每个行旁边都有一个删除图标,您应该点击删除一个条目。简单,但我找不到任何文件,不知道从哪里开始。
It does not say anything more than that (even the "Update an object" section is missing documentation) on how to connect the controller deleteAction($id) with the twig template. What I want to do is to list all guests with a viewGuests action and a viewGuests twig template, having a delete icon next to every row, which you should click to delete an entry. Simple, but I cannot find any documentation and do not know where to start from.
public function deleteGuestAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$guest = $em->getRepository('GuestBundle:Guest')->find($id);
if (!$guest) {
throw $this->createNotFoundException('No guest found for id '.$id);
}
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
推荐答案
Symfony很聪明,要使 find()
本身:
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
要发送控制器中的ID,请使用 { {path('your_route',{'id':guest.id})}}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
这篇关于如何从symfony2中删除一个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!