Symfony 5 Delete 方法,无法猜测如何从参数的请求信息中获取 Doctrine 实例

Symfony 5 Delete methods, Unable to guess how to get a Doctrine instance from the request information for parameter

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

所以在我的控制器中我有一个这样的 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>

但它创建了一条错误消息:

"Unable to guess how to get a Doctrine instance from the request information for parameter" comment ".

通常,如果您在函数签名中键入提示,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 参数.