简体   繁体   English

symfony2 - 如何在每个页面中全局检索数据库中的数据

[英]symfony2 -How to retrieve data from database globally in every page

I want to retrieve Cities names from a table in the database and put them as options in a select input (combobox) which is defined in 'layout.html.twig' . 我想从数据库中的表中检索Cities名称,并将它们作为选项放在“layout.html.twig”中定义的选择输入(组合框)中。 All my views extends 'layout.html.twig', so how can I access to cities names in every page? 我的所有观点都扩展了'layout.html.twig',那么如何在每个页面中访问城市名称?

[Solution] [解]

I'm not able to respond to my topic ,I didn't have much reputation so I edit my topic 我无法回复我的主题,我没有太多的声誉所以我编辑我的主题

I have found the solution, using "embedding controllers" 我找到了解决方案,使用“嵌入式控制器”

  • first I've created an action to retreive all cities names: 首先,我创建了一个动作来检索所有城市名称:

     public function listCitiesAction(){ // retreiving cities $entities = $this->getDoctrine()->getRepository("MedAdBundle:City")->findAll(); return $this->render('MedAdBundle:Ville:list_cities.html.twig', array('entities' => $entities)); } 
  • this action render list_cities.html.twig defined as : 此动作将list_cities.html.twig定义为:

     <select class="form-control"> {% for entity in entities %} <option>{{ entity.name}}</option> {% endfor %} </select> 
  • finnaly I edit my layout.html.twig finnaly我编辑我的layout.html.twig

     <div> {{ render(controller('MedAdBundle:City:listCities'))}} </div> 

In this way I can access to cities combobox in every page in my app ;) 通过这种方式,我可以在我的应用程序的每个页面中访问城市组合框;)

Another nice way would be use render . 另一个好方法是使用渲染

This allows you to call a controller out of your layout.html.twig 这允许您从layout.html.twig调用控制器

{{ render(controller("AcmeDemoBundle:Helper:citySelector")) }}

you also can cache the output with ESI . 您也可以使用ESI缓存输出。

I would go with these steps: 我会采取这些步骤:

  • Write a form hosting a symfony entity field configured to work with the Cities table 编写一个托管symfony实体字段的表单,该字段配置为使用Cities表
  • Define this form as a service in the DIC 将此表单定义为DIC中的服务
  • Define a twig extension that exposes a function to output the form HTML 定义一个twig扩展,公开一个函数以输出表单HTML
  • Use the twig function in the layout.html.twig that is extended by all the other templates 使用layout.html.twig中的twig函数,该函数由所有其他模板扩展

As an optimization I would look how I could wire Doctrine with some caching system (eg memcached) to avoid hitting the database on each page load. 作为优化,我将看看如何将Doctrine与一些缓存系统(例如memcached)连接起来,以避免在每次页面加载时访问数据库。

This is where you can find documentation about the entity field: http://symfony.com/doc/current/reference/forms/types/entity.html 您可以在此处找到有关实体字段的文档: http//symfony.com/doc/current/reference/forms/types/entity.html

Use the Symfony documentation to find how to define a form as a service and how to write your own twig extension. 使用Symfony文档查找如何将表单定义为服务以及如何编写自己的twig扩展。

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

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