首页 > 解决方案 > @paramconverter 注解 Symfony 找不到 App\Entity\Article 对象

问题描述

我在修改评论后尝试重定向但我有错误App \ Entity \ Article object not found by the @paramconverter annotation 你知道这个问题吗?

/**
 * @Route("/{id}/modifier", name="comment_edit", methods={"GET","POST"}, requirements={"id" = "\d+"})
 * @param Request $request
 * @param Article $article
 * @param Comment $comment
 * @param LinkRepository $linkRepository
 * @param MoreRepository $moreRepository
 * @return Response
 */
public function editComment(Request $request,Article $article, Comment $comment, LinkRepository $linkRepository,MoreRepository $moreRepository): Response
{
    $form = $this->createForm(CommentType::class, $comment);
    $form->handleRequest($request);
    
    if ($form->isSubmitted() && $form->isValid()) {
        $this->getDoctrine()->getManager()->flush();
        return $this->redirectToRoute('article_details',['id' => $article->getId()]);
    }
}   

标签: phpsymfony

解决方案


使用您的函数名称(editComment),您似乎正在传递idCommentid不是Article

在没有任何明确解释的情况下,Symfony 会尝试id在控制器参数 (an Article) 中找到您的第一个 Entity 的(您的 URL 参数的名称),但由于您似乎正在尝试修改 a ,所以找不到它Comment

由于您希望通过 URL 参数水合多个对象,因此您应该明确说明如何找到它们中的每一个:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;

/**
 * @Route("/{id_comment}/modifier", name="edit_comment")
 * @Entity("comment", expr="repository.find(id_comment)")
 * @Entity("article", expr="repository.findArticleByCommentID(id_comment)")
 */
public function editComment(Request $request, Article $article, Comment $comment, LinkRepository $linkRepository, MoreRepository $moreRepository): Response
{
    // ...

然后在您ArticleRepository的函数中创建一个名为findArticleByCommentID().

如果您只想$comment通过注释找到 ,您还可以执行以下操作:

/**
 * @Route("/{id_comment}/modifier", name="edit_comment")
 * @Entity("comment", expr="repository.find(id_comment)")
 */
public function editComment(Request $request, Comment $comment, LinkRepository $linkRepository, MoreRepository $moreRepository): Response
{
    // Notice there isn't any Article in the controller arguments
    $article = $comment->getArticle();
    // ...

更多关于参数转换的信息:https ://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html


推荐阅读