Crop() method breaks page

Hello,

I’ve recently watched all the YouTube tutorials on the Kirby channel. However, I hit one snag along the way with the crop() method, and it’s keeping my new project from functioning as well. I’m attempting to crop and display the first image of each child page, on the parent page.

This code works,

    <?php foreach ($page->children()->listed() as $project): ?>
        
        <a href="<?= $project->url() ?>">
            <figure>
                <?= $project->image() ?>
            </figure>
        </a>

    <?php endforeach ?>

while this code does not.

    <?php foreach ($page->children()->listed() as $project): ?>
        
        <a href="<?= $project->url() ?>">
            <figure>
                <?= $project->image()->crop(320, 180) ?>
            </figure>
        </a>

    <?php endforeach ?>

My debugger gives the following:

Call to a member function crop() on null

which I don’t understand the meaning of. I’m running my site locally on PHP version 7.3.24. Any help would be much appreciated! :slightly_smiling_face:

You need to check if your image is valid. Try this:

<?php foreach ($page->children()->listed() as $project): ?>
        
    <a href="<?= $project->url() ?>">
        <?php if ($image = $project->yourImageFieldName()->toFile()): ?>
            <figure>
                <img src="<?= $image->crop(320, 180)->url() ?>">
            </figure>
        <?php endif ?>
    </a>

<?php endforeach ?>

Replace yourImageFieldName with the name of the field you set in your blueprint.

1 Like

Well, I solved the problem, and actually using my original code that was causing the page to crash in the first place. It had to do with the blueprints and pages that I was attempting to pull from either not being complete/being published/existing. :tired_face: Thank you @Fluxium for your help though! Your answer made me realize that I needed to flesh the rest of the site out.