i add some check boxes in the form to control showing or hiding textfields
i want to implement this logic rule "when you check check box and textfield appears this textfield is required"
so i use beforeValidate() on my cmodel like the following
public function beforeValidate()
{
if ($this->recycle) {//this is the checkbox
$this->validatorList->add(Yii::createComponent(array(
'class' => 'CRequiredValidator',
'attributes' => array('recycle_options'),//this is the textbox
)));
}
return parent::beforeValidate();
}
in my controller created automatically using gii
public function actionCreate()
{
$model=new MembershipItemCycles;
// Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation($model);
if(isset($_POST['MembershipItemCycles']))
{
$model->attributes=$_POST['MembershipItemCycles'];
if($model->save())
$this->redirect(array('view','id'=>$model->cycle_id));
}
$this->render('create',array(
'model'=>$model,
));
}
i tested that with an empty textfield with checkbox checked but nothing occurs and no errors and fields saved to my database
Just a thought: you can set the textbox validation rule as usual but add scenario option (for example, ‘on’ => ‘recycle’), and then switch model validation scenario if the checkbox is checked.
Check whether the following is helpful. (Not tested the code in my localhost. Kindly bear with me).
public function beforeValidate()
{
if ($this->recycle) {//this is the checkbox
$this->validatorList->add(CValidator::createValidator('required',this,'recycle_options',array()));
}
return parent::beforeValidate();
}
If user selects married status. He has to enter his wife name.
If he puts wife name without selecting married status. His wife name silently discarded.
MODEL:TestForm
<?php
class TestForm extends CFormModel
{
public $name;
public $married;
public $wifeName;
public function rules()
{
return array(
array('name', 'required'),
array('married', 'boolean'),
array('wifeName', 'safe'),
);
}
public function beforeValidate()
{
if ($this->married) {
$this->getValidatorList()->add(CValidator::createValidator('required',$this,'wifeName',array()));
}
if (!$this->married) {
$this->getValidatorList()->add(CValidator::createValidator('default',$this,'wifeName',array('value'=>'','setOnEmpty'=>FALSE)));
}
return parent::beforeValidate();
}
}
?>