Yii2 ActiveForm Ajax验证基础
此前我们探讨了Yii2中Modal的使用,以及如何在Gridview列表更新操作中调用Modal。本以为相关话题已告一段落,但实际开发中常遇意外情况:Modal弹窗内提交的表单如何进行验证,再次成为难题。
暂且不论Modal,我们先聚焦于Yii2 ActiveForm如何以Ajax方式提交表单,这是本次讨论的核心重点。关于Modal本身的内容相对较少,后续若有补充再行调整。
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表单验证的相关知识,希望能对大家有所帮助。如需了解更多内容,请持续关注本站。