Home > Blockchain >  How can I create condition "if there is no event belonging to the selected category" in Sy
How can I create condition "if there is no event belonging to the selected category" in Sy

Time:10-11

I'd like to show an element if there is no event belonging to the category. Before landing on list of events user has selected a category previously in a search form.

How can I write a condition saying 'if there is no event belonging to the selected category' ?

I tried this but I ended up with this error :

Key "category" for array with keys "0" does not exist.

My code on twig :

{% if events.category.id != category.id %}

    <a href="#">Comment participer ?</a>

{% endif %}

CodePudding user response:

From the error text it seems that your events variable is an array of objects, so you can't use .category.id in a condition without a loop. You need a loop to determine if the event is set with the category you want in the array, if not, display your message

{% set event_isset = false %}
{% for event in events %}
    {% if event.category.id == category.id %}
        {% set event_isset = true %}
    {% endif %}
{% endfor %}

{% if not event_isset %}
    <a href="#">Comment participer ?</a>
{% endif %}

CodePudding user response:

If your events is an array of objects/arrays each of which has key category then this condition should work:

{% if events|filter(e => e.category == category.id)|length == 0 %}
...
{% endif %}

Docs https://twig.symfony.com/doc/2.x/filters/filter.html

  • Related