How to access entity functions with parameters in TWIG - symfony2 - php

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.

Related

Symfony 4 EasyAdmin - Property does not render when overriding bundle template

Using Symfony 4.1 with EasyAdmin bundle.
I am trying to override a template for the User (one of my entites) show view. I have set up the override and it is working.
Created a user_show.html.twig and registered it in the easy_admin config file.
I then copy the twig blocks from corresponding bundle template for show.html.twig.
Then tried to render a User property from my user entity, called profile height.
Here are twig blocks I'm overriding:
{# templates/admin/user_show.html.twig #}
{% extends '#EasyAdmin/default/show.html.twig' %}
{% block content_title %}
Test Title {{ dump() }}
{% endblock %}
{% block main %}
{{ profileHeight }}
{% endblock %}
Error
Twig_Error_Runtime: Variable "profileHeight" does not exist
Debug
I did a dump and found the property is present on page:
Why can twig not see these variables appearing in the dump? How can I render the properties I want in the template?
As you can see in your dumped data, there is entity array key which hold the User object. So instead of:
{% block main %}
{{ profileHeight }}
{% endblock %}
Use:
{% block main %}
{{ entity.profileHeight }}
{% endblock %}

How to automatically check if variables are not empty in Symfony 3?

(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).

phalcon : volt get value from array which key taken from variable

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) }}

Twig Type Reflection in Symfony 2

I'm working in a generic index.html.twig template, for testing purposes. So, I want to check the objects properties arriving to the view. I'm testing a lister for any entity in my database.
I'll loop an object's keys obtained. But the function: keys, from Twig official book, only works with with arrays or collections.
Exists any solution to this?
Here goes the code:
{% if model and model.data %}
{% set firstKeys= model.data|first %}
{% for key, item in firstKeys %}
{{ attribute(item, key) }}<br>
{% endfor %}
<p>
...
</p>
{% endif %}

How to get a Doctrine2 Entity method from a Symfony2 Form in Twig

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 }}.

Categories