Okay I already found a way to solve it. Thanks to this post
The only problem now is when an I leave the chosen textfield as blank and it shows the error, the textfield that was shown (the one which is dependent on the value of dropdownlist) disappears or goes back to state display:hidden. This happens right after the ‘textfield cannot be blank’ error message. The initial chosen value of dropdownList is still there and is still on focus but the textfield disappears.
View:
<div class="row">
<?php echo $form->labelEx($model,'org_type'); ?>
<?php echo $form->dropDownList($model,'org_type', $model::getOrgType(), array('prompt'=>'', 'id'=>'orgType')); ?>
<?php echo $form->error($model,'org_type'); ?>
</div>
<div class="row" style="display:none" id="sec">
<?php echo $form->labelEx($model,'sec_ref'); ?>
<?php echo $form->textField($model,'sec_ref', array('id'=>'secField')); ?>
<?php echo $form->error($model,'sec_ref'); ?>
</div>
<div class="row" style="display:none" id="dti">
<?php echo $form->labelEx($model,'dti_ref'); ?>
<?php echo $form->textField($model,'dti_ref', array('id'=>'dtiField')); ?>
<?php echo $form->error($model,'dti_ref'); ?>
</div>
<div class="row" style="display:none" id="cda">
<?php echo $form->labelEx($model,'cda_ref'); ?>
<?php echo $form->textField($model,'cda_ref', array('id'=>'cdaField')); ?>
<?php echo $form->error($model,'cda_ref'); ?>
</div>
Model:
public function addCustomError($attribute, $error) {
$this->customErrors[] = array($attribute, $error);
}
/**
*/
protected function beforeValidate() {
$r = parent::beforeValidate();
if ($this->org_type == 'Single') {//this is the checkbox
$this->validatorList->add(CValidator::createValidator('required',$this,'dti_ref',array()));
}
if ($this->org_type == 'Partnership') {//this is the checkbox
$this->validatorList->add(CValidator::createValidator('required',$this,'sec_ref',array()));
}
if ($this->org_type == 'Corporation') {//this is the checkbox
$this->validatorList->add(CValidator::createValidator('required',$this,'sec_ref',array()));
}
if ($this->org_type == 'Cooperative') {//this is the checkbox
$this->validatorList->add(CValidator::createValidator('required',$this,'cda_ref',array()));
}
foreach ($this->customErrors as $param) {
$this->addError($param[0], $param[1]);
}
return $r;
}
javascript on the view:
<?php
/* @var $this BusinessController */
/* @var $model Business */
/* @var $form CActiveForm */
Yii::app()->clientScript->registerScript(‘orgType’, "
$(’#orgType’).change(function(){
if($('#orgType').val() == 'Single')
{
$('#dti').show();
$('#dtiField').addClass('required');
$('#cda').hide();
$('#sec').hide();
}
if(($('#orgType').val() == 'Partnership') || ($('#orgType').val() == 'Corporation'))
{
$('#sec').show();
$('#secField').addClass('required');
$('#dti').hide();
$('#cda').hide();
}
if($('#orgType').val() == 'Cooperative')
{
$('#cda').show();
$('#cdaField').addClass('required');
$('#dti').hide();
$('#sec').hide();
}
return false;
});
");
?>