Custom dynamic Twig template that extends Twig_Template - php

TL;DR: I am currently struggling with the idea how to elegantly generate CRUDs/GRID using Twig.
Long story:
I have a Phalcon app with AngularJs, templating system is Twig.
PHP is suppose to prepare a template for CRUD that contains:
List od entities, table that contains proper headers, columns, row items, action buttons
Simple and advanced search
Mass actions block
Main buttons - Add/Import/Export etc.
AngularJs is responsible for:
Paginating results in 2 modes: Ajax Loaded entities, All entities at once
Changing number of entities per page
Displaying various forms in modals - Add/Edit/Import
Filtering entities - simple and advanced search
Everything is working right now but I am not particularly fond of how it works.
For example a simple entity with few fields needs a following template:
{% extends 'index.twig' %}
{% block containerAttr %}ng-controller="InventoryController as ctrl"{% endblock %}
{% set ctrlName = 'ctrl' %}
{% set columnWidth = 'col-xs-12' %}
{% set tableClass = 'table table-bordered table-striped table-hover' %}
{% block header %}
{% include '#crud/crud/header.twig' %}
{% endblock %}
{% block content %}
{% embed '#crud/crud/main-box.twig' %}
{% block tableHeader %}
{% autoescape false %}
{{ crud.tableHeader('Id', 'id') }}
{{ crud.tableHeader('Nazwa', 'name') }}
<th class="col-xs-1">Actions</th>
{% endautoescape %}
{% endblock %}
{% block tableRow %}
<td ng-bind="e.id"></td>
<td ng-bind="e.name"></td>
{% endblock %}
{% endembed %}
{% embed '#crud/crud/form.twig' %}
{% block modalBody %}
{% autoescape false %}
<div class="row">
{{ crud.input('ctrl.entity.name', 'Name', 12) }}
</div>
{% endautoescape %}
{% endblock %}
{% endembed %}
{% embed '#crud/crud/upload.twig' %}{% endembed %}
{% embed '#crud/crud/advancedSearch.twig' %}{% endembed %}
<script>
window.xdata = {{ xdata | json_encode | raw }};
</script>
{% endblock %}
crud in this template is responsible for generating form fields compatible with AngularJs.
Idea is: To create new CRUDs/Grids with the least amount of work required. While still giving a room for some flexibility.
Right now to make a CRUD/Grid inside my application there is a really little work required:
PHP Controller needs to contain only one line:
class SubCategoryController extends CrudBase
{
protected $entityClass = InventoryCategory::class;
}
Thanks to extending it is really easy to customize every part of it.
Model needs to have just a few fields:
class InventoryCategory extends ModelBase
{
/** #var integer */
public $id;
/** #var string */
public $name;
public function initialize()
{
$this->setSource('inventory_subcategory');
$this::setup(['castOnHydrate' => true]);
}
}
Even the AngularJs controller contains only URLs and one line:
class InventoryCategoryController extends CrudBase {
constructor($injector, $scope) {
super($injector, $scope);
this.urlSave = '/inventory/category/save';
this.urlImport = '/inventory/category/import';
this.urlExport = '/inventory/category/export';
this.urlDelete = '/inventory/category/delete';
this.init({
advancedSearch: false
});
}
}
angular.module('App').controller('InventoryCategoryController', InventoryCategoryController);
Yes I use ES6, application is not compatible with older browsers anyways and it is admin panel so I do not care about older browsers.
But now only templates remains a tedious work to copy it over and change it. Not to mention they do look pretty ugly.
So my idea was to use Annotation Reader (Phalcon has one) to read fields from Model, then transform it into a base configuration, check if there is custom configuration in json and merge it. Then based on configuration, generate this whole template on the fly.
So the grand question is:
I was wondering if I can create some class that extends Twig_Template to generate this template on the fly?
I have seen Twig cache and it should be pretty easy but then how can i use it? How can i render it? Will extend still work?

Related

What is right way showing virtual entitys field value which computing from service

I have an entity "File" and i want to show boolean value of existing related file in filesystem. For checking existence need to use my DirectoriesManager service which can detect it uses this File entity. What is the right way of configuring ListMapper for this task or it can be solved only by rewriting some sonata templates?
So, what i made:
config.yml
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
globals:
container: '#service_container'
My Sonata Admin class
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('exist', null, [
'template' => 'AdminBundle:Files:exist.html.twig'
]);
}
And my template exist.html.twig
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
{% set value = container.get('dirs_manager').entityFileExist(object) %}
{% if value %}
{% set text = 'label_type_yes'|trans({}, 'SonataAdminBundle') %}
{% else %}
{% set text = 'label_type_no'|trans({}, 'SonataAdminBundle') %}
{% endif %}
{% if value %}
{% set class = 'label-success' %}
{% else %}
{% set class = 'label-danger' %}
{% endif %}
<span class="label {{ class }}">{{ text }}</span>
{% endblock %}
Where service DirectoriesManager has alias dirs_manager.
I know that in Yii2 can configure GridView widget columns with callback for all models that shows any value. May be i can make something like in ListMapper?
I would add listener callback for doctrine's postLoad event. And inside that callback would use the service and set corresponding boolean entity's value.

