In my blueprint author is a required field but you can create a new page and make it visible on the front-end without completing the author field and saving.
Regardless, the author field is empty
<?php if($avatar = $site->user($page->author()->value())->avatar()->crop(40)): ?>
<img width="40" height="40" src="<?php echo $avatar->url() ?>" alt="avatar">
<?php endif ?>
And I get the following error:
Call to a member function avatar() on a non-object
How can I stop this error in the event a page is made visible with empty fields?
Thanks
You can check if the field is empty and only proceed if not. [untested]
<?php
// check if author field is not empty
if ($page->author()->isNotEmpty()) {
$author = $page->author()->value();
// get the user if exists
if ($user = $site->user($author)) {
// get the avatar and crop it
$avatar = $user->avatar()->crop(40);
}
}
?>
<?php if(!empty($avatar)): ?>
<img width="40" height="40" src="<?php echo $avatar->url() ?>" alt="avatar">
<?php endif ?>
You can keep your template clean, if you move the logic to a controller.
1 Like
Additionally, you could use permissions to prevent changing the status of a page unless the field is filled in: https://getkirby.com/docs/cheatsheet/permissions/panel-page-visibility