[solved] dynamic activeform and client validation

I am rendering an ActiveForm dynamically via ajax, however because the form isn’t there on page load, the necessary JS files yiiActiveForm.js, yii.validation.js) and the associated validation triggers aren’t there when the form is echoed out.

Here is some sample code:

JS:


$('.btn-edit').on('click', function() {

    var id = $(this).attr('data-id');

    var url = base_url + '/account/editreview/' + id;


    $.ajax({

        type: 'post',

        url: url,

        dataType: 'json',

        success: function(result) {

            $('.popup').html(result.html);

        }

    });

});

Controller:


public function actionEditReview($id)

{

    $return_array = [

        'html' => null,

    ];


    $review = $this->findReview($id);


    $return_array['html'] = $this->renderPartial('review-popup', [

        'review' => $review,

    ]);


    echo json_encode($return_array);

}

View (review-popup.php):


<?php

use yii\widgets\ActiveForm;

?>


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

    'id' => 'review-form',

    'enableAjaxValidation' => false,

    'enableClientValidation' => true,

]); ?>


<?php echo $form->field($review, 'title')->textInput(); ?>


<button type="submit" class="btn-edit" data-id="<?php echo $review->id; ?>">Submit</button>


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

I have read the notes on this page https://yii2-cookbook.readthedocs.io/forms-activeform-js/ but this talks about adding validation to single attributes, and not to an entire form.

Does anyone know how to do this?

I found the solution: use renderAjax() instead of renderPartial() when echoing out the view.

http://www.yiiframework.com/doc-2.0/yii-web-view.html#renderAjax()-detail