绵阳动力网站建设

yii2中使用modal弹窗验证ActiveForm ajax表单

时间:2016-07-19

在yii2的使用过程中,ActiveForm默认做了客户端验证,但是表单的提交,却不是无刷新的。也就是常常看到的表单提交后页面会刷新。如果想要开启无刷新的模式,只需要在ActiveForm开始开启enableAjaxValidation即可,像下面这样

<?php $form = ActiveForm::begin([
'id' => 'form-id',
'enableAjaxValidation' => true,
]
); ?>

注意哦,id和enableAjaxValidation一个都不能少。

接着看服务端的实现

if ($model->load(Yii::$app->request->post())) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
if ($errors = \yii\widgets\ActiveForm::validate($model)) {
return $errors;
} else {
if($model->save(false)) {
return $this->redirect(['index']); 
}
}
}
return $this->render('create', [
'model' => $model,
]);

如此一来就简单的实现了yii2异步无刷新提交表单了!

其实下面说与不说已经不重要了,主要是写给一些懒人参考吧。聪明的人看了标题就应该明白了如何解决modal通过ActiveForm提交表单的问题。

为了兼容modal,注意我们说的是兼容而不是实现,我们对程序稍稍做了些改动,仅做参考。

if ($model->load(Yii::$app->request->post())) {
if ($model->save()) { 
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ['success' => true];
}
return $this->redirect(['index']);
} else {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return \yii\widgets\ActiveForm::validate($model);
}
}
}
if (Yii::$app->request->isAjax) {
return $this->renderAjax('create', [
'model' => $model,
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}

以上所述是绵阳动力网站建设公司给大家介绍的yii2 modal弹窗之ActiveForm ajax表单验证的相关知识,希望对大家有所帮助!

Copyright © 绵阳动力网站建设 www.kf51.cn All Rights Reserved 蜀ICP备08100083号

客服微信
客服微信
0816-6339181
客服微信
my_dongli