dongtangjie0495 2017-03-22 20:05
浏览 46
已采纳

使用ajax唯一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:

 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!

  • 写回答

2条回答 默认 最新

  • du3669 2017-03-22 20:33
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历