Loop through categories, childcategories and products in twig

My table structure in my database is like this:
Some categories have a child category and some not. A product can belong to:
Child category
Parent Category (this category has NO child categories)
My array looks like this:
Category A is a parent category. Category B - Head is also a parent category. Category B - Child is a child category of B - Head.
Now I would like to show this array like this:
But I'm stuck on how to know if it's a category or a list of products. Can someone help me with this?
If you're using Doctrine Models (which if you're using Symfony, you should be) then all you're doing is looping through the methods on the object.
Quick and dirty example with few assumptions e.g. using #Template() annotation and standard DAOs aka EntityManager[s] as well as having getChildren() and getProducts() methods on the Category.php (AKA model/entity)
On the controller
/**
* #Route("/products", name="all_products")
* #Template()
*/
public function someAction()
{
...
$categories = $this->getCategoryManager()->findBy([]);
...
return [
'categories' => $categories
];
}
In your twig template
{% if categories|length > 0 %}
{% for category in categories %}
{% if category.children|length > 0 %}
... Here you create the HTML for nested ...
{% else %}
... Here you create the HTML for Category ...
{% for product in category.products %}
... Here you create the HTML for products ...
{% endfor %}
{% endif %}
{% endfor %}
{% else %}
.... some html to handle empty categories ....
{% endif %}
If the HTML for nested is repeated in the HTML for flat (very likely scenario) then you can create and include a macro to spit that out for you.
This is basic, but I think it pretty much covers what you're asking if I'm understanding your question properly.
Btw, you should definitely read the docs for twig and Symfony since they have examples like these everywhere.
I'll edit this answer if you respond as appropriate. Right now you haven't posted enough information to really guide you properly but hope this helps.
You could use a recursive macro. In the macro you either print the list of products or print the list of categories and then call itself.. and so on...
{% macro navigation(categories, products) %}
{% from '_macros.html.twig' import navigation %}
{% if categories|length > 0 or products|length > 0 %}
<ul>
{% for category in categories %}
<li>
{{ category.name }}
({{ category.children|length }} child(ren) & {{ category.products|length }} products)
{{ navigation(category.children, category.products) }}
</li>
{% endfor %}
{% for product in products %}
<li>{{ product.name }}</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}
You would just use this in a template like...
{% from '_macros.html.twig' import navigation %}
{{ navigation(array_of_categories) }}
This just creates a basic set of nested unordered lists but then can be used with any HTML you want, obviously.
For a fiddle see http://twigfiddle.com/mzsq8z).
The fiddle renders as the following (twigfiddle only shows the HTLM rather than something you can use to visualize)...

How to override Show field in sonata admin

