Hi there!
Great idea on the panel.page.update
hook. Here’s what I came up with- I merged all four date fields into an array but it still throws an error- says the $events
variable at the beginning of the array_filter
line is unexpected. I thought maybe combining all the dates and comparing them directly would avoid creating a new field and then sorting by that field.
Can you take a look and see what’s going on here and if I have this basic concept down correctly?
Thanks to @servicethinker for the original idea as posted here: Auto Sort and Auto Filter An Structured Event. My events and the dates are not in a structure field, but I took the basic concept as inspiration.
event-sorting-by-future-date.php
<?php
// Sorting events structure field by next future date
kirby()->hook('panel.page.update', function($page) {
if(isset($page->content()->data['events'])) {
$events = $page('events')->children();
$end_date = $page('events')->end_date();
$addl_end_date1 = $page('events')->addl_end_date1();
$addl_end_date2 = $page('events')->addl_end_date2();
$addl_end_date3 = $page('events')->addl_end_date3();
// Merge all possible date fields into one array
$alldates = array_merge($end_date, $addl_end_date1, $addl_end_date2, $addl_end_date3)
// Filtering expired dates
$events = array_filter($events, function($k) {
$today = date("Y-m-d");
return strcmp($k['alldates'], $today) >= 0;
});
// Sorting future dates
usort($events, function($a, $b) {
return strcmp($a['alldates'], $b['alldates']);
});
// Save result
try {
$page->update(array(
'events' => yaml::encode($events)
));
}
catch(Exception $e) {
echo $e->getMessage();
}
}
});
Thanks for taking a look!