So I have been trying to work out this one for a while.
In PHP it is enough to first say if isset($var) and $var == something and it won’t complain about me trying to compare something that doesn’t exist.
Clearly that’s not enough in TWIG.
Now, why does this not work? I first run an if to check whether entity.container is set, and if it isn’t dont go through that block.
It seems that TWIG just HAS to go through all code anyways. So, I have this entity that doesn’t always have a container (entity.container) set, so how should I go about this? Because when I run this code TWIG just complains that I have one if statement where I try to go entitiy.container.containerType when entity.container doesn’t exist.
{% if entity.container is defined %}
{% if entity.trash == false and entity.container.containerType.name =='Module' %}
<form action="{{ path('deleteContent', { 'id': entity.id }) }}" method="post" onsubmit="return confirm('Bekräfta att du vill radera detta innehåll? Detta går inte att ångra.')">
{{ form_widget(delete_form) }}
<button type="submit" style="color:red;">Radera permanent</button>
</form>
{% elseif entity.trash == false and entity.container.containerType.name !='Module' %}
<form action="{{ path('deleteContent', { 'id': entity.id }) }}" method="post">
{{ form_widget(delete_form) }}
<button type="submit" style="color:red;">Flytta till papperskorgen</button>
</form>
{% elseif entity.trash == true and entity.container != null %}
<form action="{{ path('restoreContent', { 'id': entity.id }) }}" method="post">
{{ form_widget(delete_form) }}
<button type="submit" style="color:red;">Återställ till ursprunglig plats</button>
</form>
{% else %}
För att återställa detta innehåll måste du först välja en plats för det.
{% endif %}
{% else %}
hehe
{% endif %}
I think that in your case, the entity.container is defined but is not set, may be null.
There is a difference between a defined and an empty or null variable.
So the first if statement is checked and allow to parse the logic inside.
To check if a variable is set or not you’ve to use
or simply use the “is not null”,
both with the condition that the variable should be defined, otherwise you’ll get the error “Item or Object “container.whateverYouWant” for “entity” does not exist …”