Perform merge between views of two or more modules - php

I have a Phalcon PHP modular application. I am making an administrative interface to control which modules should be used in the system.
One module controls the application's default interface, while the other modules add functionalities.
I have the problem: when another module to enabled, it can add the HTML content to the other interface control module. In this way I would like to merge two or more views. I am using Volt as template engine.
Is this possible in Phalcon?

Note: This was asked on the official Phalcon forums. I answered it over there and it got accepted. I am just mirroring my answer so future readers can get an answer here without being redirected from StackOverflow. Phalcon forum mirror: https://forum.phalconphp.com/discussion/15891/perform-merge-between-views-of-two-or-more-modules
config.php
You will need to define your modules in the app/config/config.php file like so;
return new \Phalcon\Config([
// ...
'modules' => [
'module01',
'module02',
...
'moduleN',
],
// ...
]);
*Controller.php
Then, in your controller, you'd set a view property to store the active modules like so;
$this->view->modules_enabled = $this->di->get("config")->modules;
*.volt
And finally in your volt file, just check the module is in the array holding active modules, and if so, display the view using partials.
{% if module01 in modules_enabled %}
<div id="module">{{ partial("partials/module01") }}</div>
{% endif %}

Related

Zend expressive - Layout

In my layout (Twig), i'd like to retrieve a value from a Middleware authentication.
If i put, in templates.global.pĥp:
'twig' => [
'globals' => [
// Variables to pass to all twig templates
'auth' => (new \Zend\Authentication\AuthenticationService())->hasIdentity(),
],
],
And in layout default.html.twig
{% if auth %}
Connect
{% else %}
Not connect
{% endif %}
This code works, but, is it a good method ?
Thank you :)
It's not a good method. First of all, using the config files to set global template data is meant for static data. Creating a service in the config will fail if you want to cache the config. I don't know about the zend auction service, but it would be better to get it from the service manager or any other container you are using. This way you make sure that everywhere in your application the same service is being used.
For common variables or services which are needed in templates, I have a wrapper around the TemplateRenderer. So instead of calling the original template renderer, I call my own class and in there I populate the template with common data.
And you can also inject default parameters with TemplateRendererInterface::addDefaultParam. In any other middleware you can inject the templaterenderer, set the desired default data and later on access it in your templates.

How to add a new domain for translations in Symfony

I'm using symfony and in my bundle I need to create some translations, but I rather do it in a different domain than "messages", like FOS User Bundle does (they use the FOSUserBundle domain).
So I created a MyBundle.en.yml file with my translations, but they are not loaded. I've read in the documentation I need to do this:
$translator->addLoader('xlf', new XliffFileLoader());
$translator->addResource('xlf', 'messages.fr.xlf', 'fr_FR');
$translator->addResource('xlf', 'admin.fr.xlf', 'fr_FR', 'admin');
$translator->addResource(
'xlf',
'navigation.fr.xlf',
'fr_FR',
'navigation'
);
http://symfony.com/doc/current/components/translation.html#using-message-domains
But where should I do that?
Update
After some investigation, if I run the debug for the translations it says that all the translation I'm using for my domain in the template are missing.
My translation file is located at
src/Acme/Bundle/MyBundle/resources/translations/MyDomain.yml
I tried to located in app/Resources/translation/MyDomain.yml but same result.
I also tried to delete the cache (rm -rf app/cache) but still not working
Symfony will automatically do this for you if you place your files in the correct location(s). You can find a full description of the conventions assumed by Symfony in the documentation: https://symfony.com/doc/current/translation.html#translation-resource-file-names-and-locations
The Best Practices-guide recommends storing them in app/Resources/translations/. Alternatively you can put them in your bundle's translations folder: src/MyBundle/Resources/translations.
Please be aware that you have to specify your domain when using the translator, e.g. in your twig templates. See:
https://symfony.com/doc/current/components/translation.html#using-message-domains
https://symfony.com/doc/current/translation.html#twig-templates
you have to specify the domain name. for example in twig:
{{ some_things | trans({}, 'my_domaine_name') }}
If you have something like x.en.yaml and you want to use it inside a twing template you can do something like this:
{% trans from 'x' %}word_to_translate{% endtrans %}

