how to do ActiveForm Ajax validation

Hi,

I’m trying do do Ajax validation in a ActiveForm.

For the Product field there is a rule in my model like [[‘product’], ‘required’]

So going to the next field it should give a error like "product can not be blank"

How should I do this.

Maybe my approach is totally wrong.

In my view I have this.




<?php Modal::begin([

    'id' => 'bookingDialog',

    'header' => '<h4 class="modal-title">Add new booking</h4>',

    'footer' =>

        Html::button('Add', ['class' => 'btn btn-primary btn-modal-save', 'id' => 'saveBooking'])

        . PHP_EOL .

        Html::button('Close', ['class' => 'btn btn-default', 'data-dismiss' => 'modal']),

]);

?>

    <div id='modalContent'></div>

<?php Modal::end() ?>


<?php

$script = <<< JS

$('#saveBooking').on('click', function(event) {

    var form = $('#edit-booking-form');

    $.ajax({

        type: 'POST',

        dataType: 'JSON',

        url: '/calendar/add',

        data: form.serialize(),

        success: function(data) {

            $('#bookingDialog').modal('hide')

        }

    });

});

JS;

$this->registerJs($script);

?>



And in my Controller I have this




    public function actionAdd()

    {

        $model = new Calendar();

        $status = 'error';

        $message = 'unknown';


        if ($model->load(Yii::$app->request->post())) {

          

            $model->refresh();

            $message = \yii\widgets\ActiveForm::validate($model);


            if ($model->save()) {

                $status = 'success';

            } else {

                $status = 'error';

            }


            \Yii::$app->response->format = 'json';

            $items = ['status' => $status, 'message' => $message];

            return $items;

        }


        $view = $this->renderAjax('create', [

                    'model' => $model,

                ]);

            

        $items = [

            'status' => 'success',

            'view' => $view,

        ];

        

        \Yii::$app->response->format = 'json';

        return $items;     

    }



In my create view.




<?php

  use yii\widgets\ActiveForm;

?>


<?php $form = ActiveForm::begin([

    'id' => 'edit-booking-form',

    'action' => ['/calendar/add'],

    'enableClientValidation' => false,

    'enableAjaxValidation'=> true,

    'validateOnSubmit' => true,

    'validateOnChange' => true,

    'validateOnType' => true,


]);


 ?>

    <?= $form->field($model, 'product')->textInput(); ?>

    <?= $form->field($model, 'title')->textInput(); ?>

<?php ActiveForm::end(); ?>



Please help!