Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii::app()->user->id; gets name of user not ID

Tags:

yii

I am trying to get the user id but no luck so far...

echo Yii::app()->user->id;

and

echo Yii::app()->user->getId();

return the name of user which is weird. Any idea what is wrong?

like image 723
Symfony Avatar asked Dec 21 '11 05:12

Symfony


3 Answers

Yii::app()->user returns a component CWebUser by default.

When you want to get some additional information about user, you need to extend this component.

Create a file WebUser.php in your components folder. (my example below)

class WebUser extends CWebUser {
    /**
     * Gets the FullName of user
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->_model->first_name . ' ' .$this->_model->last_name;
    }
}

In your config file find section

'components'=>array(
'user'=>array(
'class'=>'WebUser'
)
)

if there is no this section , just create it. And change 'class'=> to WebUser'.

like image 75
RusAlex Avatar answered Nov 03 '22 13:11

RusAlex


you should have getId function in user Identity

like image 31
Afnan Bashir Avatar answered Nov 03 '22 14:11

Afnan Bashir


Or you are can use setState:

class UserIdentity extends CUserIdentity
{
    private $_id;
    public function authenticate()
    {
        $record=Users::model()->findByAttributes(array('mail'=>$this->username));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($record->password!==md5($this->password."325"))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id = $record->id;
            $this->setState('role', $record->active);
            $this->setState('mail', $record->mail);
            $this->setState('name', $record->name);
            $this->setState('surname', $record->surname);
            $this->setState('mobile', $record->mobile);
            $this->setState('adress', $record->adress);
            $record->count_login += 1;
            $record->update();
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId()
    {
        return $this->_id;
    }

}


<?php echo Yii::app()->user->name." ".Yii::app()->user->surname; ?>
like image 35
Arthur Yakovlev Avatar answered Nov 03 '22 13:11

Arthur Yakovlev