Yii Conditional Validation
I have a question about Yii validation. I have a dropdown whose options are Y and N. If the user select Y the user must explain why he chose Y hence a textArea box will become required.
My code for the rule looks at follows.
array('explain', 'check', 'trigger'=>'med_effects'),
Check is my function used for validation
public function check($attribute, $params)
{
if($this->$params['trigger'] == 0 && $this->$attribute == '') {
$this->addError($attribute, 'Explain the effects of the medicine');
}
}
开发者_如何学Python
The value for $this->$params['trigger']
does not change. I'm assuming because the saved value was 0(Y) and does not change even if the user choose N. How am I supposed to determine which option the user chose when he sumbits the form?
Thanks.
Create a property inside your model:
public $isDropDownChecked;
In your view, create a dropdown wired to new property created.
And return a array of rules inside the method rules() like this:
public function rules()
{
$rules[] = array();
if ($this->isDropDownChecked == 'Y')
$rules[] = array('explain', 'check', 'trigger'=>'med_effects');
return $rules;
}
This may also help someone on Yii1, say you have three fields with a lookup of [Yes|NO], and you want atleast one field to be selected as Yes
Here is the solution on your model add
public $arv_refill;
public $prep_refilled;
public $prep_initiate;
on your rules add
public function rules()
{
return array(
array('arv_refill,prep_refilled,prep_initiate','arvPrepInitiateValidation'),
);
}
arvPrepInitiateValidation being a function
public function arvPrepInitiateValidation($attribute_name,$params)
{
if($this->arv_refill != 1 && $this->prep_refilled != 1 && $this->prep_initiate != 1){
$msg = "arv_refill, prep_refilled or prep_initiate field must have one field as Yes";
$this->addError('arv_refill',$msg);
$this->addError('prep_refilled',$msg);
$this->addError('prep_initiate',$msg);
}
}
精彩评论