Required only when manually created


A question. How do I create a validation rule to be active only when user creates a model from the actionCreate?

I will have same model created automatically (or by other actions) and then there will be an option to create it by using ‘Create new’ form. Now I want one of the fields to be required only when user is using the form to create it. Otherwise it should pass validation with that field empty (or even null).

Thanks in advance!

You can implement your own validation function where you can check whatever you want:


     * Declares the validation rules.


    public function rules()


        return array(

            array('someField', 'checkSomeField'),




    public function checkSomeField($attribute,$params)


        if(Yii::app()->user->isGuest) //no user loggedIn


         //You can access every value of the model here: if($this->attrXY == ...), $this->xy ... 

         //or check $_POST['ahiddenformfield'] you have in the form

         //You can check the users session: if(Yii::app()->user->hasState() ....



           $this->addError('ab','Is required'); 



You can use Yii::app()->user->setState(…) on opening the edit/insert form or use a hidden field in the form and check the $_POST vars in the validation function.


You should use scenarios:

You have 2 more options other than a custom validation method:

  1. using scenario

  1. saving without validation

CActiveRecord::save(false) …

CActiveRecord::saveAttributes() …


As bennouna says, using scenarios might be the most decent option.


array('myField', 'required'),


array('myField', 'required', 'on'=>'insert'),

This field will now be required only when creating a new record.

This is especially useful for password fields.