I’m trying to filter and sort entries by date, from a structure field.
I tried to piece together solutions I found in related K2 threads but without success…
Here’s the structure field in my blueprint:
shows:
type: structure
fields:
show_date:
label: Date
type: date
I’d like to display only entries whose date in the show_date field are in the future and in ascending chronological order.
My template:
<?php foreach ($page->shows()->toStructure() as $show): ?>
<?php if ($show->show_date()->filterBy('show_date', '>', time())): ?>
<li>
The <?php echo $show->show_date() ?> show is in the future.
</li>
<?php endif ?>
<?php endforeach ?>
So far, all entries are displayed, both ones with dates in the future and dates in the past.
I haven’t included the sorting yet, because I first need to get the filtering part to work.
I’m pretty sure it’s a simple problem is in the <?php if… line…
Can somebody see it?
Hello texnixe, could you please help me to understand how you quote (I don’t know php, I try to make sense and copy/paste bits for trial/error…). when you answer
$shows = $page->shows()->toStructure()->filterBy…
which part does it corrects in
<?php foreach ($page->shows()->toStructure() as $show): ?>
<?php if ($show->show_date()->filterBy('show_date', '>', time())): ?>
<li>
The <?php echo $show->show_date() ?> show is in the future.
</li>
<?php endif ?>
<?php endforeach ?>
You can only filter a collection, not the individual fields in the structure, so the code would have to look like this:
<?php
$shows = $page->shows()->toStructure()->filterBy('show_date', '>', time());
foreach ($shows as $show): ?>
<li>
The <?= $show->show_date()->toDate('Y-m-d') ?> show is in the future.
</li>
<?php endif ?>
<?php endforeach ?>
While you don’t have to define the variable first, it’s a bit cleaner that putting everything into the foreach loop. You could do it like this as well if you absolutely want:
<?php foreach ($page->shows()->toStructure()->filterBy('show_date', '>', time()) as $show): ?>
Hello texnixe, I try to do my best to learn Kirby (I appreciate its beautiful approach and lightness), but I’m lacking a lot (I’m just a designer).
I want to show only the coming dates from a structure. I copy and use the example codes. But as I enter a date on the panel, I get a error message on the page. I did try with the 2 codes you provided without any luck.
Can you point me in a direction, thank you
right:
width: 1/2
sections:
content:
type: fields
fields:
shows:
type: structure
fields:
show_date:
label: Date
type: date
There are quite good online resources available, unless you are a fan of books. But usually in the coding area, books are often not up to date (but can still do their stuff for the basics).