简体   繁体   中英

Yii2 unique validator error display not set to form field

i am using yii2 RESTapi for my module .my problem the validation is working fne and the error msg also display in console as a json format but it's not set in form field .see the image for more info..please help me anyone ...

This is model

 public function rules()
 {
    return [
        [['username'], 'required'],
        [['username'],'unique'],             

 }

view:

<?php $form = ActiveForm::begin([
'id' => 'cab-form',   
'enableAjaxValidation' => true,

])
; ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<div class="form-group">
    <?= Html::submitButton( 'Create', ['class' => 'btn btn-success','id'=>'submit-btn']) ?>
</div>

<?php ActiveForm::end(); ?>

controller:

    public function actionCreate(){ 
        $model = new Cab;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $post_data = Yii::$app->request->post();
        $model->load($post_data); 
        $model->save();         
        return $model;
  } 

Thanks...

在此处输入图片说明

Unique require AjaxValidation to work. You need verify in your controller if an ajax request exist and return the validation encoded with JSON. See the example below:

            if ($model->load(Yii::$app->request->post()) {
                if (Yii::$app->request->isAjax) {
                    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                    return ActiveForm::validate($model);
                }
            }

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