Sort and group pages by translated category

Hi there,

I am looking for a way to group and sort children by category BUT need the translated category value for sorting in the correct language. I am currently using the t() helper to get the translated category.

In the end I need the original category to do filtering and the translated for displaying. Maybe I need to add the translated value to the collection too? Not sure.

<?php

$grouped = $page('XXX')->children()->sortBy('category')->groupBy('category');

foreach($grouped as $cat => $category){ ?>

    <a href="<?= $page->url() . '/category:' . $cat ?>"><?= t($cat) ?> (<?= $category->count() ?>)</a>

<?php } ?>

$grouped = page('XXX')
  ->children()
  ->sort(function($child) {
    return t($child->category()->value());
  })
  ->group(function($child) {
    return t($child->category()->value());
  });

Or shorter:

$grouped = page('XXX')
  ->children()
  ->sort(fn ($child) => t($child->category()->value()))
  ->group(fn ($child) => t($child->category()->value()));

Thanks, as always that worked very well. Now things have changed a bit, I don’t get the translation from the language file bit a structure field. Instead from using:

t($child->category()->value())

to

$site->categories()->toStructure()->findBy('english', $site->category()->value())

My structure field categories has name and english properties. The below obviously does not work. Hopefully you get the idea.

  ->sort(function($child) {
      return $site->categories()->toStructure()->findBy('english', $child->category()->value());
  })

  ->group(function($child) {
      return $child->category()->value();
  }) 

Many thanks in advance!

That would return a structure item, so you would have to get the field you want from that item:

  return $site->categories()->toStructure()->findBy('english', $child->category()->value())->english()->value();

Note that the code will fail if the item doesn’t exist, so better use an if statement here.

now I get “Undefined variable $site”.

And when adding $site to the function:

->sort(function($site, $child) {

Too few arguments to function Kirby\Toolkit\F::{closure}(), 1 passed in /Users/agloeckner/Library/Mobile Documents/com~apple~CloudDocs/web/wassersparfuchs.de/kirby/src/Toolkit/Collection.php on line 1028 and exactly 2 expected

Oops, sorry, use the site() helper instead:

  return site()->categories()->toStructure()->findBy('english', $child->category()->value())->english()->value();

Or arrow syntax:

  ->sort(fn ($child) => $site->categories()->toStructure()->findBy('english', $child->category()->value()))

Or a use statement:

 ->sort(function($child) use($site) {
      return $site->categories()->toStructure()->findBy('english', $child->category()->value())->english()->value();
  })