如何给一个注册用户添加一个权限或角色
在gii中生成model文件AuthItem.php和AuthAssignment.php
- 修改SignupForm文件
class SignupForm extends Model{
# code...
public $permissions ;
# code...
}
2.修改SiteController文件
use backend \models\ AuthItem;
public function actionSignup()
{
$model = new SignupForm();
$authItems =AuthItem:: find()-> all();
if ($model-> load(Yii ::$app-> request->post ())) {
if ($user = $model->signup ()) {
if (Yii:: $app->getUser ()->login ($user)) {
return $this ->goHome();
}
}
}
return $this->render ('signup', [
'model' => $model,
'authItems' =>$authItems
]);
}
3.修改signup.php文件
# code...
use
yii\helpers \ArrayHelper;# code...
<?php
$authItems
=ArrayHelper ::map( $authItems,'name' ,'name');?>
<?=
$form->field ($model, 'permissions')-> checkboxList($authItems ); ?># code...
4.修改SignupForm文件
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if ($this-> validate()) {
$user = new User();
$user ->username = $this->username ;
$user ->email = $this->email ;
$user ->setPassword( $this->password );
$user ->generateAuthKey();
$user ->save();
$permissionList =$_POST[ 'SignupForm']['permissions' ];
// lets add the permissions
foreach( $permissionList as $value ){
$newPermissions =new AuthAssignment ();
$newPermissions ->user_id= $user->id ;
$newPermissions ->item_name= $value;
$newPermissions ->save();
}
return $user ;
}
return null ;
}
来自于datou:https://github.com/datou-leo/ci