In a Page Model, return structure field value from different page

I’m attempting to create a new method $page->cat_color() using a page model for my page.php template.
On each page.php-page, I am selecting a category queried from a structure field on a categories page.

I’m getting very confused by the following outcome:

// site/models/page.php
<?php
class PagePage extends Page {
  public function cat_color() {
    return page('categories')
    ->categories()
    ->toStructure()
    ->findBy('category', $this->category())
    ->color();
  }
}

this breaks the page (“Call to a member function color() on null”).

However, if I replace $this->category() with one of my predefined categories, i.e 'Curating', it’s working well:

return page('categories')
    ->categories()
    ->toStructure()
    ->findBy('category', 'Curating')
    ->color();
// returns the set hex value for 'Curating'

Inside my method ($this->category() == 'Curating'); is true for all the pages where i have selected the category, so whyy is the method not working using $this->category()? :weary:

:point_down:here’s the result of var_dump(page('categories')->categories())

string(134) 
"- 
  category: Curating
  color: '#FFF77F'
- 
  category: Writing
  color: '#B4FFDF'
- 
  category: Public Speaking
  color: '#965AFF'
"

:point_down:here’s the result of var_dump($page('categories')->categories()->toStructure()

object(Kirby\Cms\Structure)#322 (3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
}

Try

->findBy('category', $this->category()->value())

Nevertheless, I’d make sure the element exists before calling the color() method.

<?php
class PagePage extends Page {
  public function cat_color() {
    if ($element = 
    page('categories') // hope we can safely assume that this page always exists...
    ->categories()
    ->toStructure()
    ->findBy('category', $this->category()->value())) {
        return $element->color();
    }
   return '';
}
1 Like

aaah that’s working! thank you so much!

I thought the same so I disabled name change, slug change and deletion in the blueprint—is there a better approach?

Make sense to do that. If you want to be on the really safe side, you’d add an additional check if the page exists before you call categories().

1 Like