Skip to content

Instantly share code, notes, and snippets.

@voshkin
Created January 6, 2017 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voshkin/c422da2d96e594c6f5ec853430b96b55 to your computer and use it in GitHub Desktop.
Save voshkin/c422da2d96e594c6f5ec853430b96b55 to your computer and use it in GitHub Desktop.
I have the next trouble. yiiActiveForm('updateMessages', ....) doesn't work, but ajax query is completed and success.
public function actionAjaxValidation()
{
\Yii::$app->response->format = Response::FORMAT_JSON;
$result = [];
$model = new SomeModelForm();
$post = \Yii::$app->request->post();
$model->load($post);
$result['errors'] = ActiveForm::validate($model);
return $result;
}
<script src="/assets/1ac78ba4/jquery.js"></script>
<script src="/js/someModelForm.js"></script>
<script src="/assets/bfc0238/yii.js"></script>
<script src="/assets/bfc0238/yii.activeForm.js"></script>
<script src="/assets/70a7529/js/bootstrap.js"></script>
<script type="text/javascript">jQuery(document).ready(function () {
jQuery('#someModelForm').yiiActiveForm([], []);
});</script>
$(function () {
var $someForm = $(this).find('form'),
$submitBtn = $someForm.find('[type=submit]'),
$formData = new FormData($someForm[0]);
$someForm
.on('beforeValidate', function () {
$.ajax({
url: $someForm.prop('action'),
data: $formData,
method: "POST",
processData: false,
contentType: false,
cache: false,
beforeSend: function () {
$submitBtn.button('loading');
},
success: function (response) {
$someForm.yiiActiveForm('updateMessages', response.errors);
},
complete: function () {
$submitBtn.button('reset');
}
});
})
.on('beforeSubmit', function (event) {
return false;
});
});
<?php
/* @var $this yii\web\View
* @var $model \app\models\SomeModelForm
*/
use yii\widgets\ActiveForm;
$this->registerJsFile('js/someModelForm.js', ['depends' => 'yii\web\JqueryAsset']);
$this->title = 'Some Form';
?>
<div class="site-index">
<?php $form = ActiveForm::begin([
'id' => 'someModelForm',
'enableClientValidation' => false,
'action' => ['site/ajax-validation'],
'options' => ['enctype' => 'multipart/form-data']
]) ?>
<?= $form->field($model, 'image')->fileInput([
'clean' => true,
])->label(false) ?>
<?= \yii\bootstrap\Html::submitButton('Отправить', [
'class' => 'btn btn-success',
]) ?>
<?php ActiveForm::end() ?>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment