简体   繁体   中英

Validate unique field using Ajax, Yii2 ActiveForm

I am new to Yii, and cannot figure out how ajax validation works with ActiveForm . In my model I have unique field:

public function rules()
    {
        return [
             //...
            [['end_date'], 'unique'], //ajax is not working 

            [   'end_date', //ajax is working
                'compare',
                'compareAttribute'=>'start_date',
                'operator'=>'>=',  
                'skipOnEmpty'=>true,
                'message'=>'{attribute} must be greater or equal to "{compareValue}".'
            ],
        ];
    }

The compare rule is validated with ajax and works fine, but unique is not. I tried to enable ajax validation on form:

  <?php $form = ActiveForm::begin( ['id' => 'routingForm', 'enableClientValidation' => true, 'enableAjaxValidation' => true]); ?>

But don't know what to do next.

Controller:

public function actionCreate()
{
    $model = new Routing();
    $cities = [];     
    if ($model->load(Yii::$app->request->post()) && $model->save()) {            
        return $this->redirect(['index']);
    } else {
        return $this->renderAjax('create', [
            'model' => $model,
            'cities' => $cities
        ]);
    }
}

I know I could make ajax call to controller on end_date change event and form submit , but not sure how make all appropriate css to show the errors.

You need to use Yii::$app->request->isAjax in controller.

public function actionCreate()
{
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ActiveForm::validate($model);
      }
   if ($model->load(Yii::$app->request->post()) && $model->save()) {
       return $this->redirect(['index']);
    } else {
        return $this->renderAjax('create', [
          'model' => $model,
          'cities' => $cities
        ]);
}
}

Try this code in your controller...

public function actionCreate()
{
    $model = new Routing();
    $cities = []; 

    if(Yii::$app->request->isAjax){
        $model->load(Yii::$app->request->post());
        return Json::encode(\yii\widgets\ActiveForm::validate($model));
    }

    if ($model->load(Yii::$app->request->post()) && $model->save())  {            
        return $this->redirect(['index']);
   } else {
    return $this->renderAjax('create', [
        'model' => $model,
        'cities' => $cities
    ]);
}
}

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