ActiveForm的PHP方面,通常对于大多数项目来说已经足够了,在官方的yii2.0权威指南中有很好的描述. 当涉及到诸如动态添加或删除表单字段或使用异常条件触发单个字段验证之类的高级操作时,它变得更加棘手。
在此,你讲了解 ActiveForm JavaScript API.
此文译自: yii2-cookbook.
我们将使用基础模板中的联系表单来进行尝试,所以先安装它.
$('#contact-form').yiiActiveForm('validateAttribute', 'contactform-name');
$('#contact-form').yiiActiveForm('validate', true);
第二个传递的参数true
强制验证整个表单。
$('#contact-form').on('beforeSubmit', function (e) {
if (!confirm("Everything is correct. Submit?")) {
return false;
}
return true;
});
可用事件包括:
beforeValidate
.afterValidate
.beforeValidateAttribute
.afterValidateAttribute
.beforeSubmit
.ajaxBeforeSend
.ajaxComplete
.afterInit
.要将字段添加到验证列表,请执行以下操作:
$('#contact-form').yiiActiveForm('add', {
id: 'address',
name: 'address',
container: '.field-address',
input: '#address',
error: '.help-block',
validate: function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {message: "Validation Message Here"});
}
});
要删除字段以使其不被验证,请执行以下操作:
$('#contact-form').yiiActiveForm('remove', 'address');
给属性添加错误:
$('#contact-form').yiiActiveForm('updateAttribute', 'contactform-subject', ["I have an error..."]);
移除它:
$('#contact-form').yiiActiveForm('updateAttribute', 'contactform-subject', '');
$('#contact-form').yiiActiveForm('updateMessages', {
'contactform-subject': ['Really?'],
'contactform-email': ['I don\'t like it!']
}, true);
上面代码中的最后一个参数指示是否需要更新摘要。
将事件附加到属性更改,如选择、单选按钮等...您可以使用以下代码
$("#attribute-id").on('change.yii',function(){
//your code here
});
为了与第三方小部件(如Kartik)兼容,检索属性实际值的最佳选项是:
$('#form_id').yiiActiveForm('find', 'attribute').value
如果要基于新条件更改JS中属性的验证,可以使用rule属性whenClient进行,但是如果需要不依赖于规则的验证(仅客户端),可以尝试以下方法:
$('#form_id').on('beforeValidate', function (e) {
$('#form_id').yiiActiveForm('find', 'attribute').validate = function (attribute, value, messages, deferred, $form) {
//Custom Validation
}
return true;
});
要通过AJAX提交表单,需要在beforeSubmit
事件上附加一个处理程序。处理程序将替换默认表单提交,并负责将数据发送到服务器,并在服务器验证失败时显示错误消息。显示验证消息需要控制器端的支持。
将处理程序附加到表单:
$('#contact-form').on('beforeSubmit', function () {
var $yiiform = $(this);
$.ajax({
type: $yiiform.attr('method'),
url: $yiiform.attr('action'),
data: $yiiform.serializeArray(),
}
)
.done(function(data) {
if(data.success) {
// data is saved
} else if (data.validation) {
// server validation failed
$yiiform.yiiActiveForm('updateMessages', data.validation, true); //在适当的位置呈现验证消息
} else {
// 服务器响应不正确
}
})
.fail(function () {
// 请求失败
})
return false; // 阻止默认表单提交
})
控制器支持:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if (Yii::$app->request->isAjax) {
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->asJson(['success' => true]);
}
$result = [];
// The code below comes from ActiveForm::validate(). We do not need to validate the model
// again, as it was already validated by save(). Just collect the messages.
foreach ($model->getErrors() as $attribute => $errors) {
$result[yii\helpers\Html::getInputId($model, $attribute)] = $errors;
}
return $this->asJson(['validation' => $result]);
}
return $this->render('update', [
'model' => $model,
]);
}