【发布时间】:2019-11-28 06:29:22
【问题描述】:
我有 2 个实体:文章、评论
每个都有自己的 FormType -> ArticleType, CommentType
要创建文章,我只是使用 ArticleType 创建一个表单。
对于评论,我使用我的 CommentType,但我还想修改文章中的一些信息。
例如:添加评论并能够更改文章类别。
这意味着我需要将 Article-Category 字段添加到我的 CommentType。既然有办法嵌入来完成表格。我想知道我是否只能嵌入表单的一部分。
文章类型:
$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(...);
}
谢谢。
【问题讨论】:
标签: forms symfony controller embed