Sorting matrixblocks by earliest date from child table I have a matrix field (events), each of this blocks (event) contains a table (dates) with individual rows (date), those have a start date and a start time. I would like to sort the events (matrix blocks) by the earliest start date / start time. Also at some point I would only want to display future events.

Whats the "best" way to achieve this kind of sorting in a template (twig)? Would I have to loop through them and sort them "manually"? I think about something around sorting the child tables first and then sort the blocks by their first table rows.

Entry


Event A [matrixblock]

Dates [table]

Date 1 | (12/12/2015) [datetimefield] | (10:00) [datetimefield]
Date 2 | (10/10/2015) [datetimefield] | (10:00) [datetimefield]


Event B [matrixblock]

Dates [table]

Date 1 | (09/09/2015) [datetimefield] | (10:00) [datetimefield]
Date 2 | (10/10/2015) [datetimefield] | (10:00) [datetimefield]
Date 3 | (11/11/2015) [datetimefield] | (10:00) [datetimefield]




This simple case would sort Event B, Event A. Because of the earliest date being Date 1 of Event B.

Appreciate any input. Cheers.
This is a bit tricky to do from the template, but what I would suggest is to query for the Matrix blocks once,
than loop through the blocks and store the data to a new custom array.

The idea is, to build that array in a way that ensures, you can later apply sort and group Twig filters.

{% set allDates = [] %}
{% for block in entry.myEventsMatrix %}
    {% for row in block.myDatesTable %}

        {% set allDates = allDates|merge([{
            datetime: (row.myDateTime|date('c')),
            eventId: (block.id),
            event: block
        }]) %}

    {% endfor %}
{% endfor %}


When sorting an array of arrays with the sort filter, the inner array's first value is relevant, so make sure this is the
DateTime you want to sort by. Besides that, I included the block's ID "eventID" and the complete block model "event".

{% set datesGrouped = allDates|sort|group('eventId') %}

{% for eventId, datesInEvent in datesGrouped %}
    &lt;h3&gt;{{ eventId }}&lt;/h3&gt;        
    {% for date in datesInEvent %}
        {{ date.datetime|date('Y-m-d') }}
    {% endfor %}
{% endfor %}


Outside the "datesInEvent" loop you can access the events model with:

{% set event = datesInEvent[0].event %}