I want show the list of multiple attributes Name => value in a table overriding single field of only for PortsAdmin in ShowMapper
Ports Entity mapped with PortsAttributes Entity.
Relation of entity is OneToMany Ports with multiple attributes.
Admin View (Edit Action)
Show Action
I want change attribute view same as edit Action.
You can create a custom template for the PostAttributes:
Example:
/* ShowMapper in admin */
$showMapper->add('attributes', null, array(
'template' => 'YOUR_TEMPLATE.html.twig' // <-- This is the trick
));
In your template, you can extend the base show field (SonataAdminBundle:CRUD:base_show_field.html.twig or #SonataAdmin/CRUD/base_show_field.html.twig for symfony > 4.0), and override the field block. The variable named value stores the data in twig.
Example:
YOUR_TEMPLATE.html.twig
{% extends 'SonataAdminBundle:CRUD:base_show_field.html.twig' %}
{# for sf > 4.0 #}
{# {% extends '#SonataAdmin/CRUD/base_show_field.html.twig' %} #}
{% block field %}
{% for val in value %}
{{ val.name }} - {{ val.value }} {# I'm just guessing the object properties #}
<br/>
{% endfor %}
{% endblock %}
#SlimenTN you can try changing this line in template file:
{% extends 'SonataAdminBundle:CRUD:base_show_field.html.twig' %}
with this:
{% extends '#SonataAdmin/CRUD/base_show_field.html.twig' %}
The rest of code seems ok (I have the same in a SF4 project)

Show One To Many relationship in sonata admin

I want to show the one-to-many relationshop entity in the sonata admin's show action. I found answer to my problem at ("Sonata admin bundle, manipulate objects"). I try to implement #M Khalid Junaid's solution but I get an error "An exception has been thrown during the rendering of a template ("Warning: nl2br() expects parameter 1 to be string, object given") in SonataAdminBundle:CRUD:base_show_field.html.twig at line 13."
Did anyone here face this problem before?
GroupParticipant.php
class GroupRepresentive {
...
/**
* #ORM\OneToMany(targetEntity="GroupParticipant", mappedBy="representive", cascade={"persist", "remove"}, orphanRemoval=true)
*/
public $participant;
public function __construct() {
$this->participant = new ArrayCollection();
}
...}
GroupRepresentativeAdmin.php
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('name')
->add('eventTitle')
->add('email')
->add('person')
->add('payment.paymentType')
->add('payment.bank')
->add('payment.userAccountNumber')
->add('payment.referenceNumber')
->add('payment.paymentAt')
->end()
->with('Participant')
->add('participant', 'null', array(
'template' => 'AppBundle::Admin/groupParticipant.html.twig'
))
;
}
groupParticipant.html.twig
{% extends 'SonataAdminBundle:CRUD:base_show_field.html.twig' %}
{% block field %}
{% spaceless %}
{% endspaceless %}
{% endblock %}
I put the custom template at
Because you didn't really extend the
SonataAdminBundle:CRUD:base_show_field.html.twig
try this
{% block field %}
{# show a field of your entity for example the name #}
{{value.name}}
{% endblock %}
Though the previous answer have been accepted, I'm providing solution for users who are using Symfony 4 and Symfony 3.4 (Symfony Flex).
Field in Admin class must be like:
GroupRepresentativeAdmin.php
->add('participant', 'null', array(
'template' => 'folderName/fileName.html.twig'
));
Note that the folder must be in your templates directory. The path to your twig file must be templates/folderName/fileName.html.twig
The content in twig file must be like:
fileName.html.twig
{% extends '#SonataAdmin/CRUD/base_show_field.html.twig' %}
{% block field %}
{% spaceless %}
//Your custom operation
{% endspaceless %}
{% endblock %}

Avoid repeating the same query in controllers for parent template

I am trying to make a messaging system and I'm facing a small problem. I have a bigger template that displays my menu and my content. The menu includes the number of new messages, and the content can be any page(compose a new message, inbox, sent).
The problem is that I have to render each of the small templates by passing the number of new received messages to each of them, calling the doctrine each time and repeating code. Is there any way to send the number only to the parent template?
Here are my templates:
This is the parent containing the newmsg variable that gives me problems.
{% extends "::base.html.twig" %}
{% block body %}
inbox : {{ newmsg }}
sent
compose
{% endblock body %}
Here is an example of child template:
{% block body %}
{{ parent() }}
{% if messageList %}
{% for message in messageList %}
<li>title = {{ message.title|e }}</li>
<li>cont= {{ message.content|e }}</li>
<li>data= {{ message.date|date('d-m-Y H:m:s') }}</li>
<li>sender= {{ message.sender|e }}</li>
<hr>
{% endfor %}
{% else %}
<div>no messages</div>
{% endif %}
{% endblock body %}
The problem is that each child template is asking me for the newmsg variable
$messages = $this->getDoctrine()->getRepository('MedAppCrudBundle:Message');
$newMessagesNo = count($messages->findBy(array('seen' => '0', 'receiver' => $this->getUser())));
return $this->render(
'MedAppCrudBundle:UserBackend\Message:new.html.twig',
array(
'form' => $form->createView(),
'newmsg' => $newMessagesNo,
)
);
And I have to write this in every single controller. Any way I can shorten this problem?
You could implement a service that gives back the newmsg value and call it on your parent template. Then it would not be necessary to pass the variable.
You can add a service in your bundle's services.yml with something like:
services:
newmessages:
class: Full\Class\Name\NewMessagesService
arguments: ["#doctrine.orm.entity_manager"]
Then, implement the Full\Class\Name\NewMessagesService class. Keep in mind that this class will need a constructor that receives an EntityManager argument. Something like:
<?php
namespace Full\Class\Name;
class NewMessagesService{
private $entityManager;
public function __construct($entityManager){
$this->entityManager = $entityManager;
}
public function methodToCalculate(){
//Perform calculation and return result
}
}
Then, in your parent template, replace {{newmsg} with:
{{ newmessages.methodToCalculate() }}

Categories