简体   繁体   English

更新用户信息表Yii2的Ajax唯一验证

[英]Ajax unique validation on update user information form Yii2

Now, i have an update form with three inputs - username, email and password. 现在,我有一个包含三个输入的更新表单-用户名,电子邮件和密码。 Everything is ok except the case when i try to update only the password. 一切正常,除了我尝试仅更新密码的情况。 For example: Username and email of the user have to stay the same and only the password must be changed. 例如:用户名和用户的电子邮件必须保持相同,并且仅密码必须更改。 And here what is happening: 这里发生了什么: 执行此操作的结果

In this case i am trying to update only the password of the user. 在这种情况下,我尝试仅更新用户密码。 Controller actionUpdate: 控制器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 model rules: 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',
                                     'targetAttribute' => ['email', 'username'],
                                     'message' => 'The combination of username and password is already taken'],
        ];
    }

Appreciating every advice! 赞赏每一个建议! Thank you in advance! 先感谢您!

Try using save() instead of update() 尝试使用save()而不是update()

  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->save();

            $this->redirect(['view', 'id' => $user->id]);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM