Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii client validation not working on ajax loaded form

When I open the page with normal request (non ajax), everything works fine. But when I load that form with ajax, the client validation in that form does not work.

The form generator is classic gii-generated stuff:

$form = $this->beginWidget('CActiveForm', array(
    'id'=>'cat-form',
    'enableAjaxValidation'=>true,
    'action' => ...,
    'clientOptions'=>array('validateOnSubmit'=>true),
    )
);
// - form inputs go here -
$this->endWidget();

Ajax loading is done like this:

$.get(page, function(formHtml) {
    $('#content').html(formHtml);
});

I had to call renderPartial with processOutput = true, so that it outputs the javascript. The widget-generated javascript looks like this:

$('#cat-form').yiiactiveform({'validateOnSubmit':true,'attributes':[...]});

I've traced the problem to the fact that when $('#cat-form') selection is done, the returned jQuery object is empty, ie there is no form yet.

How do I properly add client validation for ajax loaded content in Yii?


I am stupid, and have just wasted 4 hours because of this:

var slider = $('.slider');
var slide = $('<div class="slide">').html(resp); // facepalm

// few lines later..
slider.append(slide);

So the script got executed when the form was only in temporary element, that was not yet appended to the page. Hence, the $('#form') did not find anything.

like image 926
psycho brm Avatar asked Oct 15 '13 18:10

psycho brm


1 Answers

Since I have just wasted few hours looking for solution (I feel like this happens a lot in programming), I may as well now explain the whole thing so that others don't have to end up like me. :|

1. enableAjaxValidation in _form.php

$form = $this->beginWidget('CActiveForm', array(
    'enableAjaxValidation'=>true,
    ...

2. performAjaxValidation in ModelController.php

public function actionCreate() {
    $model=new Model;
    $this->performAjaxValidation($model);
    ...

3. Let the renderPartial output the javascript

$outputJs = Yii::app()->request->isAjaxRequest;
$this->renderPartial('_form', array('model'=>new Model), false, $outputJs);

4. Append the ajax loaded content

$.get(url, function(resp) {
    $('#content').html(resp);

    // !! DO NOT append the html to element that is not yet part of the document
    // var slide = $('<div>').html(resp);   // WRONG
    // $('.slides').append(slide);          // WRONG

Good luck.

like image 110
psycho brm Avatar answered Oct 08 '22 04:10

psycho brm