Why is "isNotEmpty()" on a "null"?

Hey guys,

I just had a website running and my client uploaded some projects. After some time, an error occurred. In my test version on my Mac everything worked out just fine so I actually don’t know where to start.

The pages shows 5 different categories of his projects. I did the categorization with checkboxes and on the frontend with filterBy. For example for all city projects I do: <?php foreach($projects->filterBy('categories', 'city') as $city): ?>

It stopped working somehow. Here is the complete code:

      <?php foreach($projects->filterBy('categories', 'city') as $city): ?>

    <div class="category-item">
      <a href="<?= $city->url() ?>">
        <img src="<?= $city->image()->crop(500)->url() ?>" class="img-responsive">
      </a>
    </div>

  <?php endforeach ?>

I’m stuck here, I hope somebody has a tip :slight_smile:

What does the error tell us?

Without any further information, I can only guess and think the error is likely caused because you call the url() method without prior checking if you have an corresponding object, in this case a file object. Never call a class method without checking if you actually have an object!

 <div class="category-item">
      <a href="<?= $city->url() ?>">
      <?php if($image = $city->image() ?>
        <img src="<?= $image->crop(500)->url() ?>" class="img-responsive">
     <?php endif ?>
      </a>
    </div>

Depending on your use case, you might want to put the if-statement around the complete div or put something else instead of the image within the anker element, so as not to end up with an empty element in case there is no image.

Edit: In your topic title, you mention the isNotEmpty() method, but I can’t see it being used in your code?

– (not a guy)

With guys I meant a group of people, not a single male :slight_smile: Sorry for that.

You’re right, I forgot the isNotEmpty() on that code. Here is the right one:

      <?php foreach($projects->filterBy('categories', 'city') as $city): ?>
    <?php if($city->image()->isNotEmpty()): ?>
    <div class="category-item">
      <a href="<?= $city->url() ?>">
        <img src="<?= $city->image()->crop(500)->url() ?>" class="img-responsive">
      </a>
    </div>
    <?php endif ?>

  <?php endforeach ?>

The error I get is:

Error thrown with message “Call to a member function isNotEmpty() on null”

Is image a field in your content file? If so, you’d better rename it, because image() is a native Kirby method.

Oh damn. That’s awkward. :sweat_smile:

I’ve found the error. My client did not upload any pictures to the project files. With you the if statement, I just works fine. Thanks!

As I tried to say above, whenever you deal with objects and their methods (pages, fields, files etc.), always use an if-statement (or equivalent) to check if you have an object first, otherwise you are doomed to run into errors over and over again.

2 Likes

Pretty good point! Thanks for the advice! :slight_smile: