I have multiple event pages that need to be sorted by date. The problem is that some of the events have multiple dates/times that they take place, so the dates are stored in a structure field.
I want to sort the event pages by the first structure field entry but I have no idea how to use that field in the sortBy function.
My structure fields looks like this:
date:
type: structure
fields:
date:
type: date
time:
type: time
timeend:
type: time
I only need to sort by the time entry, since I have already split the events into days.
You can use a callback function with sortBy, which allows you to fetch the date of the first item of the structure field.
As an alternative you can create a page model with a custom function that returns the date, then use this custom function to sort by: Sorting | Kirby CMS
1 Like
This was much easier than I thought. I kind of missed an example of a simple callback function in the cookbook / reference but I just used this and it works great:
$eventsThisDay = $eventsThisDay->sortBy(function($event) {
return $event->date()->toStructure()->first()->time()->toDate();
});
Unless you are 100% sure that you always have a valid item, Iād add a check before calling time
to prevent calling method on null error:
$eventsThisDay = $eventsThisDay->sortBy(function($event) {
if ( $item = $event->date()->toStructure()->first() ) {
return $item->time()->toDate();
}
});
1 Like