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

时间:2017-03-23 07:30:31

标签: php ajax validation yii2

现在,我有一个包含三个输入的更新表单 - 用户名,电子邮件和密码。一切都很好,除了我尝试只更新密码的情况。 例如:用户的用户名和电子邮件必须保持不变,并且只能更改密码。在这里发生了什么:the result of performing this action

在这种情况下,我试图只更新用户的密码。 控制器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',
                                     'targetAttribute' => ['email', 'username'],
                                     'message' => 'The combination of username and password is already taken'],
        ];
    }

赞赏每一条建议!提前谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用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]);
        }
    }