Reputation: 5196
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
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
Reputation: 23738
Steps to follow
staff_name
to the safe
rulessee below
public function rules(){
return[
[['staff_name'],'safe']
] ;
}
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' ] ] );
}
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