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.
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. :|
$form = $this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>true,
...
public function actionCreate() {
$model=new Model;
$this->performAjaxValidation($model);
...
$outputJs = Yii::app()->request->isAjaxRequest;
$this->renderPartial('_form', array('model'=>new Model), false, $outputJs);
$.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With