【问题标题】:Get form from rendered controller从渲染的控制器获取表单
【发布时间】:2014-07-14 15:24:02
【问题描述】:

我对 symfony2 有这样的问题。

我有 base.html.twig,这个 base 是其他树枝的模板。 我想渲染控制器,其中包含带有语言环境类型输入字段的表单。 该表格将用于更改网站的语言。

我的语言控制器:

<?php

namespace Soczewki\PlatformaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;


class LanguageController extends Controller {

  public function createAction(Request $Request)
    {

      $form = $this->createFormBuilder()
            ->setMethod('POST')
            ->setAction(null)
            ->add('locale', 'locale', array(
                'label'     => ' ',
                'choices'   => array('pl' => 'Polski', 'de' => 'Deutsch', 'en' => 'English'),
                'data' => $this->getRequest()->getLocale(),
                'required'  => true))
              ->add('submit', 'submit')
              ->getForm();

     $form->handleRequest($Request); 

     if($form->isValid()) {
         $this->getRequest()->setLocale('en');
     }

     return $this->render("SoczewkiPlatformaBundle::myForm.html.twig",
            array(
                'form' => $form->createView(),
                'req' => $r
            ));
    }


} 

整个base.html.twig:

<html>
    <head>
        <title>{% block pageTitle %}{% endblock %}</title>
        {#js#}
        <script src="{{ asset('bundles/soczewkiplatforma/js/jquery.js') }}"></script>
        <script src="{{ asset('bundles/soczewkiplatforma/js/bootstrap.js') }}"></script>
        {#/js#}   
        {% block stylesheets %}
            <link href="{{ asset('bundles/soczewkiplatforma/css/bootstrap.min.css') }}" rel="stylesheet">
            <link href="{{ asset('bundles/soczewkiplatforma/css/my-style.css') }}" rel="stylesheet">
        {% endblock stylesheets %}         

    </head>
    <body>



    {% if app.security.getToken().getUser().getAuthKey() is defined %}    
        {% if app.security.getToken().getUser().getAuthKey() is not empty %}
            {% set diff =  ( app.security.getToken().getUser().getEndDate()|date('U') - "now"|date('U') ) / 3600  %}
            <div style="width: 300px; height: 140px; position: absolute; bottom: 90px; right: 50px;" class="alert alert-danger alert-error">
            <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
            <strong>Uwaga!</strong> Twoje konto nadal nie zostało aktywowane!<br />
            Pozostało Ci: <span class="badge">{{ diff[0:2] }} godzin {{   ( diff[3:] * 60 )[0:2]   }} minut </span> 
            <br /><br />
            <a href="{{ url('soczewki_platofrma_account') }}#activate_form_auth_key"><button type="button" class="btn btn-danger">Wpisz kod</button></a>
            <button type="button" class="btn btn-default" data-dismiss="alert">Zamknij</button>
            </div>
        {% endif %}

        {% set hasParams = app.request.get('id') %}

        {% if hasParams is empty %}
            {% set currentPath = url( app.request.attributes.get( '_route', app.request.attributes.get('_route_params'))) %}
        {% else %}
            {% set currentPath = url( app.request.attributes.get( '_route', app.request.attributes.get('_route_params')),{'id': 0}   ) %}
        {% endif %}

        {% set dirs = currentPath|split('/') %}
        {% set flag = "" %}
        {% set url = "" %}

        <ol class="breadcrumb">
            <li><a href="{{ url('soczewki_platofrma_test') }}">Główna</a></li>  

            {% for key, dir in dirs %} 

                {% if url is not empty %}
                    {% set url = url ~ '/' ~ dir %}
                {% else %}
                    {% set url = url ~ dir %}
                {% endif %}
                {% if flag == true %}

                    {% if '=' in dir %}   
                        {% set _temp = dir|split('=') %}
                    {% else %}
                        {% set _temp = dir|split(' ') %}
                    {% endif %}

                    {% if key + 1 == dirs|length %}
                        <li class="active"> {{ _temp[0]|capitalize|replace('-',' ') }} </li> 
                    {% else %}
                        <li><a href="{{ url }}"> {{ _temp[0]|capitalize|replace('-',' ') }} </a></li> 
                    {% endif %}
                {% endif %}  
                {% if dir == 'app_dev.php' %}
                    {% set flag = true %}
                {% endif %}  
            {% endfor %}

            <li class="dropdown" style="float: right !important;">    
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Zalogowano jako: {{ app.security.getToken().getUser().getName() }} <span class="caret"></span></a>
                <ul class="dropdown-menu" role="menu">
                    <li><a href="{{ path('soczewki_platofrma_account') }}">Moje konteło</a></li> 
                    <li><a href="{{ path('logout') }}">Wyloguj</a></li>
                </ul>   
            </li>
        </ol>

    {% else %}           
        <ol class="breadcrumb">
            <li><a href="{{ url('soczewki_platofrma_test') }}">Główna</a></li>   
            <!--- logowanie --->
            <li class="dropdown" style="float: right !important;">    
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Zaloguj <span class="caret"></span></a>
                <div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px; left: -200px;">


                    <form action="{{ path('login_check') }}" method="post">
                    <label for="username">Email/NIP:</label>
                    <input type="text" id="username" name="_username" />
                    <br />

                    <label for="password">Hasełko:</label>
                    <input type="password" id="password" name="_password" />
                    <br /><br />

                    <button type="submit">Loguj do Afganistanu</button>
                    </form>

                </div>   
            </li>
            <!--- log ---->
        </ol>         
    {% endif %}  

     {{ render(controller('SoczewkiPlatformaBundle:Language:create')) }}

    {% block pageContainer %}

    {% endblock %}  

    </body>
</html>    

没有任何显示,我也收到任何错误。 为什么会这样?

// 代码更新

myForm.html.twig:

{{ dump(req) }}

{{ form(form) }}

和LocaleListener.php:

<?php
namespace Soczewki\PlatformaBundle\Translations;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'pl')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

【问题讨论】:

  • 你能发布“SoczewkiPlatformaBundle::base.html.twig”吗?为什么要检查 isset($form)?
  • 能否贴出base.html.twig文件的代码?

标签: forms symfony controller twig render


【解决方案1】:

你创造了一种情况,你无限次调用同一个方法,直到页面死掉。

正在渲染您的原始基础,最终渲染SoczewkiPlatformaBundle::base.html.twig 模板。在此模板中,render() 正在调用一个操作,然后该操作将渲染 SoczewkiPlatformaBundle::base.html.twig 模板,然后该模板调用 render(),然后再渲染 SoczewkiPlatformaBundle::base.html.twig,然后继续……

您需要为要呈现的表单指定一个模板而不是基础模板,然后在您的changeAction 中调用它。

例如...

Soczewki\PlatformaBundle\Controller\LanguageController

public function changeAction(Request $Request)
{
    // ..

    return $this->render("SoczewkiPlatformaBundle:Locale:change_form.html.twig",
        array(
            'form' => isset($form) ? $form->createView() : null,
        ));
}

SoczewkiPlatformaBundle:Locale:change_form.html.twig

{{ form_start(form, {'method': 'POST', 'action': 'your_locale_change_route' }) }}
    {{ form_row(form.locale) }}
{{ form_end(form) }}

您的下一个问题是您的 changeAction 实际上并没有执行操作(除了创建表单),尽管您可能只是希望在您进入该部分之前显示该页面。

【讨论】:

  • 好的,我将表单传递给新树枝,然后尝试嵌入:{% embed "SoczewkiPlatformaBundle::myForm.html.twig" %} {% endembed %} 然后显示在新树枝中,但现在我得到:变量“表单”不存在SoczewkiPlatformaBundle::myForm.html.twig 在第 1 行
  • 谁说要使用embed?你也是render(controller()),只是改变渲染的模板。
  • 但是现在我在更改语言环境时遇到了问题...代码已更新。
  • 老实说,我会在一个单独的问题中提出所有问题。 'req' =&gt; $r 是什么?是请求还是什么?您可以使用app.request 在模板中获取请求。你的
【解决方案2】:

您需要将此代码添加到您希望表单出现的位置

{{ form(form) }}

在下面的cmets之后编辑;

创建一个名为 myForm.html.twig 的文件并放入 SoczewkiPlatformaBundle;
现在在里面写下这段代码:

{{ form(form) }}

现在你的控制器应该是:

public function changeAction(Request $Request)
    {


      $form = $this->createFormBuilder()
            ->add('locale', 'locale', array(
                'label'     => 'user.locale',
                'required'  => true,
                'choices'   => array('en' => 'English', 'de' => 'Deutsch', 'pl' => 'Polish')
                                ))
                    ->getForm();

     $form->handleRequest($Request); 


     return $this->render("SoczewkiPlatformaBundle::myForm.html.twig",
            array(
                'form' => $form->createView(),
            ));


    }

【讨论】:

  • 有:[2014-07-14 17:47:15] event.DEBUG:通知事件“kernel.controller”到监听器“Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController” . [] []
  • 查看编辑后的答案。您的日志是否包含该行以外的任何内容?
  • 这不是我问题的答案...我可以将表单传递给视图,但我想将带有表单的控制器渲染到基本视图,因为我有很多视图。并且表格是为改变语言而设计的
  • 你犯了一个概念错误;您在基础内调用 {{ render(controller('SoczewkiPlatformaBundle:Language:change')) }} ,但此控制器也渲染基础。这会导致无限循环!这就是我发布此解决方案的原因
  • 你试过我的解决方案了吗?
猜你喜欢
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
相关资源
最近更新 更多