我无法在Yii2中找到以下方法:
这是我到目前为止所得到的:
在我看来:
<?php
$form = ActiveForm::begin([
'id' => 'subscribe-form',
'action' => ['site/subscribe'],
'validationUrl' => ['site/validate-subscribe'],
'validateOnSubmit' => true,
'enableAjaxValidation' => true,
]) ?>
<?= $form->field($model, 'name')->input('text', ['class' => 'w-input']) ?>
<?= $form->field($model, 'email')->input('text', ['class' => 'w-input']) ?>
<div class="form-group">
<?= Html::submitButton('SUSCRIBIRSE', ['class' => 'w-inline-block btn', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end() ?>
在我的控制器中:
public function actionValidateSubscribe(){
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Subscription(Yii::$app->getRequest()->getBodyParams()['Subscription']);
if (!$model->validate()) {
return ActiveForm::validate($model);
}
}
}
public function actionSubscribe()
{
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Subscription(Yii::$app->getRequest()->getBodyParams()['Subscription']);
if(!$model->validate()){
throw new NotAcceptableHttpException('Tiene errores de validación en la forma');
}
if($model->save()){
Yii::$app->mailer->compose('subscription', ['model'=>$model])
->setTo([$model->name => $model->email])
->setFrom(['Test' => 'info@test.com'])
->setSubject('Por favor confirme su suscripción')
->send();
}
$response = [
'data'=>$model->getAttributes(),
'success'=>'true'
];
return $response;
}
}
在我的JS中:
$(document).ready(function () {
$('body').on('beforeSubmit', 'form#subscribe-form', function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length) {
return false;
}
// submit form
$.ajax({
url : form.attr('action'),
type : 'post',
data : form.serialize(),
success: function (response) {
// do something with response
},
error : function () {
}
});
return false;
});
});
问题是当我设置&#34; enableAjaxValidation&#34;时,yii.ActiveForm.js没有触发afterVAlidate或beforeSubmit事件。在我的ActiveForm中为true。
答案 0 :(得分:3)
尝试$('form#subscribe-form').on('beforeSubmit', function () {...});