RBAC 为用户选择角色 [ 1.0 版本 ]
1、在 user/index.php 中添加权限按钮
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{view} {update} {delete} {options}',
'options'=>['width'=>'100'],
'buttons'=>[
'options'=>function($url,$model,$key){
return Html::a('权限',['/user/role','id'=>$model->id]);
}
],
],
2、 在 UserController.php 中添加权限方法
#为用户选择角色
public function actionRole($id){
$user = User::findOne($id);
if(!$user) throw new NotFoundHttpException('用户未找到');
$authManager = Yii::$app->authManager;
if(Yii::$app->request->isPost){
$roleNames=Yii::$app->request->post('roles');
$authManager->revokeAll($id);
if(!empty($roleNames)&&is_array($roleNames)){
foreach($roleNames as $roleName){
$role=$authManager->getRole($roleName);
if(!$role){
continue;
}
$authManager->assign($role,$id);
}
}
Yii::$app->session->setFlash('success','更新成功');
$this->redirect(['role','id'=>$id]);
}else{
$userRoles=$authManager->getRolesByUser($id);
$roleNames=ArrayHelper::getColumn(ArrayHelper::toArray($userRoles),'name');
$roles=$authManager->getRoles();
return $this->render('role',['roles'=>$roles,'roleNames'=>$roleNames]);
}
}
3、user/role.php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = '角色权限';
$this->params['breadcrumbs'][] = ['label' => '管理员', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
$action=Yii::$app->controller->action->id;
?>
<div class="role-node">
<?=Html::beginForm() ?>
<?php foreach($roles as $role): ?>
<?= Html::checkbox('roles[]',in_array($role->name,$roleNames),['value'=>$role->name,'id'=>$role->name]) ?>
<?= Html::label($role->description,$role->name) ?>
<?php endforeach; ?>
<p><?= Html::submitButton('保存',['class'=>'btn btn-primary']) ?></p>
<?= Html::endForm() ?>
</div>
specialnot
注册时间:2015-08-06
最后登录:2019-08-16
在线时长:27小时54分
最后登录:2019-08-16
在线时长:27小时54分
- 粉丝43
- 金钱1175
- 威望200
- 积分3445
共 0 条评论