How to create different rules depending on condition


I have a model class called "Usuario" that stores user information belonging to a database table with that name.

When I add a new user, I show a form to add the information. I have in that form 2 fields to allow specifying the password. Only in that case, password must be required.

When I am editing a user, password fields are not showm so that, these fields don’t have to be required.

I tried this:

public function rules()


        $reglas = array(

    		    array('username, nombres, apellidos, email', 'required'),


    			array('username', 'filter', 'filter'=>'strtolower'), 




	    if ($this->isNewRecord)


    	    $reglas = array_merge($reglas, array(

    		    array('password, password_repeat', 'required'),

    			array('password','length','max'=>50, 'min'=>6),

			    array('password_repeat','length','max'=>50, 'min'=>6),

			    array('password_repeat', 'compare', 'compareAttribute'=>'password')));



	    return $reglas;


But it didn’t work.

How can I do it?



You must use scenarios.

I have rewrote your code:

public function rules()


        return array(

                    array('username, nombres, apellidos, email', 'required'),

                    array('password, password_repeat', 'required', 'on' => 'insert'), //attention here!



Just this =)

You can read more about scenarios on the guide.

Further more when you then instantiate the class in your action like:

$form = new User;

You will need to define the scenario:

 $form = new User;



That’s how to apply the scenarios you make. So you could define multiple scenarios in your one model class and then depending on the action, call a different scenario when you instantiate the class.


Thanks a lot! it worked perfectly :rolleyes: