Expression To Perform A Model Rule


is there a way to apply a rule on Model by condition?

I mean something like that

public function rules() {

    array('specialattribute', 'numerical', 'integerOnly' => true, 

'when'=>'Yii::app()->user->checkAccess("superadmin") or a method'),


instead of

public function rules() {

    array('specialattribute', 'numerical', 'integerOnly' => true, 



to avoid the repeateding set of scenario in Controllers/action

if there is no way yet, may be included in yii 2 :)

In Yii2 scenario will be more or less mandatory to use.

samdark, thanks for response

I hope what you mean will cover more cases like the one I mentioned.

You can always create rules array inside of the method and return it:

public function rules() {

    $rules = array();

    if (Yii::app()->user->checkAccess("superadmin")) {

        $rules[] = array('specialattribute', 'numerical', 'integerOnly' => true); 


    $rules[] = array('otherattribute', 'required');

    // ...

    return $rules;


For dependend data validation(in case you want to do that) you should create custom validator, not use scenarios.

Cebe, you are right!

I have used that in config/main.php, accessRules in Controller etc

I did’t think that the same thing could be applied also in rules method (although it is exactly the same thing!)

I have used both condition way and Expressions in accessRules, so I thought there was something like Expressions in models rules.

  1. Yes I could use conditions in custom validators, but why did you say ‘not use scenarios’? Controllers could set the scenarios of the model by condition so the results are the same, Please tell me if it is best way and why.