Dear Friends
Let us have a real life situation.
We have a form where user has to enter his name.Then there is a boolean field(radio button) for his/her married status.
If he chooses the married status as true, then one has to enter his or her spouse name.
Otherwise errors will be thrown.
If he or she enters his spouseName without choosing the marital status,
then marital status would be assumed true.
MODEL
<?php
class TestForm extends CFormModel
{
public $name;
public $married;
public $spouseName;
public function rules()
{
return array(
array('name', 'required'),
array('married', 'boolean'),
array('spouseName', 'safe'), //this is very important.
);
}
public function beforeValidate()
{
if ($this->married) {
$this->getValidatorList()->add(CValidator::createValidator('required',$this,'spouseName',array()));
}
if (!$this->spouseName==null) {
$this->married=true;
}
return parent::beforeValidate();
}
}
?>
view
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'test-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>64)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row rememberMe">
<?php echo $form->checkBox($model,'married'); ?>
<?php echo $form->label($model,'married'); ?>
<?php echo $form->error($model,'married'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'spouseName'); ?>
<?php echo $form->textField($model,'spouseName',array('size'=>60,'maxlength'=>64)); ?>
<?php echo $form->error($model,'spouseName'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller
public function actionValidate(){
$model=new TestForm;
if(isset($_POST['TestForm']))
{
$model->attributes=$_POST['TestForm'];
$model->validate();
}
$this->render('validate',array('model'=>$model));
}
NOTE: We has to make the rule safe for dependent attribute.Othewise we can not get the value
during massive assignment.
Regards.