2

I want to modify this query so that the dated entries are sorted in descending order on a custom field called 'startDate'.

Have tried adding .order('startDate') to the end of the craft.entries(query)... but this causes any entry with a startDate to be excluded from the query.

(Maybe it's possible to set the order on just the {% for entry in programmeEntriesDated... loop?)

{% set query = { section: 'programme' } %}
{% set query = category is defined ? query | merge({ relatedTo: category }) : query %}
{% set programmeEntriesDated = craft.entries(query) %}

{# Show programme entries if available #}
{% if programmeEntriesDated|length %}
<div class="flex flex-wrap flex-row-ns">
  {# DATED ENTRIES #}
  {% for entry in programmeEntriesDated if (
        (entry.startDate|date('Y-m-d') >= now|date('Y-m-d'))
    or  (entry.endDate is not null and entry.endDate|date('Y-m-d') >= now|date('Y-m-d'))
    ) and
        (entry.type != 'old_programme_entry')
    and (entry.isOngoing == 0)
  %}
    {% include "_blocks/event_single.html" with { 'blockWidth' : 'w-100 w-third-ns' } %}
  {% endfor %}

  {# ONGOING ENTRIES  #}
  {% for entry in programmeEntriesDated if (entry.isOngoing) and
        (entry.type != 'old_programme_entry')
  %}
    {% include "_blocks/event_single.html" with { 'blockWidth' : 'w-100 w-third-ns' } %}
  {% endfor %}
</div>
  • Your use of the order parameter is totally correct. Entries without a value in that field won't be excluded, they'll just appear last. Your first loop won't show them because of the condition (which is a bit strange because you are comparing strings with each other. That may cause unexpected behavior. I would suggest to compare the DateTime) – Robin Schambach Nov 12 '18 at 12:48
  • Ahh, I don't have a good grasp of how dates work in Twig, thanks for pointing that out Robin. I just realised a hacky solution, I can reverse the first for loop with for entry in programmeEntriesDated|reverse EDIT: Not really a true solution, as the events still aren't correctly sorted by date) – James Greig Nov 12 '18 at 12:56
  • 1
    Or just re-order them correctly from the beginning with ASC or DESC you can compare Date objects directly with entry.date >= now PHP will compare the timestamps in your DateTime objects which is more accurate than strings – Robin Schambach Nov 12 '18 at 12:58
  • I can do that inside the original query? – James Greig Nov 12 '18 at 13:27
  • Can't use entry.date because I want to search on the custom startDate field not the post date (I think...) – James Greig Nov 12 '18 at 14:09

Your Answer

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

Browse other questions tagged or ask your own question.