Preciel Preciel - 2 months ago 17
Twig Question

Filter related entity in twig

[SETTINGS]


  • Symfony 3

  • ContainerEntity: [id, name]


    • Can contain 0,n BoxEntity


  • BoxEntity: [id, container_id, parent, name]


    • Is always associated to a ContainerEntity

    • Can contain 0,n BoxEntity




[DATABASE CONTENT]

container

------------------
| id | name |
------------------
| 1 | container |
------------------


box

--------------------------------------
| id | container_id | parent | name |
--------------------------------------
| 1 | 1 | null | box 1 |
--------------------------------------
| 2 | 1 | null | box 2 |
--------------------------------------
| 3 | 1 | 1 | box 3 |
--------------------------------------


[FILES]

inventory.html.twig

{% if container.box|length > 0 %}
{% for box in container.box %}
<li class="nav_menu_item">
<a class="nav_menu_link" href="">{{ box.name }}</a>
{% if box.inbox|length > 0 %}
<div class="nav_menu_dropdown">
<ul>
{% for inbox in box.inbox %}
<li class="nav_menu_dropdown_item">
<a class="nav_menu_dropdown_link" href="">{{ inbox.name }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
</li>
{% endfor %}
{% endif %}


[PROBLEM]

In twig, I would like to filter the related entity list based on it's
parent
parameter.

Currently, doing
{{ container.box|length }}
will return 3 box (same problem with
{% for ... %}
)

How can I get all
container.box
where
box.parent
is null ?

Answer Source

try this

{% for box in container.box if box.parent is null %}