A
A
Abr_ya2019-09-03 13:50:46
Yii
Abr_ya, 2019-09-03 13:50:46

Yii2 how to understand in the controller that the Save button is pressed in the form?

I raise the modal, render in it the part of the form responsible for the update.
I can’t figure out the appropriate behavior in the modal: when to validate, when to save, when to close the modal?
Ajax turned on, validation turned on and off, now it’s not about that, it seems to me.
Question: how can I check in the controller that the Save button was pressed in the form?
I think it would make things easier, something like this:

if (нажали save) {
    if (валидация успешна) {
        пишем данные, закрываем модалку
    } else {
        выводим результат валидации (рендерим аякс? или встроенная валидация?)
    }
} else {
    тут просто валидация, например
}

Or am I digging in the wrong place?
UPD:
Thank you all for your help! Apparently, it really didn’t lead me there. My controller is written in such a way that the form began to behave exactly as I would like, when I removed this parameter from its begin:
'enableAjaxValidation' => true,
As it turned out, this does not interfere with the built-in on-the-fly validation from the framework at all!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim, 2019-09-03
@Abr_ya

1. The Save button has nothing to do with it.
2. The model has 2 methods $model->save() and $model->validate()
$model->save() - saves and validates
$model->validate() - only validates data.
Yours should be a little different:

if ($model->validate()) {
        ///здесь ваш код
        $model->save()
        пишем данные, закрываем модалку
    } else {
        выводим результат валидации (рендерим аякс? или встроенная валидация?)
    }
}

Loading data from a form
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
///code
   $model->save()
}

Validation is up to you. I think simple validation rules are validated by ajax. And complex ones after pressing the button and requesting the server. For example, we validate the length of the text on the client. And complex logic after the request
Why do you need to check if the button is pressed? This is a JS question. And in the controller, you look at the submitted data from the form. If they are, then you process them. If there are none, then you show the form.

N
Nikita Krasnikov, 2019-09-03
@YekitKsv

Like this

if ($model->load(Yii::$app->request->post()) && $model->validate()) {
   // you code
}

S
serginhold, 2019-09-03
@serginhold

post request data is saved, so usually in the controller they write:
if ($request->isPost()) {}
well, or check the value transfer:
if ($request->post($buttonname)) {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question