When trying to display first and last name of page author I get:
Call to a member function firstName() on a non-object
In blueprint:
title: Article
files: true
fields:
title:
label: Title
type: text
author:
label: Author
type: user
text:
label: Text
type: textarea
In template:
<?php
$author = $page->author();
echo $site->user($author)->firstName() . " " . $site->user($author)->lastName();
?>
Can anyone help?
Thanks
This happens if the user object does not exist. You should always check if the object on which you want to call a method, actually exists:
<?php
$author = $page->author();
$user = $site->user($author);
if($user) {
echo $user->firstName() . " " . $user->lastName();
}
?>
If the author field is empty or if the username is wrong, $user
will evaluate to false, and the object methods firstname()
and last name()
will not be called, thus preventing the error.
OK I will do that but in this case the user does exist and they are set as the author of the page?


Well, that user looks more dead than alive 
Are you testing this on a single page or on a blog page with more than one child where other pages may not have a user selected?
Very much alive precious!
It is a single page content/home/category/page
If I replace $author with ‘admin’ it spits out the correct full name?
$user = $site->user('admin');
What does $page->author()
return?
On a page with admin as author it returns nothing
On a page with any other user as author it returns the username
So everything works fine as long as the author is not admin?
Hm, that’s weird and I can’t reproduce this (ok, it’s probably not the best choice to call the admin admin unless you are on localhost, but that’s another story). If I create a user called admin, it still spits out her name.
OK I tried with a fresh site and it worked fine.
So I went back to the problem site, changed the author of the problem page to another user then back to admin, and it worked!
It seems when you create a page the author field defaults to admin but you have to save again for it to take effect.
Nevertheless, I recommend to make a habit of checking for an object, and not only for users, but also for images or any other objects that might not exist when you try to do something with them.
2 Likes
I will do that, thanks for the great support
1 Like