我尝试在SignupForm
中注册时为用户分配一个角色(RBAC)public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->role = $this->role;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
$myRole = '';
switch ($user->role) {
case 0:
$myRole = 'developer';
break;
case 1:
$myRole = 'project_manager';
break;
case 2:
$myRole = 'customer';
break;
}
$auth = Yii::$app->authManager;
$role = $auth->getRole($myRole);
$auth->assign($role, $user->id);
return true;
}
查看注册
<?= $form->field($model, 'role')->dropDownList(
[
'0' => 'Developer',
'1' => 'Project Manager',
'2' => 'Customer'
],
['prompt' => 'Choose your role..']) ?>
它不起作用...表auth_assignment不会更新,但表用户更新。 如果我将这段代码插入到User.php中的AfterSave方法
中$myRole = '';
switch ($user->role) {
case 0:
$myRole = 'developer';
break;
case 1:
$myRole = 'project_manager';
break;
case 2:
$myRole = 'customer';
break;
}
$auth = Yii::$app->authManager;
$role = $auth->getRole($myRole);
$auth->assign($role, $user->id);
工作正常...... 谁可以解释,为什么会这样?
答案 0 :(得分:3)
此方法中间有return
,因此return $user->save() ? $user : null;
之后的所有内容都是死代码。
您可能需要将其替换为:
if (!$model->save()) {
return null;
}
答案 1 :(得分:1)
我认为这与此有很大关系
return $user->save() ? $user : null;
您在save()方法之后返回用户或null,因此您之后编写的任何代码都不会实际执行。
如果您只想在保存成功后分配角色,您可以这样做:
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->role = $this->role;
$user->setPassword($this->password);
$user->generateAuthKey();
if($user->save())
{
$myRole = '';
switch ($user->role) {
case 0:
$myRole = 'developer';
break;
case 1:
$myRole = 'project_manager';
break;
case 2:
$myRole = 'customer';
break;
}
$auth = Yii::$app->authManager;
$role = $auth->getRole($myRole);
$auth->assign($role, $user->id);
return true;
}
else
return false;