how to get Current role name


how to get RBAC current role name

i tried :


$role = Yii::app()->authManager->getRoles(Yii::app()->user->id);

echo "<br /><h1>" . $role->itemname . "</h1>";


but not work, return array


If it returns an array, then it works. ;)

it return :

Array ( [deletePost] => CAuthItem Object ( [_auth:private] => CDbAuthManager Object ( [connectionID] => db [itemTable] => AuthItem [itemChildTable] => AuthItemChild [assignmentTable] => AuthAssignment [db] => CDbConnection Object ( [connectionString] => mysql:host=localhost

how to get "deletePost" String in this array

when i try :

echo $role->itemname

not works

you could write a getRole in your user model

public function getRole() 


        $role = Yii::app()->db->createCommand()



		->where('userid=:id', array(':id'=>$this->id))


	return $role;


I found a direct query to be the easiest way to get a user’s role.

Hi jpm, thanks for reply

i call this method from views/layout/main.php

$q = Users::model();

echo $q->getRole();

return empty

wether AuthAsignment table must have class in model ?

No this has nothing to do of having a model. It is a direct command to database. Do that select statement inside the db. Does it work?

‘getRoles’ returns an array, obviously:

It returns an associative array in this form: [color=#222222][font=Arial, sans-serif][size=2]name=>CAuthItem[/size][/font][/color]

Why do you need it?

Wouldn’t CWebUser::checkAccess(‘deletePost’) work?

hi jacmoe,

how to get this name name=>CAuthItem from $role = Yii::app()->authManager->getRoles(Yii::app()->user->id);

i need it for global variable in each page

<div id="role-name"><?php echo $roleName?></div>

if i write all of rolename


$roleName = ‘deletePost’;

}else if(checkAccess(‘readPost’)){

$roleName = ‘readPost’;


it will spend alot of code


The query I wrote will only work if you have a record already loaded. in the code above you are not loading a record from the database.

$q = Users::model()->findByPk(1);

echo $q->getRole();

should give you the role of the user with the primary key of 1, assuming you have assigned a role to that user.

Hi jpm thank you very much

$q = Users::model()->findByPk(Yii::app()->user->id);

			echo $q->getRole();

it Works fine



foreach (roles as $role)


    echo $role->name;