【发布时间】:2015-06-21 22:03:24
【问题描述】:
我正在制作一个菜单,我想让它尽可能地成为最好的方式。有问题的菜单将始终出现在我的网站中,因此,我为该菜单制作了一个树枝模板,并且每个页面都对其进行了扩展。
问题是,就我现在所拥有的而言,我的控制器每次使用该模板时都必须将表单传递给我的模板,因此这意味着我的所有控制器都需要重复创建表单并传递的代码它的形式。我不想要那个!
我坚持了,我坚持我可以创建一个服务,该服务将由我的 twig 模板调用,并且该服务将传递有问题的表单,我的模板将显示它。如果能做到这一点,那就意味着我的代码将在服务中编写一次并在模板中调用一次,这将是完美的。
但是,最大的问题是……我真的可以这样做吗?如果有可能我如何注册我的服务以在我的树枝中调用它,我如何在我的树枝中调用它,最后,因为它是一个表单,我可以在我的服务中使用表单上的 handleRequest() 函数并制作当有人提交该表单时页面会发生变化?
这是我现在拥有的代码:
树枝:
{% 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 %}
控制器:
<?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());
}
}
【问题讨论】: