Php 如何在Symfony的一个小树枝中使用2个表单?

Php 如何在Symfony的一个小树枝中使用2个表单?,php,mysql,symfony,doctrine,twig,Php,Mysql,Symfony,Doctrine,Twig,Im有两个实体:Post和Article。在我的TestController中,我有一个名为:addAction()的函数,我试图获取这两个实体并向它们添加一些数据,但当我在运行应用程序时尝试这样做时,表单成功提交,但这两个表(帖子和文章)是空的。为什么? 下面是我的addAction函数: public function addAction(Request $request) { $post = new Post(); $article = new Ar

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

下面是我的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()
        ));
    }
还有树枝:

{% 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 %}
{%extends'base.html.twig%}
{%block body%}
添加帖子
{{form_start(postForm)}
{{form_小部件(postForm)}
添加帖子
{{form_end(postForm)}

附加条款 {{form_start(articleForm)}} {{form_widget(articleForm)} 附加条款 {{form_end(articleForm)} {%endblock%}
您不能同时提交两份表格。因此,请逐个提交

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

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

我看到的第一个问题是,在一个包含两个表单的页面上提交一个表单将导致只发送该提交表单的数据,而不是同时发送两个表单的数据。如何解决该问题?尝试看看是否可以为两个实体创建一个表单。如果要在一种形式中使用其中的两个,我并不知道handleRequest()的结果(如果它知道如何将字段分配给实体的话)。这是最简单的解决办法