Can't evaluate a return value for menu item

Hi,

My php is at best rusty, and I am struggling with the simplest of tasks

I am building my navigation and want an optional field (menu_title) to be used if it’s available otherwise fallback on title

To illustrate a var_dump of two menu items

// var_dump($child->menu_title());
    object(Kirby\Cms\Field)#292 (1) {
      ["menu_title"]=>
      string(25) "Engineering Visualisation"
    }
    object(Kirby\Cms\Field)#295 (1) {
      ["menu_title"]=>
      NULL
    }

NULL should evaluate to false, yes? Is that not what is being returned when I call the getter ->menu_title()

my first thought was I could use the following to output my anchor text
<?= ($child->menu_title() || $child->title())->html() ?>

even this fails
if (!($child->menu_title())) echo 'menu-title is null';

or

if(is_null($child->menu_title())) echo 'menu-title is null';

Thanks for any help.

In the latest Kirby you could use <?= $page->menu_title()->or($page->title()) ?>.

1 Like

Thanks bvdputte, your solution works a treat!

What dawned on me is the fact you can chain a method call e.g. ->html() on the end, is menu_title() actually returning an object, rather than a property?

Yes, menu_title returns a field object, not a string.

Note that not all field methods return a Field object, but you can find the return type of each method in the documentation.

1 Like

@pixelijn

Thanks for clearing that up, much appreciated.