Sorting by multiple fields but with one custom function

Dear community,

I am trying to sort pages like in this example: Sorting | Kirby CMS

In my case, I have to sort by rooms and by start date. I want to have a list of rooms with the respective events sorted by start date. Because the rooms are a referenced page, I have to use a custom sorting function.

$callback = function($e) {
  return $e->room()->toPage()->num();
}

$events = $event_page->children()->sortBy('from', 'asc')->sort($callback);

Depending on the order in which I sort, I either don’t get the events in the right chronological order, or the rooms are not grouped.

How could I solve this?

Do you want to sort or group? What is the expected result?

I think I rather want to sort. My goal is a “list” to use in foreach in the following structure:

Room Z (Num/Order 1)
Event M: 9:00
Event L: 11:00

Room X (Num/Order 2)
Event A: 10:00
Event K: 11:00

Room Y (Num/Order 3)
Event F: 09:00
Event B: 13:00
Event T: 15:00

If possible, I would use the following code:

$events = $event_page->children()->sortBy('from', 'asc', 'room__num', 'asc');

Hm, the result I see is a list grouped by room and then sorting by start date, that cannot be achieved with sorting alone. And also, with sorting alone, you would have to sort first by room and then by date, not the other way round as currently.

So if I were you, I would group by room (group() with a callback), then sort the items within the group by start date.

Thank you very much for the help.

I can’t get it to work at the moment, but that’s my fault, because I don’t seem to understand collections very well (group() return at the moment a 2-3-1-5-4 order, I expect 5->1 or 1->5, like the years of blog posts in the example).

Maybe tomorrow I’ll just try to create a nested array and then use a sorted loop of the rooms to get the data from the array.

Hm, but something like this should do the job:


$groupedEvents = $event_page
->children()
->sort(fn ($event) => $e->room()->toPage()->num())
->group((fn ($event) => $e->room()->toPage()->title());

foreach ($groupedEvents as $group => $events) {
echo $group;
foreach ($events as $event) {
echo $event->title() . ': ’ . $event->from();
}
}


Code might have typos, it's late... Your IDE should warn you