In Yii 1.x there is CHtml::ajaxSubmitButton that is very useful. If I’m not wrong, I see there is none in Yii2. So, is there any other work around for this?
In Yii 1.x there is CHtml::ajaxSubmitButton that is very useful. If I’m not wrong, I see there is none in Yii2. So, is there any other work around for this?
No. Workaround is to write a line of JS yourself.
It’s really not a problem, maybe I will rephrase… The problem actually is that I can’t validate the form using validateOnSubmit in this case. I want to check that everything is OK and only then submit the form via ajax. Can I fire validation before sending the form in ajax?
For instance, is it possible to make the validation before submitting in this example:
<?php
$this->registerJs("
$('.main-form-btn').click(function(){
$.ajax({
type: 'POST',
...
data: $('.comment-form form').serializeArray(),
success: function (data) {
....
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
...
}
});
return false;
});
",
yii\base\View::POS_END, 'comment-form');
?>
<div class="comment-form">
<?php $form = ActiveForm::begin(['enableAjaxValidation'=>true,
'validateOnSubmit'=>true]);
?>
<?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>
<div class="form-group">
<?= Html::submitButton('Send', ['class' => 'btn main-form-btn']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Hey check this out. This works well for me. No need of extra steps.
<?php $form = ActiveForm::begin([
'action' => ['create'],
'enableAjaxValidation' = false,
'enableClientValidation' = true,
'beforeSubmit' => "function(form) {
if($(form).find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(data) {
// do something ...
}
});
return false;
}",
]); ?>
This solution does not work:
Exception: Unknown Property
Setting unknown property: yii\bootstrap\ActiveForm::beforeSubmit
The events have been removed from the form - as mentioned you need to write that code in a js file outside of the form definition.
Examples here.
http://www.ramirezcobos.com/2014/09/12/how-to-implement-form-events-on-yii2/