I want to use client validation on an activeform but in some cases it is not working. I see no error messages in the consoles, but I noticed that jquery.yiiactiveform.js is not being included.
Undoubtedly the problem is related to the somewhat convoluted way the page is being rendered. The form is not shown initially - the user first has to make a choice from a drop-down list. That triggers an ajax request, and the response is a renderPartial of a view which contains the activeForm. I used this approach because the structure of the form will be different according to options they select, and this was the most straightforward way to code it under the time pressure I faced. My current plan is to forget about ajax and just make separate views, but that will take some effort.
Minimal code example. The initial view, with a drop-down list:
<?php
$list = array(0 => 'a', 1 => 'b');
echo CHtml::dropDownList('group_id', '', $list, array('ajax' => array(
'type' => 'POST',
'url' => $this->createUrl('group/formAjax2'),
'dataType' => 'json',
'success' => "js:function(data){
document.getElementById('formContent').innerHTML=data.form;
}"
)));
?>
<div id="formContent">
</div>
The idea is that the user makes a choice from the drop-down, and the form gets inserted into the formContent div. Here is the controller action (formAjax2) that services the Ajax request:
public function actionFormAjax2() {
$model= new Group();
$result['form'] = $this->renderPartial('_form2', array('model' => $model), true);
echo CJSON::encode($result);
}
And here is ‘_form2’ which is inserted into the view’s formContent div:
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'group-form',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
'action' => 'myAction',
));
?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model, 'name'); ?>
<?php echo $form->textField($model, 'name', array('size' => 60, 'maxlength' => 128)); ?>
<?php echo $form->error($model, 'name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
When I run this code, it works correctly, in that changing the drop-down causes the form to be loaded, but client validation is not happening in the form, and jquery.yiiactiveform.js is not loaded.
Now, if I forget about using ajax and just render the form directly, like this:
public function actionCreateLocal4($option_id=NULL) {
$model= new Group();
$this->render('_form2', array('model'=>$model));
}
then client validation is working fine. So obviously by passing the form through ajax I am breaking something. Any advice?