If has parents?

This don’t work:

if( $page->parents() ) {
  echo 'This is echoed even if there are no parents';
}

Any other idea how to check if there are parents?

What about:

if( $page->parents()->count() > 0 ) {
  echo 'This is echoed even if there are no parents';
}

You could check if the page is in the $pages collection, which is only first level pages (i.e. no parents).

Thanks!

I found out a solution:

if( $page->parents()->toArray() ) {
}

…but what do we expect when we write:

if( $page->parents() ) {
}

That it should check if there are parents. The same way to check if a page exists. Maybe I should turn this topic into a suggestion?

1 Like

It returns a collection of all parents. I agree though that it should return false if there are no parents.

An object can return different things when echo or compare it as a string than using print_r or var_dump. Some kind of magic php I guess. In this case I think that the string output could be improved.

That’s unfortunately not going to work as an object is always considered as “truthy”.

I think the best solution is the one proposed by Sonja above. It’s easier to understand and more explicit than checking if the returned array is truthy.

Alright. I don’t fully understand. Is there a difference between these two? Couldn’t they work the same way?

if( $page ) {
  echo 'Page exists. (works)';
}

if( $page->parents() ) {
  echo 'Parents exists. (doesn't work today)';
}

That depends on how you got $page. If via the page() helper: It returns false if the page does not exist. Returning false for empty collections however would break code that expects a collection object.

1 Like

what about $page->parents()->count() > 0?

edited: already suggested by @texnixe above. missed that since i followed the link from kirby secrets which jumps to mid of thread . :blush:

Yes, that was already suggested above and is probably the best option.

As a page method:

<?php
page::$methods['hasParents'] = function($page) {
  return $page->parents()->count();
};

Edit: I don’t know why @jenstornell suggests using the toArray() method in his secrets. I’d stick with count(), not only in this case but for each collection to check if it has elements.

This is also in line with other hasXYZ() methods in Kirby, e.g.

  public function hasChildren() {
    return $this->children()->count();
  }
1 Like

The reason was that I tried a few things and toArray() was short and worked.

I also saw your suggestion and compared it to mine:

if( $page->parents()->count() > 0 ) {
if( $page->parents()->toArray() ) {

My was a bit simpler and shorter so I kept it in the secrets.

Now it seems like we have an even shorter version:

if( $page->parents()->count() ) {

I’ve not tested it because I’m not at work today but if it works it’s probably the shortest and simplest solution. I’ll change the secret tomorrow after testing it out. :slight_smile: