sortBy number and groups my projects

Hi,

For a project I need to organize projects by years, the intention it’s to layout in the frontend my project like this :

  • 2021
    project A
    project B

  • 2020
    project C
    project D

For the moment, I manage to sort my project by year and display the years. But I don"t really know how I can do the layout I want.

This is what I have for the moment :

  • 2021

  • 2020

  • project A

  • project B

  • project C

  • project D

Here’s my code :

    <?php  foreach ($pages->find('projets')->children()->pluck('year', ',', true) as $year): ?>
        <datetime><?= $year ?></datetime>
    <?php endforeach ?>

    <?php
      $articles = page('projets')->children()->listed()->sortBy(function ($page) {
        return $page->number()->toNumber();
      })->flip();
  
      foreach($articles as $article): ?>
        <!-- Looping through blocks, to get some blocks fields -->
        <?php foreach ($article->cover()->toBlocks() as $block): ?>

          <a class="column-<?= $block->layout() ?>" href="<?= $article->url() ?>">
            <h2><?= $article->number()->toNumber() ?></h2>
            <?= $block ?>
            <h3>
              <?= $article->title() ?>
            </h3>
          </a>
        <?php endforeach ?>
    <?php endforeach ?>

I was thinking by sorting byGroup. But I’m not really sure.
If you have a suggestion, I’ll be glad to look at it.

Thank’s

Check out this cookbook recipe:

1 Like

Thanks !

I’ve got an other question.

I want also filter my projects by category. For the moment, it’s working, but the year when there is not projects in the selected category still displaying like this:

I don’t want to display the year 2019 because there no projects in the category « chercher » for this year.

Here is my code:

<?php
  $years = page('projets')->children()->listed()->sortBy('year')->groupBy('year');
  foreach($years->flip() as $year => $itemsPerYear): ?>
    <time><?= $year ?></time>
    <?php
    if($category = param('category')) {
         $itemsPerYear = $itemsPerYear->filterBy('category', param('category'), ',' );
       }
      foreach($itemsPerYear as $item) : ?>
       ....
    <?php endforeach ?>
<?php endforeach ?>

You have to move your category filter up:

<?php
  
$years = page('projets')->children()->listed()->sortBy('year', 'desc');
if($category = param('category')) {
  $years = $years->filterBy('category', $category, ',' );
}
$years = $years->groupBy('year');

foreach($years as $year => $itemsPerYear): ?>
    <time><?= $year ?></time>
    <?php foreach($itemsPerYear as $item) : ?>
       ....
    <?php endforeach ?>
<?php endforeach ?>

Thanks, it was so simple !