Symfony twig - Third party

i am currently working on a symfony project,
what i have:
app/Resources/views/mytemplate/
the folder mytemplate contains all of the important twig-views for my web app.
My question is, is there any possibility that third party members can create their own templates which override my "mytemplate" without creating controllers pointing to them ?
Like:
i have this template:
app/Resources/views/mytemplate/home/index.html.twig
An other person could create a new template in the same views directory like:
app/Resources/views/thirdparty/home/index.html.twig
to override my template.
is there any possibilty like this?
Greetings!
Well, to me, you have two possibilities :
The template that you want to be able to be redefined is the one specified with the method renderView() or similar in your controller : in this case, the possibilities are limitless. It's up to you to define the logic layer determining which template has to be rendered. You could for example force the user redefining the template to name it with a specific additional pattern, and then parse the right template to use thanks to a method inherited in all your controllers.
$content = $this->renderView(
$this->getInheritedTemplate('AcmeHelloBundle:Hello:index.html.twig'),
array('name' => $name)
);
The template that has to be redefined is one inherited in another twig template : In this case, it's almost the same. You could imagine writing your own Twig filter/function in order to retrieve the right template. The code should be very similar to the first case.
Hope this helped.

What's the most convenient way to globally set 2 different form themes for app back-end and front-end

So, theming a form in Symfony2 is easy. You create a custom theme file and you add it to your config.yml file to load it. Done.
However, I have 2 different form themes. One for the front-end of the application and one for the back-end of the application.
I went through the documentation (http://symfony.com/doc/2.3/cookbook/form/form_customization.html) but couldn't find a good and easy way to do this.
When I add the theme to the config.yml file, I have the same theme in both front-end and back-end. I could also include the form within each view like this
{% form_theme form 'form_table_layout.html.twig' %}
However, that means I have to do it within each view.
Is there somehow a way to create a separate config file for front-end and back-end? Can I somehow indicate in the base template file which form theme should be used?
Anything else I could do?
If you use the Symfony2 default directory structure, i.e. you have a single kernel for both the frontend and the backend, you can only (as you mentioned) either set the form theme in each template, or use the same template application-wide by setting it in the config.yml file.
The alternative solution you mentioned, that is creating two base templates, each one setting a "global" form_theme tag would theoretically work. Create a base front-end.html.twig template for all your frontend pages with the following tag:
{% form_theme form 'form-front-end.html.twig' %}
That would work, but you would be forced to have a form variable in each inherited template. You would also not be able to set the theme to multiple forms in the same page.
You could improve the solution by checking if the form variable is defined before styling it:
{% if form is defined %}
{% form_theme form 'form-front-end.html.twig' %}
{% endif %}
or even better, if you want to be able to passing multiple form to the same template, you could do it by using a forms array:
{% if forms is defined %}
{% for form in forms %}
{% form_theme form 'form-front-end.html.twig' %}
{% endfor %}
{% endif %}
The good thing is that this would not throw any exceptions, even if you don't pass the variable at all, but you have to remember to put any forms to be rendered into the forms array.
Obviously, you would do the same thing for the back-end base template.
There may be better solutions, but in the meanwhile I hope this helps!
I also faced this problem some times ago, found this post, and followed the way as Andrea Sprega suggested. Recently I came out of a way which can save some repetitive typings.
Warning: This is somewhat "hackish", is probably not the best way, and is not guarantee to work in next framework release. You'll see why when you read below.
Goal: We want to have different default form templates depending on the application "environment" (the most common examples would be "frontend" and "backend). But fundamentally Symfony isn't aware of such "environment". Although it is possible to split the project into different environments and load different configurations, this is definitely an overkill if what we want is just having different form templates.
I think the best way would be an ability to set/override the default form themes in the base template. So we can have form theme A in frontend base template, and form theme B in backend base template. This sounds the best solution to me because as form theme is a "view" stuff, it makes perfect sense to have it changed in the view. However, the problem seems to be that, when the twig (template) code is executed, the form view is already initialized. So it would be too late to change the default form theme there. (I could be wrong here, because I didn't dig deep enough to have 100% confidence)
So I decided to do it another way. It works like this:
First, I made an assumption that all frontend controllers will extend the same base class (e.g. "BaseFrontendController"). Similarly, all backend controllers will extend the same BaseBackendController class. Here's how we distinguish a frontend and backend environment. This is actually the case in my project.
The default twig templates will be added to these base controller classes. It can be done via a method, or an annotation. In this post I'll use a public method.
Before the controller is executed, overwrite the defined default twig templates.
When the form view is initialized, it will use the default twig template defined in the controller.
Here's how it's done:
Firstly, the default form themes defined in your config.yml will be passed to the constructor of \Symfony\Component\Form\AbstractRendererEngine, and is assigned to the local instance $defaultThemes. This field is protected so that it can be used by its derived classes, but there is no setter to change its value.
So, we need to roll our own Symfony\Bridge\Twig\Form\TwigRendererEngine:
namespace AppBundle\Form\Twig;
use Symfony\Bridge\Twig\Form\TwigRendererEngine as BaseTwigRendererEngine;
class TwigRendererEngine extends BaseTwigRendererEngine
{
/**
* #param array $defaultThemes
*/
public function addDefaultThemes($defaultThemes)
{
$this->defaultThemes = array_merge($this->defaultThemes, $defaultThemes);
}
}
This custom renderer engine is plain simple - it just add a new method to append the default themes to the existing one. And this is why I say it's "hackish" - it will no longer work when the internal is changed.
Secondly, define an interface TwigTemplateProvider which is going to be implemented by the base frontend/backend controller classes:
namespace AppBundle\Form\Twig;
interface TwigTemplateProvider
{
/**
* #return array|string The form template path
*/
public function getDefaultFormTwigTemplates();
}
Thirdly, we need a listener which will run when the controller is executed.
<?php
namespace AppBundle\EventListener;
use AppBundle\Form\Twig\TwigRendererEngine;
use AppBundle\Form\Twig\TwigTemplateProvider;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class PerControllerFormTemplateListener
{
/**
* #var \Twig_Environment
*/
private $twig;
public function __construct(\Twig_Environment $twig)
{
$this->twig = $twig;
}
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
if ($controller[0] instanceof TwigTemplateProvider) {
/** #var \Symfony\Bridge\Twig\Extension\FormExtension $formExtension */
$formExtension = $this->twig->getExtension('form');
$engine = $formExtension->renderer->getEngine();
if ($engine instanceof TwigRendererEngine) {
$templates = (array)$controller[0]->getDefaultFormTwigTemplates();
$engine->addDefaultThemes($templates);
}
}
}
}
The listener will get the form template name (in string or array) supplied by controllers implementing TwigTemplateProvider interface. Then it will add it to the default theme list and pass it to the form renderer engine.
Now, wire them together by adding the followings to your services.yml:
parameters:
twig.form.engine.class: AppBundle\Form\Twig\TwigRendererEngine
services:
app.form.per_controller_template_listener:
class: AppBundle\EventListener\PerControllerFormTemplateListener
arguments: ["#twig"]
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
Here we set the %twig.form.engine.class% parameter to our own implementation, and added our event listener to the stack.
Using it is very simple. For example, in your base frontend controller, implement TwigTemplateProvider and add the following method:
public function getDefaultFormTwigTemplates()
{
return 'frontend/form_layout.html.twig';
}
Then this layout will be added to the form template stack when your front controller is executed.

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' . All my views extends 'layout.html.twig', so how can I access to cities names in every page?
[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 :
<select class="form-control">
{% for entity in entities %}
<option>{{ entity.name}}</option>
{% endfor %}
</select>
finnaly I edit my 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
{{ render(controller("AcmeDemoBundle:Helper:citySelector")) }}
you also can cache the output with ESI.
It's well explained in the cookbook.
http://symfony.com/doc/current/cookbook/templating/global_variables.html
I would go with these steps:
Write a form hosting a symfony entity field configured to work with the Cities table
Define this form as a service in the DIC
Define a twig extension that exposes a function to output the form HTML
Use the twig function in the layout.html.twig that is extended by all the other templates
As an optimization I would look how I could wire Doctrine with some caching system (e.g. memcached) to avoid hitting the database on each page load.
This is where you can find documentation about the entity field: 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.

Categories