Uncaught error: Call to a member function url() on null

$menu is a page object:

<?php var_dump($menu->files()->first()->url()); ?>
[Thu Mar 17 19:47:12 2016] [500]: / - Uncaught Error: Call to a member function url() on null in /home/manu/Desktop/napoli/site/templates/home.php:10
Stack trace:
#0 /home/manu/Desktop/napoli/kirby/toolkit/lib/tpl.php(22): require()
#1 /home/manu/Desktop/napoli/kirby/kirby.php(705): Tpl::load('/home/manu/Desk...')
#2 /home/manu/Desktop/napoli/kirby/kirby.php(680): Kirby->template(Object(Page), Array)
#3 /home/manu/Desktop/napoli/kirby/kirby.php(781): Kirby->render(Object(Page))
#4 /home/manu/Desktop/napoli/index.php(16): Kirby->launch()
#5 {main}
  thrown in /home/manu/Desktop/napoli/site/templates/home.php on line 10

Also when I do var_dump $menu->files() I always get the whole $menu page object instead of just the files array.

You can use the toArray() method on the files collection to get a simple array: https://getkirby.com/docs/cheatsheet/files/to-array

Does the file exist?

I itterate through a collection of pages, some of them have files, but not all.

Then you need to check if files exist before trying to get an URL, otherwise the error if no files exist:

if($page->hasFiles()) {
//get the url of the first file

You should shield the call to url() on the (possibly null) file object:

<? foreach ( $menu_items as $item ) { ?>
    <? if ( $item->hasFiles() ) { ?>
      <li><?= $item->files()->first()->url() ?></li>
    <? } else { ?>
    <? } ?>
<? } ?>

Dangit, @texnixe is too quick!

1 Like

Yes that’s it!

Why do I need toArray() I remember in older versions of kirby I didnt need to do so and var_dump worked as expected. It is really annoying to get the whole page object with all the stuff in there all the time.

I need to read about collection. I thought it is the same as an array. Seems to be a kirby related thing.

A colllection is of type object, not of type array. I don’t think it ever worked to just output the files, but I may be mistaken.

I would expect at least kirby’s integrated dump utility would work like that. :cat:

Is there any good way to dump objects in a more comfy way? If I write them in a 20% column I could never really read what’s going on in there. Do you know of an utility or how do you deal with? console.log() as workaround?

No, the dump() method basically does the same as var_dump(), just gives you a more readable output.

FYI: You can use gettype() (PHP function) to check the type of a variable.

1 Like

You might want to check out xdebug

Thank you all, you so kind :kissing_cat: