如何在更新信息时回避用户的当前用户名和密码?例如 - 当我尝试仅更新名称时,它会向我显示已经收到电子邮件,反之亦然。这样我就不能只更新或只更新电子邮件,只能更新它们。 我的actionUpdate:
public function actionUpdate()
{
$model = new UpdateForm();
$id = \Yii::$app->user->identity->id;
$user = $this->findModel($id);
//default values
$model->username = $user->username;
$model->email = $user->email;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if (isset($_POST['UpdateForm']))
{
$model->attributes = $_POST['UpdateForm'];
if($model->validate())
{
$user->username = $model->username;
$user->email = $model->email;
$user->password = md5($model->password);
$user->update();
$this->redirect(['view', 'id' => $user->id]);
}
}
else
{
return $this->render('update', [
'model' => $model,
]);
}
}
我的UpdateForm规则:
public function rules()
{
return [
[['email', 'password', 'username'], 'required'],
[['email', 'password', 'username'], 'string', 'max' => 50],
[['image'], 'string', 'max' => 255],
[['username', 'password', 'email'], 'trim'],
['email', 'email'],
[[ 'email', 'username'], 'unique'],
];
}
提前谢谢!
答案 0 :(得分:1)
你应该同时使用两者
例如:
// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
在你的情况下
[[ 'email', 'username'], 'unique', 'targetAttribute' => ['email', 'username']],
http://www.yiiframework.com/doc-2.0/yii-validators-uniquevalidator.html
答案 1 :(得分:0)
如果要一次更新一个字段。您需要删除必填字段。然后他检查3必须存在。删除这一行:
[['email', 'password', 'username'], 'required'],