Symfony 4嵌入表格-仅嵌入部分

时间:2019-07-19 09:24:22

标签: forms symfony controller embed

我有2个实体:文章,评论

每个都有自己的FormType-> ArticleType,CommentType


要创建文章,我只是使用ArticleType创建一个表单。

对于注释,我使用我的CommentType,但我也想修改文章中的一些信息。

例如:添加评论并能够更改文章类别。

这意味着我需要将Article-Category字段添加到我的CommentType中。由于有嵌入完整表格的方法。我想知道我是否只能嵌入表格的一部分。

ArticleType:

$builder->add('headline', TextType::class, [ ... ])
        ->add('text', TextType::class, [ ... ])
        ->add('category', EntityType:class, [ ... ])

评论类型:

$builder->add('article', ArticleType::class, [ ... ])
//adds all fields of ArticleType, but only want the category field

是否有任何方法可以解决此问题,而不必从我的ArticleType中添加类别部分? (防止代码重复)。

我还想知道控制器对于我的情况如何。 现在,我使用以下代码,可能需要改进:

/**
 * @Route("/article/{id}", name="app_article")
 */
public function article(Request $request, Article $article)
{
    $comment = new Comment();
    $comment->setArticle($article); //to modify current article values

    $form = $this->createForm(CommentType::class, $comment);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $tmpArticle = $comment->getArticle(); //if I don't get the article from my comment, doctrine/symfony creates a *new* Article - which I dont want
        $article->setCategory($tmpArticle->getCategory());

        $em->persist($comment);
        $em->persist($article);
        $em->flush();

        return $this->redirectToRoute(...);
    }

    return $this->render(...);
}

谢谢。

2 个答案:

答案 0 :(得分:0)

如果要为类别选择现有文章。 您应该使用EntityType:Link

使用参数,您可以在select中选择标签。

答案 1 :(得分:0)

解决方案:我将ArticleType更改为默认使用所有字段,但是当我使用特定选项时,它仅使用了我需要的几个字段。