specialnot 2015-10-13 11:19:16 5731次浏览 1条评论 4 0 0

1. 控制器

<?php
namespace backend\controllers;

use common\models\RoleForm;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

class RoleController extends BaseController{
    public function actionIndex(){
        $authManager = \Yii::$app->authManager;
        $roles = $authManager->getRoles();
        return $this->render('index',[
            'roles'=>$roles,
        ]);
    }

    public function actionCreate(){
        $model = new RoleForm();

        if($model->load(\Yii::$app->request->post()) && $model->save()){
            \Yii::$app->session->setFlash('success','角色['.$model->name.']添加成功');
            return $this->redirect(['/role/index']);
        }else{
            return $this->render('create',[
                'model'=>$model,
            ]);
        }
    }

    public function actionUpdate($name){
        $authManager = \Yii::$app->authManager;
        $child = $authManager->getChildren($name);
        if($child){
            \Yii::$app->session->setFlash('success','角色['.$name.']有用户,不能修改');
            return $this->redirect(['/role/index']);
        }

        $role = $authManager->getRole($name);
        if(!$role) return false;
        $model = new RoleForm();
        $model->name = $role->name;
        $model->description = $role->description;

        if($model->load(\Yii::$app->request->post()) && $model->update($name)){
            \Yii::$app->session->setFlash('success','角色['.$name.']修改成功');
            return $this->redirect(['/role/index']);
        }else{
            return $this->render('update',[
                'model'=>$model,
            ]);
        }
    }

    public function actionDelete($name){
        $authManager = \Yii::$app->authManager;
        $child = $authManager->getChildren($name);
        if($child){
            \Yii::$app->session->setFlash('success','节点['.$name.']有子节点,不能删除');
            return $this->redirect(['/node/index']);
        }
        $role = $authManager->getRole($name);
        if(!$role) return false;
        if($authManager->remove($role)){
            \Yii::$app->session->setFlash('success','节点['.$name.']删除成功');
        }else{
            \Yii::$app->session->setFlash('error','节点['.$name.']删除失败');
        }
        return $this->redirect(['/role/index']);
    }

    public function actionNode($name){
        $authManager = \Yii::$app->authManager;
        $role = $authManager->getRole($name);
        if(!$role){
            throw new Exception('节点未找到');
        }
        if(\Yii::$app->request->isPost){
            $nodes = \Yii::$app->request->post('node');
            $authManager->removeChildren($role);
            foreach($nodes as $v){
                $node = $authManager->getPermission($v);
                if(!$node)continue;
                $authManager->addChild($role,$node);
            }
            return $this->redirect(['/role/index']);
        }
        $roleNodes = $authManager->getPermissionsByRole($name);
        $roleNodes = array_keys($roleNodes);
        $nodes = $authManager->getPermissions();
        return $this->render('node',[
            'nodes'=>$nodes,
            'roleNodes'=>$roleNodes,
            'name'=>$name,
        ]);
    }

}

2. 视图

2.1. index.php

<?php

use yii\helpers\Html;
use yii\grid\GridView;


