1

I'm trying to group events in a matrix field by day. Each date has a title and start and end time. I would like events for today, tomorrow and any dates beyond grouped separately.

This is what I have so far but it's not working:

{% set events = entry.liveStreamEvents %}
{% set todaysEvents = events|group("eventStartTime|date('Y')") %}
                            
{% for block in todaysEvents %}
    <h2>{{ block.eventTitle }}</h2>
{% endfor %}

I get an error Key "eventTitle" for array with keys "0, 1" does not exist.

Where have I gone astray?

Appreciate any help.

1 Answer 1

1

Check out the documentation for the group filter and you'll realise that it creates a nested array for each thing you want to group by, and the array key of each nested array will be your eventStartTime. Once you have your grouped array you can then cherrypick today's events, tomorrow's events, and the rest using the filter filter, combined with Twig's now variable, and the date_modify filter. I haven't tested this but it should work:

{# Fetch all events from the matrix #}
{% set eventsMatrix = entry.liveStreamEvents.all() %}

{# Group the array by date in the format 2024-12-31 #}
{% set eventsGroupedByStartDate = eventsMatrix|group("eventStartTime|date('Y-m-d')") %}

{# Filter out today's and tommorrow's events by comparing to `now` #}
{% set todaysEvents = eventsGroupedByStartDate|filter(date => date == now|date('Y-m-d')) %}
{% set tomorrowsEvents = eventsGroupedByStartDate|filter(date => date == now|date_modify('+1 day')|date('Y-m-d')) %}
{% set beyondTomorrowsEvents = eventsGroupedByStartDate|filter(date => date > now|date_modify('+1 day')|date('Y-m-d')) %}

{% if todaysEvents|length %}    
    <h2>Today’s events</h2>
    <ul>
        {% for event in todaysEvents[0] %}
            <li>{{ event.eventTitle }}</li>
        {% endfor %}
    </ul>
{% endif %}

{% if tomorrowsEvents|length %}    
    <h2>Tomorrow’s events</h2>
    <ul>
        {% for event in tomorrowsEvents[0] %}
            <li>{{ event.eventTitle }}</li>
        {% endfor %}
    </ul>
{% endif %}

{% if beyondTomorrowsEvents|length %}
    {% for date, events in beyondTomorrowsEvents %}
        <h2>{{ date }}</h2>
        {% if events|length %}
            <ul>
                {% for event in events %}
                    <li>{{ event.eventTitle }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endfor %}
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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