简体   繁体   English

如何在我的树枝模板中调用服务以使用Symfony 2创建表单

[英]How to call a service in my twig template to create a form with Symfony 2

I'm working on a menu and I want to make it the best way as possible. 我正在处理菜单,所以我希望使其成为最佳方法。 The menu in question will always appear in my site, therefore, I made a twig template for that menu and each page extends it. 有问题的菜单将始终出现在我的站点中,因此,我为该菜单制作了一个树枝模板,并且每个页面都对其进行了扩展。

The thing is that, with what I have right now, my controller must pass the form to my template each time it use that template, therefore it means that all my controllers will need to repeat the code that creates the form and pass it to the form. 事实是,根据我现在拥有的内容,控制器每次使用该模板时都必须将表单传递给模板,因此这意味着我的所有控制器都需要重复创建表单的代码并将其传递给模板。形成。 I don't want that! 我不要那个!

I tought about it and I tought I could create a services that would be called by my twig template and that services would pass the form in question and my template will juste show it. 我对此深信不疑,我可以创建一个服务,该服务将由我的树枝模板调用,并且该服务将通过有问题的表单,并且我的模板将显示它。 If could do that, it would mean that my code would be written once in a service and called once in the template, witch would be perfect. 如果能够做到这一点,那意味着我的代码将在服务中编写一次,并在模板中调用一次,witch将是完美的。

But, the big question... Can I actually do that? 但是,一个大问题……我真的可以这样做吗? And if it is possible how do I register my services to be callable in my twig, how do I call it in my twig and finally, since it's a form, could I use the handleRequest() function on the form in my service and make the page change when someone submit that form? 如果有可能如何在树枝中注册可调用的服务,又如何在树枝中调用它,最后,由于它是一种表单,我可以在服务中的表单上使用handleRequest()函数并生成有人提交表单时页面会更改吗?

Here is the code I have right now: 这是我现在拥有的代码:

Twig: 枝条:

{% extends  "::base.html.twig"%}

{# Feuilles de style de la page #}
{% block stylesheets %}

    <link href="{{ asset("bundles/admin/css/main.css") }}" type="text/css" rel="stylesheet" />

{% endblock %}

{# Contenu de la balise Body #}
{% block contenu_body %}

    <header>
        <a href="{{ path("deconnexion") }}">
            <img src="{{ asset("bundles/admin/images/deconnexion.png") }}" alt="Déconnexion" />
        </a>
    </header>
    <main>
        <nav>
            {{ form_start(formulaire) }}
                {{ form_widget(formulaire.Ajouter) }}
                {{ form_widget(formulaire.projet) }}
                {{ form_row(formulaire.modifier) }}
                {{ form_row(formulaire.supprimer) }}
            {{ form_end(formulaire) }}
        </nav>
        <section>

        </section>
    </main>

{% endblock %}

controller: 控制器:

<?php

namespace AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Form\ModifierSupprimerProjet;

class AdminController extends Controller
{
  public function indexAction(Request $request)
  {
    //Gets the list of my projects
    $listeProjets=$this->container->get('portfolio')->chercherListeProjets();      

    //Form to select to modify, delete or add a project
    $formulaire=$this->createForm(new ModifierSupprimerProjet(), null, array('choix' => $listeProjets, ));


    $formulaire->handleRequest($request);

    //If valid
    if($formulaire->isValid())
    {

      if($formulaire->get('Ajouter')->isClicked())
      {
        echo 'add';
      }


      if($formulaire["projet"]->getData()!=='')
      {

        if($formulaire->get('modifier')->isClicked())
        {
          echo $formulaire["projet"]->getData();
        }

        else if($formulaire->get('supprimer')->isClicked())
        {
          echo $formulaire["projet"]->getData();
        }
      }
    }

    return $this->render('AdminBundle::admin.html.twig', array(
                                                                'formulaire'=>$formulaire->createView()
                                                              ));
  }

  public function testAction()
  {
    return $this->render('AdminBundle::admin.html.twig', array());
  }
}

You should start by making sure that you really have to use a form to do the manipulations that you are trying to do. 首先,请确保您确实必须使用表单来执行您要尝试的操作。 Maybe using a link to a page with the form would suffice. 也许使用带有表单的页面链接就足够了。

But this doesn't not answer your question so here goes: Since the form will be used on every page it should be placed in your main template, in this case the base.html.twig . 但这并不能回答您的问题,因此请按以下步骤进行:由于该表单将在每个页面上使用,因此应将其放置在您的主模板中,在本例中为base.html.twig In fact, the content in the <main> and <header> tags should be moved to your base template. 实际上, <main><header>标记中的内容应移至base模板。 Then, you should add an action in your controller which handles the form or just rename the indexAction giving it a name more related to what you are trying to accomplish. 然后,您应该在控制器中添加一个处理该表单的操作,或者只是重命名indexAction ,使其名称与您要完成的操作更相关。 After, you will move the code from the form in another template without any of you block tags. 之后,您将代码从表单移到另一个模板中,而没有任何块标记。

menu.html.twig menu.html.twig

{{ form_start(formulaire) }}
    {{ form_widget(formulaire.Ajouter) }}
    {{ form_widget(formulaire.projet) }}
    {{ form_row(formulaire.modifier) }}
    {{ form_row(formulaire.supprimer) }}
{{ form_end(formulaire) }}

controller 调节器

use Symfony\Component\HttpFoundation\Request;

class AdminController extends Controller
    ...

    public function menuAction() {
        $request = Request::createFromGlobals();

        // code that was in the indexAction

        return $this->render('AdminBundle::menu.html.twig', array(
            'formulaire'=>$formulaire->createView()
        ));
    }
}

In your base you will render the action. 在您的基地中,您将渲染动作。

base.html.twig base.html.twig

{{ render(controller('AdminBundle:Admin:menu')) }}

You can also find more documentation on this page: http://symfony.com/doc/current/book/templating.html 您也可以在此页面上找到更多文档: http : //symfony.com/doc/current/book/templating.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM