Pierrou Pierrou - 4 months ago 31x
PHP Question

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 :

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