Newbie: Call to a member function url() on a non-object

Hi guys,

First time user of Kirby and so far loving it. I’m playing with the default installation of Kirby. In the about.php template we have:

<img src="<?= $member->image()->url() ?>" alt="Portrait of <?= $member->title()->html() ?>" />

This works, however, if I delete a photo (i.e., if there are no images), a fatal error is triggered: Call to a member function url() on a non-object. I guess because there’s no image found.

What’s the best solution to prevent this error? Assuming editors can preview the page without adding images (triggering the error).

Thank you.

Hey @rodrigogalindez,

welcome to the Kirby community.

When dealing with objects (no matter if images, pages or whatever) it is necessary to make sure that the object exists before trying to call a class method:

<?php if($image = $member->image()): ?>
  <img src="<?= $image->url() ?>" alt="Portrait of <?= $member->title()->html() ?>" />
<?php endif ?>

This is a general rule/best practice, because you can never be sure that an object really exists.


Thank you, I understand now. Is there a way to force to upload an image before saving the page in the Panel?

No, you can’t force an upload. An indirect way of forcing an upload would be to use an image field, and require that field to be filled. However, even if you do that, stick with the if statement, just to be on the safe side.

Edit: If you use the image field, you will have to modify your code, so that the image is picked from that field.

1 Like