How To Filter Validation Rules ?

Hey everyone, thanks for taking the time to read .

I have an integer column in my db called Priority. This column should have only one unique number. Eg Priority 1 , 2 , 3 ,4 and so on , but a different user in the same table can have also the same priority. But the same user cannot have the same priority.

I tried to use unique in the validation rules but obviously it validates all of the data and it dose not filter by user id . How can i filter the validation rules only on the current user or how can i check if the Priority only exists for the current user.

For a start, you can enforce the restriction in the database (to ensure data integrity). Add a unique constraint across both the user ID and priority fields. That’ll prevent the risk of invalid data.

Next, I suspect that you can use the criteria property of the CUniqueValidator class:




    array(

        'priority_field', 'unique', 'criteria'=>array(

            'condition'=>'user_field = :userValue',

            'params'=>array(':userValue', $userValueToTest),

        ),

    ),



Try something like the above.

Thanks , code seems logical . But its still not validating. Am i forgetting something in the controller

A better question would be how can i write a function that will filter the results

By "filter", are you asking how to retrieve a subset of the data or are you still talking about inserting / updating?

Dear Friends

Let us assume that we have a model CustomModel. It has got two fields apart from other fields.

1.priority

2.username.

As Keith suggested, we can make a rule in the following way.




array(

        'priority', 'unique','className'=>'customModel','attributeName'=>'priority', 'criteria'=>array(

            'condition'=>'username = :username',

            'params'=>array(':username'=> $userName),

//$userName may be like Yii::app()->user->id or you might have assigned in some other way.

//If you are using the rule in the same model for same attribute , properties 'className','attributeName' not needed. 

        ),

    ),



or

We can make custom validator.




array(


     'priority','checkUniquness'

)




public function checkUniqueness($attribute,$params)

    {


      if(CustomModel::model()->exists('username=:username AND priority=:priority',array(

                    ':username'=>$this->username,

                    ':priority'=>$this->priority

                  )))

               $this->addError($attribute,"You have your priority set already");





   }



Regards.

Thanks guys i implemented the above code just modified it to my needs and now its validating like a boss. Thanks a lot