nirsh
June 1, 2022, 10:44am
1
Hi again!
I have a list of events that are ordered by the date.
I would like to show only the events that happen today.
I guess I need to use an if statement but I can’t figure out how to fetch the event before the ‘foreach’. this is my code now:
<?php
$events = page()->children()->template('event');
$sortedEvents = $events->sortBy(function ($page) {
return $page->date()->toDate();
});
foreach($sortedEvents as $event): ?>
<?php snippet('event', ['event'=>$event])?>
<?php endforeach ?>
Would appreciate any help
You want to filter your events by date before you go into the loop: Filtering compendium | Kirby CMS
nirsh
June 1, 2022, 11:55am
3
Thanks!
I almost succeeded.
I managed to filter future events. but for some reason it shows none when I try to show the events that happen today:
<?php
$today = date('Y-m-d');
$events = page()->children()->template('event')->filterBy('date', 'date >', $today);
$sortedEvents = $events->sortBy(function ($page) {
return $page->date()->toDate();
});
foreach($sortedEvents as $event): ?>
<?php snippet('event', ['event'=>$event])?>
<?php endforeach ?>
this one works - it shows only future events (and remove current events)
but when I changes the sign ‘>’ to ‘===’ (or ‘==’, ‘=’) it shows nothing.
and I have events that their date is today.
I even printed the $today and the $event->date() to see if it’s the same and it is
Am I doing something wrong?
Thank you!
$events = page()->children()->template('event')->filter(fn ($p) => $p->date()->toDate('Y-m-d') === $today);
1 Like
nirsh
June 1, 2022, 12:03pm
5
It works now!
I’m not sure I understand what exactly that you did.
is it the same as this tutorial?
$year = date('Y');
$articles = page('blog')
->children()
->filter(function ($page) use ($year) {
return $page->date()->toDate('Y') === $year;
});
Anyway - thank you so much
Yes, only with Y-m-d instead of year only
Only difference apart from that is the shorter callback syntax.
nirsh
June 1, 2022, 12:34pm
7
yeah I understand now! the shorter syntax got me confused
Thanks a lot again!