Symfony 4 嵌入表单 - 仅嵌入部分
Symfony 4 Embed Forms - Embed Part Only
我有 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(...);
}
谢谢。
如果您想为类别选择现有文章。
你应该使用 EntityType : Link
使用参数,您可以在 select 中选择标签。
解决方案:我更改了我的 ArticleType 以使用默认的所有字段,但是当我使用特定选项时它只使用我需要的几个字段。
我有 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(...);
}
谢谢。
如果您想为类别选择现有文章。 你应该使用 EntityType : Link
使用参数,您可以在 select 中选择标签。
解决方案:我更改了我的 ArticleType 以使用默认的所有字段,但是当我使用特定选项时它只使用我需要的几个字段。