Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-24T13:12:12.617Z
Answers.Text: 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.
Answers.UserDisplayName: CreateSean
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-24T13:13:07.377Z
Answers.Text: 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
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-24T13:15:35.047Z
Answers.Text: Not eager loading - have updated the original post with the full template code.
Answers.UserDisplayName: CreateSean
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-24T13:17:57.320Z
Answers.Text: Where do you set the `fieldName` variable? I'm a little bit confused, because you just have to call `entry.field.all()`
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-24T13:26:06.827Z
Answers.Text: That's coming through an include ```    {% include '_includes/pub-section' with {
        "categoryTitle" : "Market Monitor",
        "hash"          : "market-monitor",
        "fieldName"     : "marketMonitor"
      } %}```
Answers.UserDisplayName: CreateSean
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-24T13:28:56.270Z
Answers.Text: And your `countries` query? As already said Craft provides the order by default unless you changed it in the query
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-24T13:56:26.483Z
Answers.Text: countries is set in the parent template {% set countries = craft.entries.section('countries') %} and then a for loop goes over it in the include
Answers.UserDisplayName: CreateSean
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-21T06:55:32.153Z
Answers.LastActivityDate: 2018-07-24T14:44:07.207Z
Answers.LastEditDate: 2018-07-24T14:44:07.207Z
Answers.UserDisplayName: Robin Schambach
Body: <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>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-07-20T18:31:42.367Z
Comments.Text: You trying to output a list of entries that were selected in an Entries field (in the order selected), is that right?
Comments.UserDisplayName: Simon Kuran
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-07-24T13:17:34.427Z
Comments.Text: @SimonKuran Yes that is correct
Comments.UserDisplayName: CreateSean
Tags: <entries-field><sorting>
Title: Related Entries not sorting correctly
ThreadText: # 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](https://docs.craftcms.com/v3/entries-fields.html) 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
  
  ```
    <li class="accordion-item {#{% if loop.first %}is-active{% endif %}#}" data-accordion-item>
      <!-- Accordion tab title -->
      <a href="#" class="accordion-title">
        {{ categoryTitle  }}
        <i class="icon-chevron-right"></i><!-- /.arrow right -->
      </a>
  
      <!-- Accordion tab content: it would start in the open state due to using the `is-active` state class. -->
      <div class="accordion-content" data-tab-content>
  
        {# start tabbed content #}
        <ul class="tabs" data-tabs id="cat-{{ hash }} ">
  
         {# inside categories list countries #}
        {% for country in countries.all() %}  
          <li class="tabs-title {#{% if loop.first %}is-active{% endif %}#}"><a href="#{{ country.slug }}" aria-selected="true" data-tabs-target="{{ country.slug }}">{{ country.title }}</a></li>
        {% endfor %} {# end countries loop #}
        </ul>
  
        <div class="tabs-content" data-tabs-content="cat-{{ hash }}">
          {% for country in countries.all() %}
          <div class="tabs-panel {#{% if loop.first %}is-active{% endif %}#}" id="{{ country.slug }}">
            <ul class="no-bullet pubs full-width">
  
              {# 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 %}
  
                  <li><a href="{{ link }}" target="_blank">
                    <p>{{ entry.title }}</p>
                    <div class="icon-holder">
                      <img src="/assets/img/next.svg" alt="" class="go-icon">
                    </div><!-- /.icon-holder --></a>
                  </li>
                {% endfor %}{#end link #}
  
                {% else %}
                {# output nothing for no results #}
              {% endfor %}
  
            </ul><!-- /.no-bullet pubs -->
          </div>
          {% endfor %}
        </div>
        {# end tabbed content #}      
  
      </div><!--accordion content-->
    </li>
  
  ```
  
  **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**: @username_1 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](https://nystudio107.com/blog/handling-errors-gracefully-in-craft-cms#defensive-coding-in-twig) 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](https://docs.craftcms.com/v3/dev/tests.html#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**: username_2 - 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  
  
  ---
  
  