S
S
skajtersen2017-07-06 13:12:51
Yii
skajtersen, 2017-07-06 13:12:51

How to avoid instant saving of the model during ajax validation?

I want to add Ajax validation to validate the form before updating. In the view, I hung it on the desired field In the controller, in actionUpdate, there is such a place
['enableAjaxValidation' => true]

if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($modelForm->validate()) {
                $model->setAttributes($modelForm->getAttributes());
               
                if ($model->save()) {
                    return $this->redirect([тут путь назад]);
                }

                if ($model->hasErrors()) {
                    return ActiveForm::validate($model);
                } else {
                    return ['success' => 1, 'html' =>
                        $this->renderPartial('view', [тут передаю, что нужно];
                }
            } else {
                return ActiveForm::validate($modelForm);
            }
        }

The problem is that selecting any value in a field that has 'enableAjaxValidation' => true will immediately save the model (even without pressing the save button). How to avoid it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-07-06
@qonand

The most correct solution would be to move the validation to a separate controller action

M
Maxim Timofeev, 2017-07-06
@webinar

Or, as Maxim Fedorov said , move the logic into a separate action or in the controller, through:

if(Yii::$app->request->isAjax){
//тут валидация
}else{
//тут сохранение
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question