在Yii2中,要防止必须单击两次表单提交按钮才能执行操作的情况发生,可以采取以下几种方法:
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
// ...
'options' => ['onsubmit' => 'disableButton()'],
]);
// ...
echo Html::submitButton('Submit', ['class' => 'btn btn-primary']);
ActiveForm::end();
然后,在JavaScript部分定义disableButton()
函数:
function disableButton() {
document.getElementById("submit-button").disabled = true;
}
composer require 2amigos/yii2-avoid-duplicate-submission-widget
然后,在表单视图文件中使用该插件:
use dosamigos\avoidduplicatesubmission\AvoidDuplicateSubmissionActiveForm;
$form = AvoidDuplicateSubmissionActiveForm::begin([
// ...
]);
// ...
echo Html::submitButton('Submit', ['class' => 'btn btn-primary']);
AvoidDuplicateSubmissionActiveForm::end();
'components' => [
// ...
'request' => [
'enableCsrfValidation' => true,
],
],
然后,在表单中使用yii\helpers\Html::csrfInput()
方法生成CSRF令牌:
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
// ...
]);
// ...
echo Html::csrfInput();
echo Html::submitButton('Submit', ['class' => 'btn btn-primary']);
ActiveForm::end();
以上是防止必须单击两次Yii2表单提交按钮才能执行操作的几种方法。根据具体情况选择适合的方法来实现防止重复提交的功能。
领取专属 10元无门槛券
手把手带您无忧上云