(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).
Related
I need to be able to test the existence of a macro in Twig and to call it dynamically.
Here is what I tried:
{% macro test(value) %}
Value: {{ value }}
{% endmacro %}
{% import "_macros.html.twig" as macro %}
{{ attribute(macro, 'test', ['foo']) }}
But I get this error: Accessing Twig_Template attributes is forbidden.
Regards,
Since Twig 1.20.0, template attributes are not available anymore for security reasons, so there are no native way to do it properly.
You can eventually use the source function to get macro's source file and parse it to check if a macro exists, but that's a kind of ugly hack easy to bypass.
Example:
main.twig
{% import 'macros.twig' as macros %}
{% set sourceMacros = source(macros) %}
foo {% if 'foo()' in sourceMacros %} exists {% else %} does not exist {% endif %}
bar {% if 'bar()' in sourceMacros %} exists {% else %} does not exist {% endif %}
macros.twig
{% macro foo() %}
Hello, world!
{% endmacro %}
See this example live
Another approach would be to create a custom test to do the job.
I am trying to access array but it is not getting accessed.
in my config.yml following is my array :
abc : [xyz]
and in another file i am writing following code to access abc array.
{% if abc[0] is defined) %}
then do something
{% endif %}
but somehow its not working. please help me out i am newbie in this.
It depends if the variable is always declared or not:
If the variable is always declared and the array can be empty
{% if abc is not empty %}
{# then do something #}
{% endif %}
<variable> is not empty in Twig is equivalent to !empty($variable) in PHP. When an array is provided, is not empty will check there is a value and/or a value in the array.
empty test in Twig documentation.
If the variable is not always declared
Check that the abc variable is declared and not empty:
{% if (abc is declared) and (abc is not empty) %}
{# then do something #}
{% endif %}
<variable> is declared in Twig is equivalent to isset($variable) in PHP.
defined test in Twig documentation.
Based on comments I would recommend using foreach loop instead and define your ifs based on index values. Something like this:
{% for abcs in abc %}
{% if (loop.index == 0) %}
then do something
{% endif %}
{% endfor %}
BR's
I'm trying to render a form on a twig template if its is defined in the render call on controller. Something like:
{% if form_to_be_rendered is defined %}
{{ form(form_to_be_rendered) }}
{% endif }
If the controller's render call includes the var of form_to_be_rendered, everything runs well, and the form is rendered. But if I try to render the template without this argument, Twig throws a RuntimeError indicating that the form_to_be_rendered variable is not defined.
Variable "form_to_be_rendered" does not exist in BundleName:Path/to/template:template.html.twig at line 3
500 Internal Server Error - Twig_Error_Runtime
I've tried passing it as a null value and is not null check on condition, but it fails too.
I put this dump on template:
{% dump reset_password_form is defined %}
And it is evaluated as false when I don't pass any arguments to render function.
EDIT
I forgot to post that there is a {% block content %} inside the conditional block which causes the issue. Please view the solution below.
Thanks,
Solved.
It's pretty weird and my fault since I don't post the full code on the OP.
{% if form is defined %}
{% block content%}
{{ form(form)}}
{% end block %}
{% endif %}
The conditional block has inside a {% block content %} that Twig tries to render even the condition is evaluated to false. If I surround the conditional block with the content block, the issue is resolved.
{% block content%}
{% if form is defined %}
{{ form(form)}}
{% endif %}
{% end block %}
Thanks
Twig documentation says:
defined:
defined checks if a variable is defined in the current context.
empty:
evaluates to true if the foo variable is null, false, an empty array, or the empty string.
null:
null returns true if the variable is null.
So figure out, what exactly you want to check, depending on what value "form_to_be_rendered" can have.
Did you try:
{% if form_to_be_renderer|length %}
{{ form(form_to_be_renderer) }}
{% endif %}
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 %}
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 }}.