specialnot 2015-10-13 11:21:19 4712次浏览 0条评论 1 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>
觉得很赞
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册