$this->title = '角色';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="node-index">


    <p>
        <?= Html::a('新建角色', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>角色名称</th>
                <th>角色描述</th>
                <th>操 作</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($roles as $v){?>
            <tr>
                <td><?= $v->name?></td>
                <td><?= $v->description?></td>
                <td style="width: 140px;">
                    <?= Html::a('修改',['/role/update','name'=>$v->name])?>
                    &nbsp;
                    <?= Html::a('权限',['/role/node','name'=>$v->name])?>
                    &nbsp;
                    <?= Html::a('删除',['/role/delete','name'=>$v->name],[
                        'data' => [
                            'confirm' => '确认删除吗?',
                            'method' => 'post',
                        ]
                    ])?>
                </td>
            </tr>
        <?php }?>
        </tbody>
    </table>


</div>

2.2. create.php

<?php
    use yii\widgets\ActiveForm;
    use yii\helpers\Html;

    $this->title = '创建角色';
    $this->params['breadcrumbs'][] = ['label'=>'角色','url'=>['/role/index']];
    $this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
    <?php $form=ActiveForm::begin()?>
        <div class="col-md-6">
            <?= $form->field($model,'name')->textInput(['maxlength'=>true])->hint('角色名称由小写字母开头,3-20位字符(a-z-_)组成')?>
        </div>
        <div class="col-md-8">
            <?= $form->field($model,'description')->textarea(['rows'=>3])?>
        </div>
        <div class="col-md-8">
            <?=Html::submitButton((Yii::$app->controller->action->id == 'create')?'新建':'更新',['class'=>'btn btn-primary'])?>
        </div>
    <?php ActiveForm::end()?>
</div>

2.3. update.php

<?php
    use yii\widgets\ActiveForm;
    use yii\helpers\Html;

    $this->title = '更新角色';
    $this->params['breadcrumbs'][] = ['label'=>'节点','url'=>['/node/index']];
    $this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
    <?php $form=ActiveForm::begin()?>
        <div class="col-md-6">
            <?= $form->field($model,'name')->textInput(['maxlength'=>true,'value'=>$model->name])->hint('角色名称由小写字母开头,3-20位字符(a-z-_)组成')?>
        </div>
        <div class="col-md-8">
            <?= $form->field($model,'description')->textarea(['rows'=>3,'value'=>$model->description])?>
        </div>
        <div class="col-md-8">
            <?=Html::submitButton((Yii::$app->controller->action->id == 'create')?'新建':'更新',['class'=>'btn btn-primary'])?>
        </div>
    <?php ActiveForm::end()?>
</div>

2.4. node.php

<?php

use yii\helpers\Html;


$this->title = '权限';
$this->params['breadcrumbs'][] = ['label'=>'角色','url'=>['/role/index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="node-index col-md-6">
    <?= Html::beginForm(['/role/node','name'=>$name],'post')?>
    <table class="table table-striped">
        <thead>
            <tr>
                <th><?= Html::checkbox('check',false,['id'=>'check_all'])?></th>
                <th>权限名称</th>
                <th>标书</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($nodes as $v){?>
            <tr>
                <td><?= Html::checkbox('node[]',in_array($v->name,$roleNodes)?true:false,['value'=>$v->name,'class'=>'node_check'])?></td>
                <td><?= $v->name?></td>
                <td><?= $v->description?></td>
            </tr>
        <?php }?>
        </tbody>
    </table>
    <div>
        <?= Html::submitButton('提交',['class'=>'btn btn-primary'])?>
    </div>
    <?= Html::endForm()?>

</div>
<?php
    $this->registerJs(
        <<<ENT
       $('#check_all').click(function(){
            if($(this).is(':checked')){
                $('.node_check').attr('checked',true);
            }else{
                $('.node_check').attr('checked',false);
            }
        });
ENT
    );
?>
  1. 模型
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\helpers\Html;

class RoleForm extends Model
{
    public $name;
    public $description;

    public function rules(){
        return [
            [['name'],'string','max'=>20],
            [['name','description'],'required'],
            ['name','match','pattern'=>'/^[a-z][a-z-_]{2,20}$/','message'=>'name属性不合法'],
            ['description','filter','filter'=>function($value){
                return Html::encode($value);
            }],
        ];
    }


    public function attributeLabels(){
        return [
            'name'=>'角色名称',
            'description'=>'角色描述',
        ];
    }

   public function save(){
        if($this->validate()){
            $authManager = Yii::$app->authManager;
            $role = $authManager->createRole($this->name);
            $role->description = $this->description;
            $authManager->add($role);
            return true;
        }else{
            return false;
        }
    }

    public function update($name){
        if($this->validate()){
            $authManager = Yii::$app->authManager;
            $role = $authManager->getRole($name);
            if(!$role) return false;
            $authManager->remove($role);

            $role = $authManager->createRole($this->name);
            $role->description = $this->description;
            $authManager->add($role);
            return true;
        }
        return false;
    }

  
}
您需要登录后才可以评论。登录 | 立即注册