简体   繁体   English

Yii2 Ajax验证未验证唯一字段

[英]Yii2 Ajax Validation not validating one field unique

Very weird behavior i found out with yii2 ajax validation i found today. 我今天发现的yii2 ajax验证发现了非常奇怪的行为。

Basically i was trying to perform ajax validation on 1 field of the form to check that the input is unique and not found anywhere in that field of that table. 基本上,我试图在表单的1个字段上执行Ajax验证,以检查输入是否唯一并且在该表的该字段中的任何地方都找不到。

If you ask me the following code should work correctly: 如果您问我以下代码应正常工作:

In model: 在模型中:

public function scenarios(){
   return ['update' => ['username']];
}
public function rules(){
   return [['username'], 'unique'];
}

In Controller: 在控制器中:

public function actionUpdate(){
    $user = User::findmodel.. bla bla
    some more bla bla..

    if(Yii::$app->request->isAjax){

        $user->setScenario('update');

        $user_post_ajax = Yii::$app->request->post('User');
        $user->username = $user_post_ajax['username'];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ActiveForm::validate($user);
    }

    some more bla bla bla..
}

In View: 在视图中:

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($user, 'username', ['enableAjaxValidation' => true])->textInput() ?>
    <?= Html::submitButton('Save', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    <?php ActiveForm::end(); ?>

This should work, but it doesn't, it doesn't display the validation errors, in this case something like: 'Username is already taken' , it doesn't display neither valid nor invalid. 这应该可以,但是不能,它不会显示验证错误,在这种情况下,类似于: 'Username is already taken' ,它既不显示有效也不无效。 It performs the ajax request, and i can see the json response in the dev tools but it doesn't display at all. 它执行ajax请求,我可以在开发工具中看到json响应,但根本不显示。 But, When you move the $user->setScenario('update'); 但是,当您移动$user->setScenario('update'); outside the if condition, above the if(Yii::$app->request->isAjax) only then it works perfectly fine. 在if条件之外,仅在if(Yii::$app->request->isAjax)之上的情况下,它才能很好地工作。 I don't understand this, am i missing something? 我不明白,我想念什么吗? Why using setScenario when ajax request changes the behavior? 为什么在ajax请求更改行为时使用setScenario?

You're overriding the scenarios() function from the Yii Model, thus not validating any attributes. 您将覆盖Yii模型中的visions()函数,从而不验证任何属性。

Check: https://github.com/yiisoft/yii2/blob/master/framework/base/Model.php#L184 检查: https : //github.com/yiisoft/yii2/blob/master/framework/base/Model.php#L184

What you should do, is: 您应该做的是:

public function rules(){
  return [['username'], 'unique', 'on'=>['update']];
}

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

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