如何在 Symfony 的 1 个树枝中使用 2 个表单?

Rum*_*hev 2 php mysql doctrine symfony twig

我有 2 个实体:PostArticle。在我的TestController 中,我有一个名为addAction()的函数,其中我试图获取这 2 个实体并向它们添加一些数据,但是当我在运行我的应用程序时尝试执行此操作时,表单已成功提交,但是 2表格(帖子和文章)是空的。为什么 ?

这是我的 addAction 函数:

public function addAction(Request $request)
    {
        $post = new Post();
        $article = new Article();

        $postForm = $this->createForm(PostType::class, $post);
        $articleForm = $this->createForm(ArticleType::class, $article);

        $postForm->handleRequest($request);
        $articleForm->handleRequest($request);

        if ($postForm->isValid() && $articleForm->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $em->persist($post);
            $em->persist($article);

            $em->flush();
        }
        return $this->render('add/add.html.twig', array(
            'postForm' => $postForm->createView(),
            'articleForm' => $articleForm->createView()
        ));
    }
Run Code Online (Sandbox Code Playgroud)

和树枝:

{% extends 'base.html.twig' %}

{% block body %}
    <div style="text-align: center;">
        <div class="container">
            <h1>Add Post</h1>
            {{ form_start(postForm) }}
                {{ form_widget(postForm) }}
                <button class="btn btn-primary" type="submit">Add Post <span class="glyphicon glyphicon-plus"></span></button>
            {{ form_end(postForm) }}
        </div>
    </div>
    <hr>
    <div style="text-align: center;">
        <div class="container">
            <h1>Add Article</h1>
            {{ form_start(articleForm) }}
            {{ form_widget(articleForm) }}
            <button class="btn btn-primary" type="submit">Add Article <span class="glyphicon glyphicon-plus"></span></button>
            {{ form_end(articleForm) }}
        </div>
    </div>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

Dan*_*nel 5

您不能同时提交两个表格。所以,相反,将它们一一提交

$postForm->handleRequest($request);
if ($postForm->isSubmitted() && $postForm->isValid()) {
    // persist and flush $post
}

$articleForm->handleRequest($request);
if ($articleForm->isSubmitted() && $articleForm->isValid()) {
    // persist and flush $article
}
Run Code Online (Sandbox Code Playgroud)