使用ajax调用呈现表单时,客户端验证在Yii2中不起作用

使用ajax调用呈现表单时,客户端验证在Yii2中不起作用

问题描述:

Form rendered using ajax:

<?php $form = ActiveForm::begin(['id' => 'que',
        'enableClientValidation' => true
    ]); ?>
            <?php echo $form->field($model, 'fk_subject')
                    ->dropDownList(ArrayHelper::map($subjects, 'id_subject', 'name'), [
                        'class'     => 'form-control ng-pristine ng-valid ng-touched',
                        'ng-model'  => 'que.fk_subject',
                        'prompt'    => 'Select subject',
                        'ng-change' => 'fillTopic(que);'
                    ]); ?>
            <?php echo $form->field($model, 'fk_topic')
                    ->dropDownList([], [
                        'class'     => 'form-control ng-pristine ng-valid ng-touched',
                        'ng-model'  => 'que.fk_topic',
                        'prompt'    => 'Select topic',
                        'ng-change' => 'openAddTopic(que);',
                        'ng-options' => 'topic.id_subject as topic.name for topic in topics',
                    ]); ?>
            <?php echo $form->field($model, 'type')
                    ->dropDownList($questionTypes, [
                        'class'     => 'form-control ng-pristine ng-valid ng-touched',
                        'prompt'    => 'Select question type',
                        'ng-model'  => 'que.type',
                        'ng-change' => 'addAnswerOptions(que);',
                    ]); ?>
                    <?php echo Html::submitButton('Save',
                        ['class' => 'btn btn-primary',
                            'name' => 'Save']) ?>
<?php ActiveForm::end(); ?>

I loaded the above form using ajax in yii2 and problem is client side validation is not working with it. If I load the form content on window load it works fine.

OK I find the solution, I will have to use renderAjax to get the form html or will have to add beginpage and beginend function if I use renderPartial

<?php $this->beginPage(); ?>
<?php $this->beginBody(); ?>
// Form and content redenered using ajax
<?php $this->endBody(); ?>
<?php $this->endPage(); ?>

so that yii can add client validation script with the rendered content

make sure you use renderAjax() method in your controller to load this form via ajax, this way It's needed scripts will register when it loads.

other than that you need to assign a unique ID to your form to prevent possible conflicts when this form is loaded in other views.