简体   繁体   English

使用ajax唯一的Yii2验证默认用户名和电子邮件时,请回避

[英]Sidestep the default username and email when validate it with ajax unique Yii2

How can i sidestep current username and password of the user when updating his information? 更新用户信息时,我该如何回避该用户的当前用户名和密码? For example - when i try to update only the name it shows me that email is already taken and vice versa. 例如-当我尝试仅更新名称时,它向我显示电子邮件已经被使用,反之亦然。 That way i can not update only the or only the email, only both of them. 这样,我就无法仅更新或仅更新电子邮件,仅更新两者。 My 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,
            ]);
        }
    }

My UpdateForm 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'],
        ];
    }

Thank you in advance! 先感谢您!

you should use both for unique 您应该将两者用于唯一

eg: 例如:

// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]

in your case 在你的情况下

[[ 'email', 'username'], 'unique', 'targetAttribute' => ['email', 'username']],

http://www.yiiframework.com/doc-2.0/yii-validators-uniquevalidator.html http://www.yiiframework.com/doc-2.0/yii-validators-uniquevalidator.html

If you want to update the fields one at a time. 如果要一次更新一个字段。 You need to remove the required fields. 您需要删除必填字段。 He then checks that 3 must exist. 然后,他检查3必须存在。 Delete this line: 删除此行:

[['email', 'password', 'username'], 'required'],

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

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