【问题标题】:Why my action is not loaded when I click on a button?为什么单击按钮时未加载我的操作?
【发布时间】:2016-01-21 19:35:15
【问题描述】:

我想创建一个删除学生的按钮。但是我有一个问题,我的按钮没有在我的控制器中启动 deleteAction。

我的控制器:

public function deleteAction(Eleve $id, $schoolId)
{
    $repository = $this->getDoctrine()->getManager()->getRepository('WCSCantineBundle:Lunch');
    $pupil = $repository->findOneBy(array(
        'eleve' => $id
    ));
    $em = $this->getDoctrine()->getManager();
    $em->remove($pupil);
    $em->flush();

    return $this->redirect($this->generateUrl('wcs_cantine_todayList', array('schoolId' => $schoolId)));
}

我的路线:

delete_pupil:
path:     /
defaults: { _controller: "WCSCantineBundle:CanteenManager:delete" }

我的按钮(在我看来):

<a href="{{ path('delete_pupil', { 'id': lunch.eleve.id, 'schoolId': ecole.id }) }}">Désinscrire</a>

感谢您的帮助。

【问题讨论】:

  • 我想,您在路线中忘记了WCSCantineBundle:CanteenManager:delete 末尾的“Action”一词。
  • 我会尝试,但通常它不会像这样的路线:wcs_cantine_todayList:路径:/todayList/{schoolId} 默认值:{ _controller: "WCSCantineBundle:CanteenManager:todayList" } 启动 todayListAction
  • 是的,你是对的。 Action 是自动附加的(多么奇怪的脚本语言)。你检查过,如果你删除参数,方法deleteAction是否被调用?
  • @MartinZabel 在 Symfony2 中,路由由 logical groupings 定义,为简洁起见,这些分组中的类和方法名称的后缀被省略。所以WCSCantineBundle:CanteenManager:delete的逻辑名指的是WCSCantine包中CanteenManagerController类的deleteAction方法。
  • 当您单击按钮访问您的路线时,会收到什么具体错误?

标签: symfony controller onclick action


【解决方案1】:
public function deleteAction(Eleve $id, $schoolId)
{
    $em = $this->getDoctrine()->getManager();
    $pupil = $em->getRepository('WCSCantineBundle:Lunch')->findOneBy(array('eleve' => $id));

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

    return $this->redirect($this->generateUrl('wcs_cantine_todayList', array('schoolId' => $schoolId)));
}

您的代码失败,因为学说实体管理器不知道 $pupil 是什么,因为有两个不同的实体管理器实例,上面的代码是删除瞳孔的简写,但您可以根据需要更改它,只要实体经理“了解”实体

【讨论】:

  • 您可能是对的,但实际的代码差异在哪里?您将$this-&gt;getDoctrine()-&gt;getManager() 的结果保存到变量em 中,以便以后再次使用它。但是,然后您以与 OP 相同的方式检索了 pupil
  • OP 两次创建实体管理器,第一个知道 $pupil,第二个不知道,第二个调用了 flush(),因此删除函数对数据库没有影响
【解决方案2】:

我做到了,它有效。

我的控制器:

public function deleteAction($id, $schoolId)
{
    $dateNow = new \DateTime();
    $em = $this->getDoctrine()->getManager();
    $lunches = $em->getRepository('WCSCantineBundle:Lunch')->findBy(array(
        'eleve' => $id,
        'date' => $dateNow
    ));
    foreach ($lunches as $lunch) {
        $em->remove($lunch);
    }
    $em->flush();

    return $this->redirect($this->generateUrl('wcs_cantine_todayList', array('schoolId' => $schoolId)));
}

我的路线:

delete_pupil:
path:     /todayList/{schoolId}/{id}
defaults: { _controller: "WCSCantineBundle:CanteenManager:delete" }
methods: [GET, DELETE]

我的看法:

<a href="{{ path('delete_pupil', {'id': lunch.eleve.id, 'schoolId': ecole.id }) }}">Désinscrire</a>

我错过了在我的路线中用斜杠传递我的论点:/todayList/{schoolId}/{id} 感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多