1

I need to loop related entries.

I am using a SuperTable field with the handle "related" with an entry field with the handle "contentEntry" and two text fields for alternative text and descriptions.

The "contentEntry" field is limited to two entries being selected. The issue I'm having is that the following code repeats the first entry twice and doesn't loop and display the second. What am I doing wrong?

{# Related Entry #}

{% set relatedEntries = block.related.all %}
{% set relatedEntry = block.related.contentEntry.all() %}
{% set relatedAltDesc = block.related.altDescription %}
{% set relatedAltTitle = block.related.altTitle %}


{% if relatedEntries %}

<div class="{{ padding }} {{ fontsize }}" id="{{ blockID }}">
    <div class="{{ margin }}">

            {% for entries in relatedEntries %}

              {% for rel in relatedEntry %}

                {% if relatedAltTitle %}
                  {{ relatedAltTitle }}
                {% else %}
                  {{ rel.title }}
                {% endif %}


                {% if relatedAltDesc %}
                  {{ relatedAltDesc }}
                {% else %}
                  {{ rel.previewDescription }}
                {% endif %}

              {% endfor %}

            {% endfor %}

    </div>
</div>

{% endif %}

enter image description here

2

The issue is: you don't really loop your entries at all.

{# get all super table rows #}
{% set superTableRows = block.related.all %}

{% if superTableRows is not empty %}
    <div class="{{ padding }} {{ fontsize }}" id="{{ blockID }}">
        <div class="{{ margin }}">

            {# loop all of your super tables #}
            {% for row in superTableRows %}

                {# loop all contentEntries in each row #}
                {% for entry in row.contentEntry.all() %}

                    {# 
                        display the alternative title set in your supertablerow 
                        and if thats not set display the entries title
                    #}
                    {{ row.altTitle?? entry.title }}

                    {# same as above #}
                    {{ row.altDescription ?? entry.previewDescription }}

                {% endfor %}
            {% endfor %}
        </div>
    </div>
{% endif %}

block.related is an Object of type ElementQuery. block.related.altDescription returns the criteria of this Query, this is mostly empty since no criteria is set by default.

  • Thanks Robin! superTables should be superTableRows in this example. – Dan Lee Mar 21 at 9:22
  • Uh yeah copy paste fail. Does it work for you? – Robin Schambach Mar 21 at 9:24
  • Yes, this is working well! Some coding efficiency in there too which is appreciated as a learning point. – Dan Lee Mar 21 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.