In phalcon templating engine volt (which is similar to twig) you can fetch all records by :
{% for product in products %}
Name: {{ product.name }}
Description: {{ product.description }}
price: {{ product.price}}
{% endfor %}
So, in my scenario, I'm building a crud template which will be used for different kind of models. What I wanted to achieve in this template is that every columns in this view are not hard-coded. So I store the columns I wanted to show into an array (defined in the controller, passed to the view) :
$cols = ['name','description','price']
In the view, to make it display all columns :
{% for product in products %}
{% for col in cols %}
{{ col }}: {{ product.col }}
{% endfor %}
{% endfor %}
Obviously, this will result in error, because there is no "col" in product.
Is there any solution or alternative for this ?
While frustrated tinkering with volt extension, I found a simpler solution :
Convert the model object into array. In the controller : $products->toArray()
Simply, in the view, to display specific value of specific key from an array : {{ product[key] }}
Problem solved, though because it is now not in form of object, I can't access object property using dot like {{ product.some_field }}, instead {{ product['some_field'] }}.
You should use the readAttribute() function:
http://forum.phalconphp.com/discussion/1231/volt-access-to-object-property-using-variable
{{ product.readAttribute(col) }}
Related
I have a twig template that extends from a sonata_block.
But I cant find any variables to dump.
Is there a way to dump the wrapper element, or container?
eg: {{ dump(this)}}, or {{ dump(self)}}
You can list all available variables in twig templates by looping through the _context var :
{% for key, value in _context %}
<h2>{{ key }}</h2>
{{ dump(value) }}
{% endfor %}
(Sorry for this bad english)
I would like to know if it's possible to automatically check if variables from MySQL request are not empty in Symfony 3. I know that I can put {% if foo is defined %} in Twig or something like this but I didn't find if there's a way to do it automatically. I can test the request in the controller too. But with those solutions I have to do it for every request.
All my website uses "if not empty then show it" that's why I'm trying to find it.
Edit : I know how to check every fields of every request in Twig or in php (Controller) one by one but there is a lot of duplication code, which is "boring". Thats why I am asking you if something automatic exists to check my data. (parameter in Symfony, ...)
Thank you <3
If I understand, your problem :
You want to iterate on each property in an entity. But you can't, then you are searching for a solution to not write :
{% if entity.property1 %}
{{ entity.property1 }}
{% endif %}
{% if entity.property2 %}
{{ entity.property2 }}
{% endif %}
{% if entity.property3 %}
{{ entity.property3 }}
{% endif %}
You have two solutions to make your properties traversable :
Get your entity with a Doctrine query using ->getArrayResult() instead of ->getResult()
Use ReflectionClass to get the properties as an array :
http://php.net/manual/fr/class.reflectionclass.php
So you can iterate on each property, and do something like that :
{# Where you get your entity as an array #}
{% for property in entity %}
{% if not property is null %}
{{ property }}
{% endif %}
{% endfor %}
{# where fields comes from the ReflectionClass #}
{% for field in fields %}
{% if not attribute(entity,field) is null %}
{{ attribute(entity,field)}}
{% endif %}
{% endfor %}
Use the Twig strict_variables config parameter and set it to false (should be the default value):
strict_variables boolean
If set to false, Twig will silently ignore invalid variables
(variables and or attributes/methods that do not exist) and replace
them with a null value. When set to true, Twig throws an exception
instead (default to false).
I am using the KNP Paginator bundle for pagination. Does anyone know how to append parameters to the generated url?
Here is my set up:
{{ knp_pagination_sortable(supplierProducts, 'Product Sku', 'p.name') }}
I want to add §ion=supplier to the end of the URL, I just have no clue how to do it. I looked through the docs but did not find any info.
Please help if you can.
Thanks.
According to the KnpPaginator documentation, you can append query parameters as follows:
$paginator = $this->get('knp_paginator');
...
$pagination->setParam('section', 'supplier');
You could extend the kn_pagination_sortable template. When you run "knp_pagination_sortable" behind the scenes, it will basically generate an HTML according to your specifications. However, you can extend that. Instead of using the bundle's generated HTML for that element, you can write your own template for that pagination_sortable. This is a snippet from the project I'm working on. This is at my pagination_sortable.html.twig:
<a id="table_sorteable_{{ options['title']|lower }}" {% for attr, value in options %} {{ attr }}="{{ value }}"{% endfor %}>
{{ title }}
<b class="caret {{ options['class'] }}"></b>
</a>
Get it? You can have a template like that and change it according to your needs.
You can find more information on the link below.
Overriding default pagination template
As of 2020, and KnpPaginatorBundle v5.3, the solution proposed by #likeitlikeit doesn't work because the setParam method doesn't exist any more.
But you can append parameters to the sort and pagination links directly in the knp helpers in twig:
{# 4th parameter for sortable helper #}
{{ knp_pagination_sortable(results, column.title, column.alias, {}, params) }}
{# 3rd parameter for pagination helper #}
{{ knp_pagination_render(results, '', params) }}
For example, if you want to include the query parameters in the sort and pagination links, you can do:
{# Sort - pass all query parameters except sort column and direction #}
{% set params=app.request.query.all | filter((v, k) => (k != 'direction' and k != 'sort'))%}
{% for column in ... %}
{{ knp_pagination_sortable(results, column.title, column.alias, {}, params) }}
{% endfor %}
{# Pagination #}
{{ knp_pagination_render(results, '', app.request.query.all) }}
To add parameters in the url, I proceeded like this:
in Front:
{{ knp_pagination_render(clients, ('annuaire/my_pagination.html.twig'), {"type": type ? type : '' ,"city": city ? city : ''}) }}
I have a twig template in my Symfony2 project.
In the twig template, I have an entity object.
This entity object is linked to another entity with oneToMany relation.
Example:
{{ submission }} -> Submission entity
{{ submission.histories }} -> Histories entity -> I have here an array collection of histories
The entity histories has a field "state_to"
My goal is to get only the histories object where the state_to is 4
I tryed like that:
{{ submission.histories('status_to', 4)[0] }}
But this is not working.
I know that I can use:
{% for history in submission.histories %}
{% if history.statusTo == 4 %}
{{ history.statusDate|date("d F Y") }}
{% endif %}
{% endfor %}
But I am allmost sure that there is a nicer way.
Add a method getHistoryByStatus($status) in your entity to filter your histories based on the status_to field, then in your template:
{% set filtered_history = submission.historyByStatus(4)|default(false) %}
{% if filtered_history %}
{{ filtered_history.statusDate|date("d F Y") }}
{% endif %}
you could just find the histories object where the state_to is 4 within a method called in your controller. then pass it to the view. This method can be inside your controller, but is better to have it in your history repository maybe? or a manager..
try avoiding complexity in the views.
I'm in a Twig template, and I have a "form" variable that represents a Doctrine2 Entity Form.
This Entity has properties that are mapped into the form, but the Entity has also some methods that I would like to access from my Twig template.
I would love to do something like this:
{{ form.myMethod }}
or maybe something like this:
{{ form.getEntity.myMethod }}
but unfortunately it doesn't work.
How could I achieve what I need?
To access your entity from your FormView in a twig template you can use the following code
{{ form.get('value') }}
Where form is your FormView object. This will return your entity and from there you can call any methods on it. If you embed a collection of entities or a single entity in your form you can access it the same way
{{ form.someembedform.get('value') }}
or
{% for obj in form.mycollection %}
{{ obj.get('value').someMethod }}
{% endif %}
An even more convenient syntax to get the underlying entity instead of:
{{ form.get('value') }}
is this:
{{ form.vars.value }}
Then you can call any entity method like this:
{{ form.vars.value.someMethod }}
See also the Form chapter in the Symfony documentation.
Just in order to update the subject:
form.get('value')
is deprecated since symfony 2.1. Copy from Symfony\Component\Form\FormView :
/*
* #deprecated Deprecated since version 2.1, to be removed in 2.3. Access
* the public property {#link vars} instead.
*/
public function get($name, $default = null) ....
so, I guess
form.vars.value.youMethod()
should be the way to go. It has worked form me.
... and there it goes my first post here. hope it helps!
Lost few hours trying to figure out what's going on and why
{{ form.vars.value }}
is NULL.
If you have form.element (not the form object itself) object, for example if you are overriding a form_row template that has passed the form.row object, you can get the Entity like this:
{{ form.getParent().vars.value.MyEntityMethod }}
hope that helps someone!
EDIT: Year and so later - another useful tip:
{% block sonata_type_collection_widget %}
{% for child in form %}
{{ child.vars.form.vars.value.name }}
{% endfor %}
{% endblock %}
object methods should work in twig, I know I used them in some project.
try to use ()
like {{ form.myMethod() }}
It seems that at some point the value is actually null. So you can use
{{ (form.vars.value != null) ? form.vars.value.yourEntityMethod():'' }}
tested in SF v3.0.6.
None of the above worked for me in version 2.6.7. I used customised form widgets to achieve this:
{# src/AppBundle/Resources/views/Form/fields.html.twig #}
{% extends 'form_div_layout.html.twig' %}
{%- block entity_widget -%}
<div {{ block('widget_container_attributes') }}>
{%- for n, child in form %}
{{- form_widget(child, {
'entity': form.vars.choices[n].data
}) -}}
{{- form_label(child) -}}
{% endfor -%}
</div>
{%- endblock %-}
{%- block radio_widget -%}
{# You now have access to entity #}
{%- endblock %-}
use {{ form.getData.myMethod }}.