Category view with a foreach loop

Hi, I have some hard time getting this right. Just need a little help to get this category view done.

So what I have on the site is the following. I have Product page that have children. And on each it is a field that I want to use as category name for sorting. So I want to title of field as title on the area and then attach additional icon maybe. That i know how to fix if I just get the loop right.

And under each section on the same page see the pages belonging to each section.

This is what I want to do:

Ideas? Upfront thank you…

groupBy() is what you are looking for …

1 Like

Why does the headline give an error when I try change it?

<?php
$categories = page('products')->children()->visible()->groupBy('category');
foreach($categories as $category => $items): ?>
    <h2><?php echo str::upper($category) ?></h2> // Corrected for future use.
    <ul>
      <?php foreach($items as $item) : ?>
      <li><?php echo $item->title() ?></li>
      <?php endforeach; ?>
    </ul>
<?php endforeach ?>

The upper() field method can only be used on a field object, but category is not a field object, but a string in this context. Use a string method (str::upper(), I think) instead.

On a side note: make sure that all your subpages have a category field (should be the case if you use the Panel). Kirby throws an error if the field is missing (e.g. if you use a text editor to edit your files)

1 Like

Ok, thank you @texnixe. Also for so quick answers. :slight_smile: Have a great weekend!

1 Like

Is there a way to gently let it fail if there is none?

As I said, if you use the Panel, it is not a problem, because the field may be empty, the problem only arises if the field does not exist.

If that may be the case, you’d have to use a filter to filter out all products without a category first, then group.

Ok. Great, thank you.

Don´t get this to work today. Since I have a array to check and not just one value.

<?php $groups = page('products')->children()->visible()->filterBy('category') ?>

<?php
$categories = $groups->groupBy('category');
// The rest of the loop...

This do not wrack the page, but also do not pass anything. :confused:

What you could try:

<?php $groups = page('products')->children()->visible()->filterBy('category', '!=', '') ?>

(And off to the fun part of Saturday night :slight_smile: )

2 Likes

It worked well! :slight_smile: Enjoy!

9 posts were split to a new topic: Sort collection by translated value from category map