Error when changing page author

Permalink
I get the following error (see below) when changing the page author. So only after changing the author I get this error. 1 user is adding blog items but want to change the autor so the page is displaying a other profile picture and name.

"Call to a member function getUserName() on null"


The script that is causing the error is:
<?php $userID = $c->getCollectionUserID(); 
   $u = User::getByUserID($userID);
   $UserName = $u->getUserName();
   echo $UserName;
?>


My quick fix (found here on forum) for not trowing an error:
<?php $ownerID = UserInfo::getByID($page->getCollectionUserID());
                    if (is_object($ownerID)) {
                        $name = $ownerID->getUserName();
                        echo $name;
                    } else {
                        $name = 'Test Name';
                        echo $name;
                    }?>


Any Idea why this is happening and how to fix this.

Core Version - 8.4.4
Version Installed - 8.4.4

 
Shubham2961995 replied on at Permalink Reply
Hi,

The $userID is null. Did you tried to print value of $userID?
studio4graphics replied on at Permalink Reply
Hi, thank you for your reply.

I am not a programmer so I do not fully understand what you mean.
Instead of echo use print? Can you please elaborate?
Shubham2961995 replied on at Permalink Reply
Yes. I meant print_r instead of echo, so that you find whether it is returning any value or not.
Also, I found below code in other thread:
echo $u->getByUserID($comment->getUID())->getUserName();

Try this.
studio4graphics replied on at Permalink Reply
I get errors when trying to get any results:
Call to a member function getUserName() on null


I found and edited the following code that works:
<?php 
                    $ownerID = UserInfo::getByID($page->getCollectionUserID());
                    $uID = $c->getCollectionUserID();
                    if($uID) {
                       $ui = UserInfo::getByID($uID);
                    }
                    if($ui) {
                       $firstName = $ownerID->getUserName();
                       $lastName = $ui->getAttribute('last_name');
                       $avatar = $ui->getUserAvatar();
                       if ($ui->hasAvatar()) {
                               $av = $avatar->output(80, 80, true);
                       }
                        else {
                               $av = '<img src="'. $this->getThemePath() .'/images/no-user-avatar.png" alt="">';


Thanks for your help.