【问题标题】:How to inject entity depencies into a controller in symfony 5.2?如何将实体依赖项注入 symfony 5.2 中的控制器?
【发布时间】:2021-05-21 20:21:50
【问题描述】:

我是 symfony 的初学者,我想将我的 post 实体注入到我的控制器的方法中。

但是,我触发了以下错误:

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

这是我的代码:

/**
 * @Route("/post/article/new", name="new.html.twig")
 * @param Request $request
 * @param Posts $posts
 * @return Response
*/
public function newArticle(Request $request, Posts $posts): Response
{
    $post = $posts;
    $article = new Articles();
    $post->setAuthor(1);
    $form =  $this->createForm(PostsType::class, $post);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()) {
        $this->em->persist($post);
        $this->em->flush();
        $article->setPost($post->getId());
        $themes = $form->get('themes')->getData();
        $article->setThemes(implode(',', $themes));
        $this->em->persist($post);
        $this->em->flush();

        return  $this->redirectToRoute('home.html.twig');
    }

    return $this->render('post/article.html.twig', [
        'formArticle' => $form->createView()
    ]);
}

【问题讨论】:

  • 将您的路由更改为 /post/{id}/article/new 并且 id 应该是 post id 以便参数转换器将获取与此 id 相关的 post 对象,或者您可以只传递id并自行搜索
  • 您要插入哪个实体? newArticle 听起来好像没有要插入的现有实体
  • 不太清楚。有PostArticle 实体,表单管理一个Post 实体。 Post 是新实体还是现有实体?
  • NicoHaase, jonas303, Post 是我想插入到我的数据库中的一个新实体。一篇文章是一篇文章,但具有文章实体没有的特定其他字段。事实上文章继承自帖子实体我的数据库结构。

标签: php symfony dependency-injection doctrine-orm


【解决方案1】:

您需要在路由中引用 Post,例如 id 或其他唯一字段的 slug。
@Route("/post/{id}/article/new", ...

否则 Symfony 不知道要加载哪个 Post。

【讨论】:

    猜你喜欢
    • 2011-11-27
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多