Using the key from a grouping inside the find method doesn't work

I’m facing a problem with my kirby project right now. In general, the below code works as expected, except for line 4.

<?php
$categories = $page->children()->visible()->groupBy('typ');
foreach($categories as $category => $products): ?>
  <h2><?= page('angebote/kategorien')->children()->find((string)$category)->title() ?></h2>
  <ul class="products grid gutter-1">
    <?php
      foreach ($products as $product): 
        snippet('single-angebot', array('product' => $product)); 
      endforeach;
    ?>
  </ul>
<?php endforeach ?>

The problem is, that I want to specify several user-defined categories as pages, in my case they are located in the relative folder angebote/kategorien. This folder contains all of the categories with a textfile that only contains a ´Title´ field.

The children of the current page are grouped by a property called typ which is basically the uid for the category. Because each category has another display title, I want to fetch the title from this category.

According to the docs the ->find(key) method returns the related page object. And this is true, whether with or without the (string) cast. I’ve actually checked that via dump().

The actual issue now, is that I cannot call the ´->title()´ method. Below is the error mesage.

Call to a member function title() on boolean

Ironically, it works perfectly when I am hardcoding a specific category like the following example:

<h2><?= page('angebote/kategorien')->children()->find('sample')->title() ?></h2>

But a dump($category) only returns the plain string, nothing special.

Am I doing something wrong or is this a bug? Besides that, is there a more elegant solution for a simple user-manipulateable categories field which is also queryable via the select field on the panel?

Could you please check if this works and what result you get:

<h2><?= $catPage = (page('angebote/kategorien')->children()->find($category))? $catPage->title(): 'page does not exist'; ?></h2>

The returned error is:

Undefined variable: catPage

This implies that the page has been found. And when I hardcode a category that doesn’t exist, it also returns “page does not exist” as expected.

Oh, sorry, wrong placement of parenthesis, try this:

<h2><?= ($catPage = page('angebote/kategorien')->children()->find($category))? $catPage->title(): 'page does not exist'; ?></h2>

Yay, everything works as expected and each category is returning the correct title :slight_smile:
Thank you!

I know I’m repeating myself over and over again, but I can only recommend to make this a best practice: Whenever you try to call a method on an object, always check if the object exists first.