How to prevent multiple form feeds in Yii2?

To process the form, I use the following code (for test only):

$(document).on("beforeSubmit", "#test-form", function (event, messages) {
    $(this).find(':submit').attr('disabled', true);
    console.log('Test new form');
    return false;
});

But, despite the fact that I am making the submit button inactive, we can see in the console that the form is submitted at least twice when I quickly click on the button. As a fix, temp wrote the following code:

$(document).on("beforeValidate", "form", function(event, messages, deferreds) {
    $(this).find(':submit').attr('disabled', true);
    console.log('BEFORE VALIDATE TEST');
}).on("afterValidate", "form", function(event, messages, errorAttributes) {
    console.log('AFTER VALIDATE TEST');
    if (errorAttributes.length > 0) {
        $(this).find(':submit').attr('disabled', false);
    }
});
$(document).on("beforeSubmit", "#test-form", function (event, messages) {
    console.log('Test new form');
    return false;
});

But not sure if this is a good solution or not. How to fix this problem?
Thanks in advance!

+4
source share
1 answer

One solution is to disable the button using JavaScript. But this is ineffective all the time due to problems with browsers or due to the fact that the user could disable JavaScript in his browser.

- , ​​ , .

https://github.com/yiisoft/yii2/issues/10498:

Model

public function getHiddenFormTokenField() {
    $token = \Yii::$app->getSecurity()->generateRandomString();
    $token = str_replace('+', '.', base64_encode($token));

    \Yii::$app->session->set(\Yii::$app->params['form_token_param'], $token);;
    return Html::hiddenInput(\Yii::$app->params['form_token_param'], $token);
}

" , 'beforeAction' . . , ."

public function beforeAction($action) {
    $formTokenName = \Yii::$app->params['form_token_param'];

    if ($formTokenValue = \Yii::$app->request->post($formTokenName)) {
        $sessionTokenValue = \Yii::$app->session->get($formTokenName);

        if ($formTokenValue != $sessionTokenValue ) {
            throw new \yii\web\HttpException(400, 'The form token could not be verified.');
        }

        \Yii::$app->session->remove($formTokenName);
    }

    return parent::beforeAction($action);
}
+4

Source: https://habr.com/ru/post/1653624/


All Articles