【发布时间】:2015-08-27 00:02:07
【问题描述】:
我的 yii2 setter 有问题,我在另一个表中有一个名为“role”的字段,用户和角色与表“user_role”中的 user_id 链接,getter 可以找到,但 setter 不起作用,yii2不调用setter函数!! ,我尝试了太多东西,但“规则”中的“角色”字段功能安全,但没有帮助,我在用户类中将 $role 写为公共变量,我尝试将其作为私有但也没有工作,我不知道哪里错了!!
class User extends BaseUser
{
public $givenname;
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['role'], 'safe'],
];
}
public function getRole()
{
$sql = 'SELECT item_name FROM "user_rules" WHERE user_id = :userId';
$command = Yii::$app->db->createCommand($sql);
$command->bindValue(':userId', (int)$this->id, PDO::PARAM_INT);
return $command->queryScalar();
}
public function setRole($newRole)
{
die("SetRole has been called now " );
// Save role in the DB
.................
}
/**
* @return type array list of the system roles
*/
public static function getSystemRoles()
{
return array(
'sysadmin' => 'sysadmin',
'admin' => 'admin',
'editor' => 'editor',
'member' => 'member',
'register' => 'register'
);
}
在我的控制器中,这里是更新操作:
/**
* Updates an existing User model.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
Url::remember('', 'actions-redirect');
$user = $this->findModel($id);
$user->scenario = 'update';
$this->performAjaxValidation($user);
if ($user->load(Yii::$app->request->post()) && $user->save()) {
Yii::$app->getSession()->setFlash('success', Yii::t('user', 'Account details have been updated'));
return $this->refresh();
}
return $this->render('_account', [
'user' => $user,
]);
}
//--------------------------
在我的视图文件中:
<?= $form->field($user, 'role')->dropDownList(User::getSystemRoles(), ['class' => 'form-control col-sm-2']); ?>
你有什么想法吗?你能帮帮我吗?
问候 韦尔
【问题讨论】: