【问题标题】:symfony 3 form does not work with twig render(controller('...'))symfony 3 表单不适用于 twig 渲染(控制器('...'))
【发布时间】:2017-08-16 12:27:51
【问题描述】:

我想构建一个导航栏,显示在每个页面上。 因此我将以下代码添加到base.html.twig

{{ render(controller(
    'AppBundle:Navigation:index'
)) }}

但是 $form->isSubmitted() 返回 false$form->getData() 返回 null。这仅适用于上面的 twig-render 方式。如果我通过/navigation-route 正常打开 Navigation:index 页面,$form->isSubmitted() 返回true$form->getData() 返回表单数据。

这是导航控制器:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Language;
use Doctrine\ORM\EntityManagerInterface;
use AppBundle\Form\Type\NavigationType;
class NavigationController extends Controller
{
    /**
     * @Route("/navigation", name="navigation")
     */
    public function indexAction(Request $request, EntityManagerInterface $em)
    {
        $language = null;
        $form = $this->createForm(NavigationType::class);

        $form->handleRequest($request);
        dump($language);
        dump($form);
        if($form->isSubmitted() && $form->isValid())
        {
            dump('is valid');
        }
        $data = $form->getData();
        dump($data);
        dump('isSubmitted(): ' . $form->isSubmitted());
        dump($form->isSubmitted());

        // replace this example code with whatever you need
        return $this->render('navigation/index.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}

有人有解决方法吗?

【问题讨论】:

    标签: php forms symfony twig


    【解决方案1】:

    如果你嵌入了一个控制器,Symfony 会通过一个内部子请求来实现,这就是为什么 isSubmitted 为 false,而 getData 返回 null。

    如您所见,一种解决方法是传递原始请求。

    更好的选择是使用请求堆栈(可通过request_stack 服务 IIRC 获得)及其getMasterRequest 方法。

    【讨论】:

      【解决方案2】:

      好的,我现在找到了解决方法。需要手动使$request-object 可用

      找到方法here

      只需将 twig-code 更改为:

      {{ render(controller("SomeBundle:Foo:bar", {'request': app.request) }}
      

      并在动作函数中添加 $request 变量

      public function barAction($request) {
          // other your code
      }
      

      现在表单代码应该可以工作了。

      【讨论】:

      • 我也有类似的问题。我可以使用控制器或路由名称在 twig 中渲染,但我在目标控制器上使用的 knp 分页调用认为路由是渲染模板的控制器的路由,然后按上述方式调用渲染。
      猜你喜欢
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多