Kirby

Can't crop image File object returned by page method

I have a plugin defining a global page method to return a hero image for any page on my site:

'my_seoHero' => function () {
  if($this->seo_hero() != ''){
  	$hero = $this->seo_hero()->toFile();
  }elseif($this->hero() != ''){
  	$hero = $this->hero()->toFile();
  }elseif(count($this->images()->template('hero')) > 0){
  	$hero = $this->images()->template('hero')->current();
  }else{
  	$hero = site()->hero()->toFile();
  }
  return $hero;
},

This code works as intended wherever I need it (returning a File object when I call $page->my_seoHero()). But since this is a File object, why can’t I crop it using $page->my_seoHero()->crop(500,500)->url()? I get a “Call to a member function crop() on null” error.

Any help would be appreciated.

if ($hero = $page->my_seoHero()) {
  echo $hero->crop(500,500)->url();
}

Thanks for your help. This is a nice quick fix!

Why doesn’t my code work, though? You will see my page method is structured to ensure an image is always returned, so the crop error should never happen. Can you help me understand the logic that makes your code work and mine not?

Well, first of all, you can never be sure that you get an image, so checking if your really have an image object is imperative, anyway.

But I think the problem here might be that you have to store your image in a variable first to create the object, then call any methods on it. It might even work if you wrap it in parenthesis ($page->my_seoHero())->crop(), but I’d still recommend the if statement, or as a one-liner:

echo ($hero = $page->my_seoHero()) ?  $hero->crop(500,500)->url() : '';
1 Like