Display Blocks filtered by date

I would like to display each of my Blocks as an event either under the headline “Upcoming” or “Past”. In my Block I have two date fields called “from” & “to”:

  from:
    label: Startdatum
    type: date
    default: today
    display: D.MM.YYYY
  to:
    label: Enddatum
    type: date
    default: today + 1day
    display: D.MM.YYYY

I tried to create two collections in my template like this:

<?php $upcoming = $site
->children()
->filter(function ($child) {
       return $child->from()->toDate() > time() || $child->to()->toDate() > time();
})
->sortBy(function ($site) {
       return $site->from()->toDate();
}, 'desc');

$past = $site
->children()
->filter(function ($child) {
       return $child->to()->toDate() < time();
})
->sortBy(function ($site) {
       return $site->from()->toDate();
}, 'desc');
?>

but I know that it’s not referenced to my blocks. How can I do that and how can I then display the Blocks out of a collection?

My draft to display the blocks in my template:

<h2>
    Upcoming
</h2>

<?php if ($upcoming->count() > 0): ?>
<ul>
    <?php foreach ($upcoming as $event): ?>
    <li class="event">
        <?php foreach ($site->munichBlocks()->toBlocks() as $block): ?>
        <div id="<?= $block->id() ?>" class="block block-type-<?= $block->type() ?>">
            <?= $block ?>
        </div>
        <?php endforeach ?>
    </li>
    <?php endforeach ?>
</ul>
<?php endif ?>

Please post your blueprint with the blocks field and your custom block definition.

Block blueprint called “project-munich.yml”:

name: Ausstellung München
icon: page

fields:
  artist:
    label: Künstler
    type: textarea
    width: 1/1
    buttons: false
  exhibitionName:
    label: Ausstellungstitel
    type: textarea
    width: 1/1
    buttons: false
  from:
    label: Startdatum
    type: date
    default: today
    display: D.MM.YYYY
  to:
    label: Enddatum
    type: date
    default: today + 1day
    display: D.MM.YYYY

And my site.yml:

    fields:
      munichBlocks:
        type: blocks
        label: Ausstellungen München
        fieldsets:
          projects:
            label: Projekte
            type: group
            fieldsets:
              - project-munich

(The website has no subpages, thats why I am using the site.yml)

What you are doing here is filter child pages, but you want to filter the blocks, therefore

$blocks = $site->munichBlocks()->toBlocks();

Then you filter the blocks by date:

$upcoming = $blocks->filter(function ($block) {
       return $block->to()->toDate() < time();
});
1 Like

Thanks!