Example #1
0
 public function actionEdit()
 {
     $auth = Yii::$app->authManager;
     $data = Yii::$app->request->post('UserForm');
     $result = array();
     $oldPassword;
     //更改用户时如果不改密码,保存旧密码
     if (is_numeric($data['id']) && $data['id'] > 0) {
         $user = UserForm::findOne($data['id']);
         if (!$user) {
             $result['status'] = 0;
             $result['message'] = '未找到该记录';
         } else {
             $oldPassword = $user->password;
         }
     } else {
         $user = new UserForm();
     }
     if ($user->load(Yii::$app->request->post())) {
         if (!$user->isNewRecord && $user->password != '******') {
             $oldPassword = Yii::$app->security->generatePasswordHash($user->password);
         }
         if ($user->save()) {
             if (isset($oldPassword)) {
                 //重置密码
                 UserForm::updateAll(['password' => $oldPassword], 'id=:id', [':id' => $user->id]);
             }
             //分配权限
             $auth->revokeAll($user->id);
             //删除所有权限
             foreach ($user->roles as $rolename) {
                 if ($role = $auth->getRole($rolename)) {
                     $auth->assign($role, $user->id);
                 }
             }
             $result['status'] = 1;
             $result['message'] = '保存成功';
         }
     }
     $errors = $user->getFirstErrors();
     if ($errors) {
         $result['status'] = 0;
         $result['message'] = current($errors);
     }
     return $this->renderJson($result);
 }