【问题标题】:How to use 2 forms in 1 twig in Symfony?如何在 Symfony 的 1 个树枝中使用 2 个表单?
【发布时间】:2017-10-18 20:39:33
【问题描述】:

我有 2 个实体:PostArticle。在我的 TestController 中,我有一个名为:addAction() 的函数,我在其中尝试获取这两个实体并向它们添加一些数据,但是当我尝试执行此操作时我运行我的应用程序,表格已成功提交,但 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()
        ));
    }

还有树枝:

{% 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 %}

【问题讨论】:

  • 我看到的第一个问题是,在包含 2 个表单的页面上提交一个表单将导致只为该提交的表单发送数据 - 而不是两个。
  • 问题如何解决?
  • 尝试查看是否可以为两个实体创建一个表单。如果您打算以一种形式使用其中的 2 个(如果它知道如何将字段分配给实体),我真的不知道 handleRequest() 的结果。
  • 您可以在 twig symfony.com/doc/current/templating/embedding_controllers.html 中渲染控制器。这是最简单的解决方案

标签: php mysql symfony doctrine twig


【解决方案1】:

您不能同时提交两个表单。因此,请一一提交

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

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

【讨论】:

    猜你喜欢
    • 2018-08-16
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 2023-03-06
    • 2022-01-02
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多