2014-07-14 4 views
-1

symfony2에 이와 같은 문제가 있습니다.렌더링 된 컨트롤러에서 양식 가져 오기

저는 base.html.twig가 있고이베이스는 다른 나뭇 가지를위한 템플릿입니다. locale-type 입력 필드가있는 양식을 포함하는 컨트롤러를 렌더링하려고합니다. 이 양식은 사이트 언어를 변경하는 데 사용됩니다.

내 LanguageController :

<?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)), 
     ); 
    } 
} 
+0

"SoczewkiPlatformaBundle :: base.html.twig"를 게시 할 수 있습니까? 왜 isset ($ form)을 확인합니까? – Filo

+0

base.html.twig 파일의 코드를 게시 할 수 있습니까? – Filo

+0

예, 방금 업데이트되었습니다. – r3m4k3

답변

0

당신은 같은 방법을 시간의 무한한 양을 호출하는 상황을 만들었습니다

{{ form(form) }} 

이제 컨트롤러가 있어야한다 :
지금 내부에이 코드를 작성 .

원래 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 실제로 양식을 작성에서 떨어져 작업을 (수행되지 않는다는 것), 비록 당신이 그 부분에 도달하기 전에 그 페이지가 보여 지길 바랄 수도 있습니다.

+0

좋아요, 양식을 새 나뭇 가지로 전달한 다음 삽입하려고 시도했습니다. {% embed "SoczewkiPlatformaBundle :: myForm.html.twig"%} {% endembed %} "그런 다음 새로운 나뭇 가지에 표시되지만 지금은 내가 받고있어 : Variable "form"이 SoczewkiPlatformaBundle :: myForm.html.twig 1 호선에 존재하지 않는다. – r3m4k3

+0

누가 임베드를 사용하겠다고 말 했는가? 같은'render (controller())'를 사용하면 렌더링 된 템플릿을 변경하면됩니다. – qooplmao

+0

작동. 감사! :) – r3m4k3

0

{{ form(form) }} 

아래의 댓글 이후에 편집 됨.

myForm.html.twig라는 파일을 만들고 SoczewkiPlatformaBundle에 넣습니다. 페이지 그냥 죽을 때까지

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(), 
      )); 


    } 
+0

같은 페이지가 아직로드되지 않습니다. 오류가 발생했습니다 – r3m4k3

+0

로그를 보려고 했습니까? (app/logs) – Filo

+0

있습니다 : [2014-07-14 17:47:15] event.DEBUG : 리스너 "Sensio \ Bundle \ FrameworkExtraBundle \ EventListener \ TemplateListener :: onKernelController"에 "kernel.controller"이벤트를 알립니다. [] [] – r3m4k3

관련 문제