Required only when manually created

Hi,

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

          return;


         //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() ....

        

        if(empty($this->ab))

           $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.

Hello.

You should use scenarios: http://www.yiiframework.com/wiki/266/understanding-scenarios/

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

  1. using scenario

http://www.yiiframework.com/doc/guide/1.1/en/form.model#triggering-validation

  1. saving without validation

CActiveRecord::save(false) … http://www.yiiframework.com/doc/api/1.1/CActiveRecord/#save-detail

CActiveRecord::saveAttributes() … http://www.yiiframework.com/doc/api/1.1/CActiveRecord#saveAttributes-detail

[EDIT]

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

Change:


array('myField', 'required'),

To:


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

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

This is especially useful for password fields.