问题描述
我想在控制器中放置第二个删除按钮以删除注释,但是我收到了很多错误消息,例如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>
但是它会创建一条错误消息:
“无法猜测如何从参数的请求信息中获取Doctrine实例”注释。
解决方法
通常,如果您在功能签名中键入提示,Symfony会尝试将路由参数转换为实体automatically。例如,由于您不使用BlogPost
实体,因此可以编写:
/**
* @Route("/delete/{id}",name="comment_delete",methods={"DELETE"})
*/
public function deleteComment(Comment $comment): Response
您当然也应该在树枝函数中更改参数名称。
如果您想更明确一些,并保持原样的名称,为清楚起见,您可以编写:
/**
* @Route("/delete/{comment_id}",methods={"DELETE"})
* @ParamConverter("comment",options={"id" = "comment_id"})
*/
为了将route参数映射到列名。
您收到的错误是因为您写了options={"id": "id"}
告诉转换器使用url中的id
参数来查找实体,当然没有id
参数。