简体   繁体   中英

Yii2 Ajax Validation not validating one field unique

Very weird behavior i found out with yii2 ajax validation i found today.

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.

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. It performs the ajax request, and i can see the json response in the dev tools but it doesn't display at all. But, When you move the $user->setScenario('update'); outside the if condition, above the if(Yii::$app->request->isAjax) only then it works perfectly fine. I don't understand this, am i missing something? Why using setScenario when ajax request changes the behavior?

You're overriding the scenarios() function from the Yii Model, thus not validating any attributes.

Check: 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']];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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