Yii2:ajax 对 ajax 提交的表单进行表单验证
Yii2: ajax form validation on an ajax submitted form
我想知道是否有任何 Yii2 专家可以帮助我了解如何最好地使用 ajax 表单与 Yii ajax 验证相结合。我想我可以解释这个问题,而无需带您浏览我的所有代码。
我正在制作一个促销代码输入表单,用户可以在该表单中输入他们的促销代码,该表单通过 ajax 提交。然后我们执行促销代码详细信息的数据库查找,验证代码,如果代码验证,我们要显示隐藏在页面上的注册表单。
我有一个表单字段 "code" 的自定义验证函数,它是名为 "register" 的模型场景中的活动字段。
class UserCode extends ActiveRecord
{
...
public function scenarios()
{
return [
'register' => ['code'],
];
}
public function rules()
{
return [
[['code'], 'required'],
[['code'], 'validateUserCode', 'on' => ['register']],
];
}
public function validateUserCode($attribute, $params)
{
// perform all my custom logic to determine if the code is valid
if ($code_invalid) {
$this->addError($attribute, 'Sorry, this code is invalid.');
}
}
...
}
然后在控制器中,正如 Yii2 指南所建议的那样,我使用以下代码捕获此 ajax 验证:
public function actionValidate() {
$model = new UserCode(['scenario' => 'register']);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
// no logic can be run after the above code b/c the form is submit with ajax
// and therefore always trapped in the Yii::$app->request->isAjax conditional
}
以上代码一切正常,如果我从表单上的 $form->field($model, 'code')
字段中移除焦点,Yii 的 ajax 验证将启动并根据我的自定义验证逻辑显示我的自定义错误消息.
当我去提交表格时,我的挑战出现了。表单提交也是通过 ajax 处理的,因此控制器操作总是 returns ActiveForm::validate($model);
的结果,因为 if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
将同时应用于 ajax ] 表单验证并在表单上提交。
使用上述方法,我不得不 return 仅 ajax 验证的结果,而不是我可能需要的任何 json 额外客户端验证的数据,例如通过 ajax 表单提交有效使用代码后显示注册表。
我意识到我可以在 ActiveForm 上设置 'enableAjaxValidation' => false
,然后在 if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
条件中 return 我自己的 json 数据。如果这样做,我就可以出示注册表,因为我有自己的 json 数据可以使用。
有没有办法对使用 ajax 提交的表单进行 ajax 验证?您如何将 ajax 验证与 ajax 表单提交分开,以不同的方式处理这两个事件?
非常感谢任何建议或替代方法!
您应该将 validationUrl
设置为与您要向其提交表单的 URL 不同的 URL。通过这种方式,您可以拥有验证功能和 return return ActiveForm::validate($model);
以及执行其他操作的正常提交表单。
您可以阅读更多关于 validationUrl
here:
我找到了解决方案:
表格:
<?php
$form = ActiveForm::begin(['id' => 'form-add-contact', 'enableAjaxValidation' => true, 'validationUrl' => Yii::$app->urlManager->createUrl('contacts/contacts/contact-validate')]);
?>
通过 Ajax 提交:
<?php
$script = <<< JS
$(document).ready(function () {
$("#form-add-contact").on('beforeSubmit', function (event) {
event.preventDefault();
var form_data = new FormData($('#form-add-contact')[0]);
$.ajax({
url: $("#form-add-contact").attr('action'),
dataType: 'JSON',
cache: false,
contentType: false,
processData: false,
data: form_data, //$(this).serialize(),
type: 'post',
beforeSend: function() {
},
success: function(response){
toastr.success("",response.message);
},
complete: function() {
},
error: function (data) {
toastr.warning("","There may a error on uploading. Try again later");
}
});
return false;
});
});
JS;
$this->registerJs($script);
?>
控制器:
/*
* CREATE CONTACT FORM AJAX VALIDATION ACTION
*/
public function actionContactValidate() {
$model = new ContactsManagement();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
$model->company_id = Yii::$app->user->identity->company_id;
$model->created_at = time();
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
/**
* Quick Add Contact Action
* @param type $id
* @return type
*/
public function actionAddContact() {
$model = new ContactsManagement();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($model->validate()) {
$flag = $model->save(false);
if ($flag == true) {
$transaction->commit();
return Json::encode(array( 'status' => 'success', 'type' => 'success', 'message' => 'Contact created successfully.'));
} else {
$transaction->rollBack();
}
} else {
return Json::encode(array('status' => 'warning', 'type' => 'warning', 'message' => 'Contact can not created.'));
}
} catch (Exception $ex) {
$transaction->rollBack();
}
}
return $this->renderAjax('_add_form', [
'model' => $model,
]);
}
我想知道是否有任何 Yii2 专家可以帮助我了解如何最好地使用 ajax 表单与 Yii ajax 验证相结合。我想我可以解释这个问题,而无需带您浏览我的所有代码。
我正在制作一个促销代码输入表单,用户可以在该表单中输入他们的促销代码,该表单通过 ajax 提交。然后我们执行促销代码详细信息的数据库查找,验证代码,如果代码验证,我们要显示隐藏在页面上的注册表单。
我有一个表单字段 "code" 的自定义验证函数,它是名为 "register" 的模型场景中的活动字段。
class UserCode extends ActiveRecord
{
...
public function scenarios()
{
return [
'register' => ['code'],
];
}
public function rules()
{
return [
[['code'], 'required'],
[['code'], 'validateUserCode', 'on' => ['register']],
];
}
public function validateUserCode($attribute, $params)
{
// perform all my custom logic to determine if the code is valid
if ($code_invalid) {
$this->addError($attribute, 'Sorry, this code is invalid.');
}
}
...
}
然后在控制器中,正如 Yii2 指南所建议的那样,我使用以下代码捕获此 ajax 验证:
public function actionValidate() {
$model = new UserCode(['scenario' => 'register']);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
// no logic can be run after the above code b/c the form is submit with ajax
// and therefore always trapped in the Yii::$app->request->isAjax conditional
}
以上代码一切正常,如果我从表单上的 $form->field($model, 'code')
字段中移除焦点,Yii 的 ajax 验证将启动并根据我的自定义验证逻辑显示我的自定义错误消息.
当我去提交表格时,我的挑战出现了。表单提交也是通过 ajax 处理的,因此控制器操作总是 returns ActiveForm::validate($model);
的结果,因为 if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
将同时应用于 ajax ] 表单验证并在表单上提交。
使用上述方法,我不得不 return 仅 ajax 验证的结果,而不是我可能需要的任何 json 额外客户端验证的数据,例如通过 ajax 表单提交有效使用代码后显示注册表。
我意识到我可以在 ActiveForm 上设置 'enableAjaxValidation' => false
,然后在 if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
条件中 return 我自己的 json 数据。如果这样做,我就可以出示注册表,因为我有自己的 json 数据可以使用。
有没有办法对使用 ajax 提交的表单进行 ajax 验证?您如何将 ajax 验证与 ajax 表单提交分开,以不同的方式处理这两个事件?
非常感谢任何建议或替代方法!
您应该将 validationUrl
设置为与您要向其提交表单的 URL 不同的 URL。通过这种方式,您可以拥有验证功能和 return return ActiveForm::validate($model);
以及执行其他操作的正常提交表单。
您可以阅读更多关于 validationUrl
here:
我找到了解决方案:
表格:
<?php
$form = ActiveForm::begin(['id' => 'form-add-contact', 'enableAjaxValidation' => true, 'validationUrl' => Yii::$app->urlManager->createUrl('contacts/contacts/contact-validate')]);
?>
通过 Ajax 提交:
<?php
$script = <<< JS
$(document).ready(function () {
$("#form-add-contact").on('beforeSubmit', function (event) {
event.preventDefault();
var form_data = new FormData($('#form-add-contact')[0]);
$.ajax({
url: $("#form-add-contact").attr('action'),
dataType: 'JSON',
cache: false,
contentType: false,
processData: false,
data: form_data, //$(this).serialize(),
type: 'post',
beforeSend: function() {
},
success: function(response){
toastr.success("",response.message);
},
complete: function() {
},
error: function (data) {
toastr.warning("","There may a error on uploading. Try again later");
}
});
return false;
});
});
JS;
$this->registerJs($script);
?>
控制器:
/*
* CREATE CONTACT FORM AJAX VALIDATION ACTION
*/
public function actionContactValidate() {
$model = new ContactsManagement();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
$model->company_id = Yii::$app->user->identity->company_id;
$model->created_at = time();
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
/**
* Quick Add Contact Action
* @param type $id
* @return type
*/
public function actionAddContact() {
$model = new ContactsManagement();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($model->validate()) {
$flag = $model->save(false);
if ($flag == true) {
$transaction->commit();
return Json::encode(array( 'status' => 'success', 'type' => 'success', 'message' => 'Contact created successfully.'));
} else {
$transaction->rollBack();
}
} else {
return Json::encode(array('status' => 'warning', 'type' => 'warning', 'message' => 'Contact can not created.'));
}
} catch (Exception $ex) {
$transaction->rollBack();
}
}
return $this->renderAjax('_add_form', [
'model' => $model,
]);
}