I’m trying to figure out how to filter items by year with a tag but cant wrap my head around the params part of it.
Template
<?php
if($year_tag = param('year_tag')) {
$items = $items->filter(function($child) {
$structure = $child->playtime()->toStructure();
return $structure->filter(function($item) {
$year_number = $year_tag;
$start_year = date(mktime(0, 0, 0, 1, 1, $year_number));
$end_year = date(mktime(0, 0, 0, 12, 31, $year_number));
return $item->eventdate()->toDate() >= $start_year && $item->eventdate()->toDate() <= $end_year;
})->count();
});
};
?>
<?php snippet('filter', ['items' => $items,'year_tag' => $year_tag, 'query' => $query]); ?>
Snippet
<?php foreach ($page->year_tags()->split() as $year_tag): ?>
<li>
<a href="<?= url($page->url(), ['params' => ['year' => rawurldecode($year_tag)]]) ?>">
<span class="labels mc-time <?php e($year_tag == urldecode(param('year')), 'mc-time-active') ?>"><?= html($year_tag) ?></span>
</a>
</li>
<?php endforeach ?>
texnixe
November 14, 2019, 10:33am
#2
Could you please post your data structure aka blueprint? It will make it easier to understand what you are doing there…
The filter by date & structure field works fine, the only part im struggling with is to convert the $year_tay “2019” to the $year_number.
Here are my blueprints:
Event page
fields:
playtime:
label: playtime
type: structure
fields:
eventdate:
label: Datum Event
type: date
default: today
required: true
time:
label: Time
type: time
default: now
eventtype:
label: Soort Event
type: select
options:
(wip): (WORK IN PROGRESS)
(try-out): (TRY-OUT)
(première): (PREMIÈRE)
event_id:
label: Voorstellingsgroep code
type: text
performance_id:
label: Voorstellings code
type: text
ticketlink:
label: ticket url (external)
type: url
translate: false
Archive page
year_tags:
label: Jaar filter
type: tags
texnixe
November 14, 2019, 1:08pm
#4
The first thing that springs to my eye is that you should actually get an error message, because the $year_tag
variable in not defined inside your filter functions…, you would have to pass it down with use()
.
if($year_tag = param('year_tag')) {
$items = $items->filter(function($child) use($year_tag) {
$structure = $child->playtime()->toStructure();
return $structure->filter(function($item) use($year_tag) {
$year_number = $year_tag;
$start_year = date(mktime(0, 0, 0, 1, 1, $year_number));
$end_year = date(mktime(0, 0, 0, 12, 31, $year_number));
return $item->eventdate()->toDate() >= $start_year && $item->eventdate()->toDate() <= $end_year;
})->count();
});
};
And then you are overcomplicating your code:
if ($year_tag = param('year_tag')) {
$items = $items->filter(function($child) use($year_tag) {
$structure = $child->playtime()->toStructure();
return $structure->filter(function($item) use($year_tag) {
return $item->eventdate()->toDate('Y') == $year_tag;
})->count();
});
}
Thanks! I defined the year_tag and all works fine now.
Yeah… the overcomplicating code… still in heavy learning!