本文主要介绍了yii2 modal弹窗之ActiveForm ajax表单验证的相关资料,非常不错具有参考借鉴价值,需要的朋友可以参考下。希望对大家有所帮助。
我们就yii2 ActiveForm如何以Ajax的方式提交表单做一个简单的说明,这也是我们今天主题的重点。
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);<strong style="color:transparent">本文来源gaodai#ma#com搞@@代~&码*网/</strong><strong>搞gaodaima代码</strong>}}}if (Yii::$app->request->isAjax) {return $this->renderAjax('create', ['model' => $model,]);} else {return $this->render('create', ['model' => $model,]);}
相关推荐:
Yii2中join、joinwith多表关联查询的使用方法
Yii2实现QQ互联登录
Yii2实现rbac权限控制
以上就是yii2 modal弹窗之ActiveForm实现ajax表单异步验证的详细内容,更多请关注搞代码gaodaima其它相关文章!