<p>When you include templates and pass multiple different variables to them with different types that may have a different field layout it is required to <a href="https://nystudio107.com/blog/handling-errors-gracefully-in-craft-cms#defensive-coding-in-twig" rel="nofollow noreferrer">code defensively</a> and check for variable types. Actually you should <strong>never</strong> print something without further checking. Anything bad that could happen will happen. Especially in such a case</p>

<pre><code>{% if country[fieldhandle] is defined and country[fieldhandle] is not empty and  %}
    {% for element in country.getFieldValue(fieldhandle).all() %}
        {{ element.title }}
    {% endfor %}
{% endif %}
</code></pre>

<p>You may as well include a <a href="https://docs.craftcms.com/v3/dev/tests.html#instance-of" rel="nofollow noreferrer">instance of</a> check</p>

<pre><code>{% if element.getFieldValue(fieldHandle) is instance of('craft\\elements\\db\\ElementQuery') %}
    {% set relatedElements = element.getFieldValue(fieldHandle).all() %}
{% else %}
    // eager loading, the result is an array, no need to fetch it
    {% set relatedElements = element.getFieldValue(fieldHandle) %}
{% endif %}
</code></pre>

CC BY-SA 4.0
2018-07-24T13:12:12.617Z
Robin - I"m not sure what you mean.  but I tried your code and got an error `impossible to invoke a method ("all") on an array. I really need to be able to have these entries output in a specific order.
CreateSean
CC BY-SA 4.0
2018-07-24T13:13:07.377Z
Do you eager load them? Because that would be a reason why it is not working, normally that field is a default query.. You can sort the results as you like
Robin Schambach
CC BY-SA 4.0
2018-07-24T13:15:35.047Z
Not eager loading - have updated the original post with the full template code.
CreateSean
CC BY-SA 4.0
2018-07-24T13:17:57.320Z
Where do you set the `fieldName` variable? I'm a little bit confused, because you just have to call `entry.field.all()`
Robin Schambach
CC BY-SA 4.0
2018-07-24T13:26:06.827Z
That's coming through an include ```    {% include '_includes/pub-section' with {
      "categoryTitle" : "Market Monitor",
      "hash"          : "market-monitor",
      "fieldName"     : "marketMonitor"
    } %}```
CreateSean
CC BY-SA 4.0
2018-07-24T13:28:56.270Z
And your `countries` query? As already said Craft provides the order by default unless you changed it in the query
Robin Schambach
CC BY-SA 4.0
2018-07-24T13:56:26.483Z
countries is set in the parent template {% set countries = craft.entries.section('countries') %} and then a for loop goes over it in the include
CreateSean
CC BY-SA 4.0
2018-07-21T06:55:32.153Z
2018-07-24T14:44:07.207Z
2018-07-24T14:44:07.207Z
Robin Schambach
<p>Craft 3.0.16.1</p>

<p>I have a relationship that is outputting entries, but the entries are not in the order as selected.</p>

<pre><code>{# not sorting correctly  - **fieldName** is a variable passed via include #}
{% set relatedEntries = publications.relatedTo(
  {sourceElement: country, field: fieldName}
) %}
</code></pre>

<p>I copied this <a href="https://docs.craftcms.com/v3/entries-fields.html" rel="nofollow noreferrer">code from the documentation</a> and change field names to work</p>

<pre><code>{# copied from docs but template errors #}
{% set relatedEntries = craft.entries({
    relatedTo: { sourceElement: country, field: fieldName },
    orderBy:     "sortOrder",
    limit:     null
}) %}
</code></pre>

<p>but this throws a database exception error</p>

<blockquote>
  <p>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sortOrder' in
  'order clause'</p>
</blockquote>

<p>How do I get related entries to sort on the order as selected in the entries field?</p>

<p>********************UPDATE**********************</p>

<p>HERE IS THE FULL TEMPLATE</p>

<pre><code>  &lt;li class="accordion-item {#{% if loop.first %}is-active{% endif %}#}" data-accordion-item&gt;
    &lt;!-- Accordion tab title --&gt;
    &lt;a href="#" class="accordion-title"&gt;
      {{ categoryTitle  }}
      &lt;i class="icon-chevron-right"&gt;&lt;/i&gt;&lt;!-- /.arrow right --&gt;
    &lt;/a&gt;

    &lt;!-- Accordion tab content: it would start in the open state due to using the `is-active` state class. --&gt;
    &lt;div class="accordion-content" data-tab-content&gt;

      {# start tabbed content #}
      &lt;ul class="tabs" data-tabs id="cat-{{ hash }} "&gt;

       {# inside categories list countries #}
      {% for country in countries.all() %}  
        &lt;li class="tabs-title {#{% if loop.first %}is-active{% endif %}#}"&gt;&lt;a href="#{{ country.slug }}" aria-selected="true" data-tabs-target="{{ country.slug }}"&gt;{{ country.title }}&lt;/a&gt;&lt;/li&gt;
      {% endfor %} {# end countries loop #}
      &lt;/ul&gt;


      &lt;div class="tabs-content" data-tabs-content="cat-{{ hash }}"&gt;
        {% for country in countries.all() %}
        &lt;div class="tabs-panel {#{% if loop.first %}is-active{% endif %}#}" id="{{ country.slug }}"&gt;
          &lt;ul class="no-bullet pubs full-width"&gt;

            {# finally output entries that are in the category and country #}

            {# not sorting correctly #}
            {% set relatedEntries = publications.relatedTo(                   {sourceElement: country, field: fieldName}
            ) %}

            {# error about method ('all') on an array #}
            {# {% set relatedEntries = country[fieldName].all() %} #}

            {# 
            // copied from docs but template errors
            {% set relatedEntries = craft.entries({
                relatedTo: { sourceElement: country, field: fieldName },
                orderBy:     "sortOrder",
                limit:     null
            }) %} #}



            {% for entry in relatedEntries.all() %}

              {% for block in entry.Documents.all() %}
                {% if block.externalLink|length %}
                  {# use external link field #}
                  {% set link = block.externalLink %}
                {% else %}
                  {# use uploaded file #}
                  {% set link = block.pdfOrFile.one().url ?? null%}
                {% endif %}

                &lt;li&gt;&lt;a href="{{ link }}" target="_blank"&gt;
                  &lt;p&gt;{{ entry.title }}&lt;/p&gt;
                  &lt;div class="icon-holder"&gt;
                    &lt;img src="/assets/img/next.svg" alt="" class="go-icon"&gt;
                  &lt;/div&gt;&lt;!-- /.icon-holder --&gt;&lt;/a&gt;
                &lt;/li&gt;
              {% endfor %}{#end link #}

              {% else %}
              {# output nothing for no results #}
            {% endfor %}

          &lt;/ul&gt;&lt;!-- /.no-bullet pubs --&gt;
        &lt;/div&gt;
        {% endfor %}
      &lt;/div&gt;
      {# end tabbed content #}      

    &lt;/div&gt;&lt;!--accordion content--&gt;
  &lt;/li&gt;
</code></pre>

CC BY-SA 4.0
2018-07-20T18:31:42.367Z
You trying to output a list of entries that were selected in an Entries field (in the order selected), is that right?
Simon Kuran
CC BY-SA 4.0
2018-07-24T13:17:34.427Z
@SimonKuran Yes that is correct
CreateSean
<entries-field><sorting>
Related Entries not sorting correctly
# Related Entries not sorting correctly

(Asked by: username_0 on 2018-07-19)

Craft 3.0.16.1
I have a relationship that is outputting entries, but the entries are not in the order as selected.
{# not sorting correctly  - **fieldName** is a variable passed via include #}
{% set relatedEntries = publications.relatedTo(
  {sourceElement: country, field: fieldName}
) %}

I copied this code from the documentation and change field names to work
{# copied from docs but template errors #}
{% set relatedEntries = craft.entries({
    relatedTo: { sourceElement: country, field: fieldName },
    orderBy:     "sortOrder",
    limit:     null
}) %}

but this throws a database exception error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sortOrder' in
  'order clause'

How do I get related entries to sort on the order as selected in the entries field?
********************UPDATE**********************
HERE IS THE FULL TEMPLATE
  
    
    
      {{ categoryTitle  }}
      
    

    
    

      {# start tabbed content #}
      

       {# inside categories list countries #}
      {% for country in countries.all() %}  
        {{ country.title }}
      {% endfor %} {# end countries loop #}
      


      
        {% for country in countries.all() %}
        
          

            {# finally output entries that are in the category and country #}

            {# not sorting correctly #}
            {% set relatedEntries = publications.relatedTo(                   {sourceElement: country, field: fieldName}
            ) %}

            {# error about method ('all') on an array #}
            {# {% set relatedEntries = country[fieldName].all() %} #}

            {# 
            // copied from docs but template errors
            {% set relatedEntries = craft.entries({
                relatedTo: { sourceElement: country, field: fieldName },
                orderBy:     "sortOrder",
                limit:     null
            }) %} #}



            {% for entry in relatedEntries.all() %}

              {% for block in entry.Documents.all() %}
                {% if block.externalLink|length %}
                  {# use external link field #}
                  {% set link = block.externalLink %}
                {% else %}
                  {# use uploaded file #}
                  {% set link = block.pdfOrFile.one().url ?? null%}
                {% endif %}

                
                  {{ entry.title }}
                  
                    
                  
                
              {% endfor %}{#end link #}

              {% else %}
              {# output nothing for no results #}
            {% endfor %}

          
        
        {% endfor %}
      
      {# end tabbed content #}

**Tags:** entries-field, sorting
> **Comments:**
> **username_1**: You trying to output a list of entries that were selected in an Entries field (in the order selected), is that right?  
> **username_0**: @SimonKuran Yes that is correct  

---

## 1 answers

### Answer by username_2 on 2018-07-21. Score: 3 | Accepted answer

When you include templates and pass multiple different variables to them with different types that may have a different field layout it is required to code defensively and check for variable types. Actually you should never print something without further checking. Anything bad that could happen will happen. Especially in such a case
{% if country[fieldhandle] is defined and country[fieldhandle] is not empty and  %}
    {% for element in country.getFieldValue(fieldhandle).all() %}
        {{ element.title }}
    {% endfor %}
{% endif %}

You may as well include a instance of check
{% if element.getFieldValue(fieldHandle) is instance of('craft\\elements\\db\\ElementQuery') %}
    {% set relatedElements = element.getFieldValue(fieldHandle).all() %}
{% else %}
    // eager loading, the result is an array, no need to fetch it
    {% set relatedElements = element.getFieldValue(fieldHandle) %}
{% endif %}

> **Comments:**
> **username_0**: Robin - I"m not sure what you mean.  but I tried your code and got an error `impossible to invoke a method ("all") on an array. I really need to be able to have these entries output in a specific order.  
> **username_2**: Do you eager load them? Because that would be a reason why it is not working, normally that field is a default query.. You can sort the results as you like  
> **username_0**: Not eager loading - have updated the original post with the full template code.  
> **username_2**: Where do you set the `fieldName` variable? I'm a little bit confused, because you just have to call `entry.field.all()`  
> **username_0**: That's coming through an include ```    {% include '_includes/pub-section' with {       "categoryTitle" : "Market Monitor",       "hash"          : "market-monitor",       "fieldName"     : "marketMonitor"     } %}```  
> **username_2**: And your `countries` query? As already said Craft provides the order by default unless you changed it in the query  
> **username_0**: countries is set in the parent template {% set countries = craft.entries.section('countries') %} and then a for loop goes over it in the include  

---

