user7282
user7282

Reputation: 5196

Add a new user Identity value in Yii2

I need to assign a new variable to user identity like

 Yii::$app->user->identity->staff_name = 'myName';

I have added public $staff_name; in the identityClass , which is usually common\models\User, but in my case is common\models\Person.

But when I print Yii::$app->user->identity the

Yii::$app->user->identity->staff_name value is blank.

Why it is blank ?

Upvotes: 0

Views: 1289

Answers (2)

fammi farendra
fammi farendra

Reputation: 17

Using rules does not works for me Instead i use a public parameter

public $staff_name='';

Then you can set it via afterfind like this

public function afterFind() {
    parent::afterFind ();
    $this->staff_name=\common\models\staff::findOne($this->staffid)->staffname;
}

Suppose you get staff name in your staff table, so

$this->staff_name is your public parameter \common\models\staff is your models of staff table in common\models namespace

$this->staffid is your staff id in your user identity staffname is your staff name field in your staff table

then you can use it like Yii::$app->user->identity->staff_name

Upvotes: 0

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

Steps to follow

  • You should add the public attribute staff_name to the safe rules

see below

public function rules(){
       return[
            [['staff_name'],'safe']
       ] ;
}
  • If you are using dektrium/yii2-user use the following way to add to the parent rules

add to your Person model

public function rules() {
        return array_merge (parent::rules (), [ 'staff_nameSafe' => ['staff_name' , 'safe' ] ] );
    }
  • Then you need to load this attribute manually too it won't have the value automatically like other model attributes which are the actual table fields so use afterFind in your Person model like below.

Note: i am using the hardcoded string SAMPLE STAFF NAME for the staff_name adjust it according to your needs

public function afterFind() {
    parent::afterFind ();
    $this->staff_name="SAMPLE STAFF NAME";
}

Test

Now you can use print_r(Yii::$app->user->identity->staff_name); and it will print the name

SAMPLE STAFF NAME

Upvotes: 1

Related Questions