一个普通表单,在点击submit按钮的时候采用连击的方式,在数据库内会生成多条记录。 想问下大家,是怎么解决这个问题的?重复的数据是通过create_at和updated_at时间戳判断出来的,同一个时间戳的数据会有很多条。
代码都是gii生成的,没有做过特殊处理,csrf已开启。
表单代码如下:
<div class="campus-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton(
$model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'),
['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'])
?>
</div>
<?php ActiveForm::end(); ?>
</div>
php代码如下:
public function actionCreate()
{
$model = new Campus();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
解决方法:
1、yii2-lock-form (https://github.com/lichunqiang/yii2-lock-form)
composer require light\yii2-lock-form=~1.0.0
如果项目中已经使用了 yii2-bootstrap
, 那么只需要在的你的 AppAsset
「whatever, 只要你全局依赖的就成」
轻轻的敲入:
'depends' => [
//other depends
'light\widgets\LockBsFormAsset'
]
如果你没使用 yii2-bootstrap
也能满足您:你只需要将 light\widgets\LockBsFormAsset
替换成 light\widgets\LockFormAsset
.
视图
<div class="campus-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton(
$model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'),
['data-loading-text' => '正在提交数据, 不让你点,哼','class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'])
?>
</div>
<?php ActiveForm::end(); ?>
</div>
2、在全局 js 中添加下面 js
// 防止重复提交
$('form').on('beforeValidate', function (e) {
$(':submit').attr('disabled', true).addClass('disabled');
});
$('form').on('afterValidate', function (e) {
if (cheched = $(this).data('yiiActiveForm').validated == false) {
$(':submit').removeAttr('disabled').removeClass('disabled');
}
});
$('form').on('beforeSubmit', function (e) {
$(':submit').attr('disabled', true).addClass('disabled');
});
3、php代码
在不影响原生代码时,处理方案,在当前控制器前面,增加beforeaction:
public function beforeaction($action) {
$repeatCheckKey = Yii::$app->admin->identity->id.Yii::$app->controller->id.$action->id;
/*判断这个cache是否已设置*/
if (Yii::$app->cache->get($repeatCheckKey) !== false) {
return $this->redirect(["tip/index", "msg" => "请不要过快提交。"]);
}
return true;
}
public function actionCreate(){
$model = new Campus();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$rs = $model->save();
if ($rs) {
$repeatCheckKey = Yii::$app->admin->identity->id.Yii::$app->controller->id.$this->action->id;
/*保存成功之后,设置cache过期时间。现在设置是 60秒后过期。*/
Yii::$app->cache->set($repeatCheckKey, time(), 60);
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}