如何从 symfony2 中删除实体 [英] How do I delete an entity from symfony2

查看:16
本文介绍了如何从 symfony2 中删除实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个 symfony2 项目是存储在数据库中的来宾列表(受邀参加活动).我有

My first symfony2 project is a list of guests (invited in an event) stored in a database. I have

  • 创建了实体类Guest,其中包含所有变量(id、姓名、地址、电话号码等)
  • 在 mysql 数据库中创建了架构
  • 为树枝模板添加客人"创建了一条路线
  • 创建了一个表单类型

最后是控制器中的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) 与 twig 模板连接起来(甚至更新对象"部分也缺少文档).我想要做的是使用 viewGuests 操作和 viewGuests 树枝模板列出所有来宾,每行旁边都有一个删除图标,您应该单击它来删除一个条目.很简单,但我找不到任何文档,也不知道从哪里开始.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