gpt4 book ai didi

php - 删除方法 Symfony

转载 作者:行者123 更新时间:2023-12-05 08:33:54 27 4
gpt4 key购买 nike

尝试创建删除方法后,我遇到了以下错误:

An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("id") to generate a URL for route "movie_delete".") in movies/index.html.twig at line 10.

我使用的代码: Twig 模板:

{% extends 'base.html.twig' %}

{% block body %}
{% if movies|length == 0 %}
There are no movie items available. Add a movie <a href="{{ path('movie_create_form') }}">here</a> to get started.
{% elseif movies|length != 0 %}
These are the results: <br />
<ul>
{% for x in movies %}
<li>Title: {{ x.title }} - Price: {{ x.price }} - <a href="#">Edit</a> - <a href="{{ path('movie_delete') }}{{ x.id }}"> Delete</a></li>
{% endfor %}
</ul>
<a href="{{ path('movie_create_form') }}">Add more movie entries</a>
{% endif %}
{% endblock %}

删除类:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

use AppBundle\Entity\Movie;

class MovieDeleteController extends Controller
{

public function deleteAction($id)
{
$em = $this->getDoctrine()->getManager();

if(!$id)
{
throw $this->createNotFoundException('No ID found');
}

$movie = $this->getDoctrine()->getEntityManager()->getRepository('AppBundle:Movie')->Find($id);

if($movie != null)
{
$em->remove($movie);
$em->flush();
}

return $this->redirectToRoute('movies');
}
}

还有我的routing.yml:

movie_delete:
path: /movies/delete/{id}
defaults: { _controller: AppBundle:MovieDelete:delete }

谁能解释我应该如何在 Symfony 中添加 Delete 方法,以便我可以在上面编写的代码中应用更改?

最佳答案

您忘记将“ID”变量传递给 twig 路由。

<a href="{{ path('movie_delete') }}{{ x.id }}"> Delete</a>

应该是

<a href="{{ path('movie_delete', {id: x.id}) }}"> Delete</a>

在您的“movie_delete”路由中,您定义了一个“id”参数。创建此路由需要此参数。在你的 Twig 文件中传递缺少的参数,你就完成了!

如果您也打算在“编辑”路线上工作,请记住您还需要一个“id”参数。确保像使用“删除”路由一样将其传递到您的 Twig 文件中。

参见:This Symfony documentation ,这里解释了 Twig 路由的附加参数。在您的情况下,'slug' 被替换为 'id'。

祝你好运!

关于php - 删除方法 Symfony,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35550737/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com