Home  >  Article  >  Backend Development  >  yii2 modal弹窗之ActiveForm ajax表单验证_php实例

yii2 modal弹窗之ActiveForm ajax表单验证_php实例

WBOY
WBOYOriginal
2016-06-16 08:40:55994browse

前面我们讲述了yii2中如何使用modal以及yii2 gridview列表内更新操作如何使用modal的问题,本以为modal要告一段落可以开始新的话题了,但是实际问题往往超乎想像,这不modal弹窗提交的表单说是怎么验证的问题又出来了,又出来了!

首先撇开modal不谈,我们就yii2 ActiveForm如何以Ajax的方式提交表单做一个简单的说明,这也是我们今天主题的重点,modal确实没啥好说了。后面若是有我再把话改回来。

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

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

注意哦,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表单验证的相关知识,希望对大家有所帮助,如果大家想了解更多内容敬请关注脚本之家网站!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn