简体   繁体   中英

Condtitional Validation rules in Yii

I have a problem in custom validation rules in Yii. I have some fields like day1s , day1e , day2s , day2e etc. I want to check whether these attributes have the same value stored in my db or not before creating a new record. And also check for different userid. If a value already exists I want to generate an error and prompt the user to change the value. I figured to do something like this:

 array('day1s, day1e, day2s etc','unique','message'=>'day1s is already exist, please change'),

This kinda work but I want to modify it. The default value of this is "00:00" and if I put this rule then every time I will go and create a new record it generates the error, except the first time. I want to ignore that when day1s==00:00 . And also if the user changes(in my occasion the user is SchoolID). I'm having trouble wrapping around my head on how to do that. Thanks in advance!

Add allowEmpty in rule:

array('day1s, day1e, day2s etc','unique','message'=>'day1s is already exist, please change', 'allowEmpty'=>true),

In controller before validation add this code:

if($model->day1s == "00:00") {
   $model->day1s = '';
} 

Sorry for being so late to answer. In controller you mean in my action Create?Before $model->save ?I tried that but it doesn't seem to work. I figured to make a function in my model like this:

public function unique() {       
 if ($this->day1s == "00:00" || $this->day1s == "0:00") {

       $this->day1s='';//here it seems to work for the 00:00
 } else {
     //but my rule gets ignored now for any other values. What can I add here to make it work?
 }

Also sorry for posting an answer instead of editing my question.

I figured it out eventually: my rules are like this:

array('day1s,day1e, day2s, day2e, day3s, day3e, day4s, day4e, day5s, day5e, day6s, day6e, day7s, day7e','unique','message'=>'This already exist, please change', 'allowEmpty'=>true,
                 'criteria' => array(
                 'condition' => 'schoolid=:schoolid',
                 'params' => array(':schoolid' => $this->schoolid))
               ),

and my controller is like this:

if ($model->day1s == "00:00" || $model->day1s == "0:00") {
    $model->day1s='';//for custom validation rule 'unique'
                    } 
if ($model->day1e == "00:00" || $model->day1e == "0:00") {
                            $model->day1e='';
                    }
 .....
 if($model->validate()){
        if($model->save())
                    $this->redirect('admin');}
    }  

Thanks again for your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM