【问题标题】:Symfony 5 Delete methods, Unable to guess how to get a Doctrine instance from the request information for parameterSymfony 5 Delete方法,无法猜测如何从参数的请求信息中获取Doctrine实例
【发布时间】:2021-01-20 16:35:05
【问题描述】:

我想在我的控制器中添加第二个删除按钮来删除 cmets,但我收到了很多错误消息,例如来自 ParamConverter 的错误消息,因为它无法识别类。

所以在我的控制器中,我有一个这样的 ParamConverter:

/**
     * @Route("/delete/{comment_id}", name="comment_delete", methods={"DELETE"})
     * @ParamConverter("comment", class="App:Comment", options={"id": "id"})
     */
    public function deleteComment(Request $request, BlogPost $blogPost, Comment $comment, $comment_id): Response
    {
        if ($this->isCsrfTokenValid('delete' . $comment->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($comment);
            $entityManager->flush();
            return $this->redirectToRoute('/');
        }


        return $this->render('comments/_delete_form.html.twig', [
            'comment' => $comment
        ]);
    }

在我的树枝上,我添加了这个:

<form method="post" action="{{ path('comment_delete', {'comment_id': comment.id}) }}" onsubmit="return confirm('Are you sure you want to delete this item?');">
    <input type="hidden" name="_method" value="DELETE">
    <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ comment.id) }}">
    <button class="btn delete">Delete</button>
</form>

但它会产生错误消息:

“无法从参数“comment”的请求信息中猜测如何获取Doctrine实例。

【问题讨论】:

  • 我认为你的逻辑有些奇怪,因为你是从另一个动作中做出来的。很难说到底是什么,没有你的实体,但我猜你不需要大部分函数参数,因为我猜你可以从$comment-&gt;getPost() 中得到BlogPost,从@ 中得到comment_id 987654328@。从那里开始,你不再需要任何复杂性,你可以去:* @Route("/delete/{id}", name="comment_delete", methods={"DELETE"}) 并让魔法 ParamConvert 作用于函数 public function deleteComment(Comment $comment) { 的签名
  • 谢谢你!我的 ParamConverter 错误主要来自我的 redirectToRoute。
  • 为什么在路由定义中调用该参数comment_id,在ParamConverter 的注解中调用id?另外,请不要使用不相关的标签——对我来说,与sql-deletetwig 没有关系

标签: php symfony parameters twig sql-delete


【解决方案1】:

通常,如果您在函数签名中输入提示,Symfony 将尝试将路由参数转换为实体automatically。例如,由于您不使用 BlogPost 实体,您可以只写:

/**
 * @Route("/delete/{id}", name="comment_delete", methods={"DELETE"})
 */
public function deleteComment(Comment $comment): Response

当然,您也应该在 twig 函数中更改参数名称。

如果您想更明确并保持参数名称不变,为清楚起见,您可以这样写:

/**
 * @Route("/delete/{comment_id}", name="comment_delete", methods={"DELETE"})
 * @ParamConverter("comment", options={"id" = "comment_id"})
 */

为了将路由参数映射到列名。

你收到的错误是因为你写了options={"id": "id"}告诉转换器通过在url中使用id参数来查找实体,当然没有id参数。

【讨论】:

  • 谢谢 β.εηοιτ.βε 和 msg
猜你喜欢
  • 2019-08-05
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 2012-04-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
相关资源
最近更新 更多