How To Apply Validation Rules Only When User Is Guest?

Hi,

is there any simple way to apply a validation rule to a model only if the user is a guest or do I have to implement my own validation rule?

I know about the scenarios but I just need one view and I don’t want to use two models just for that.

Any help would be very appreciated.

Diego

Well, scenarios were the way to go as there is no easy way to switch validators on and of on the fly. I wouldn’t know how that would leave you with two models, though.

one indirect way

just check with a if condition inside the model rules array


if(Yii::app()->user->Id)

{

}

for example




public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

if(Yii::app()->user->Id)

{

		return array(

			array('student_id, exam_id, grading_level_id, is_failed', 'numerical', 'integerOnly'=>true),

			array('marks', 'length', 'max'=>7),

			array('remarks', 'length', 'max'=>255),

			array('created_at, updated_at', 'safe'),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, student_id, exam_id, marks, grading_level_id, remarks, is_failed, created_at, updated_at', 'safe', 'on'=>'search'),

		);

	}

}



Thanks Da:Sourcerer for taking the time to reply.

I think I did not format my sentence clearly, sorry about that.

Whan I meant is that if you want to have two different scenarios you need two different views (as for what I understood) and a different way to go is by having only one view but 2 different models.

simply use this


if(Yii::app()->user->isGuest)

{

}

inside rules .

This will work

Thanks a lot Rajith R! it completely does the trick.

I still think there should be a neater way.

Diego

Hi

u can apply simple way. on condition in rule function




return array(

                        array('student_id, exam_id, grading_level_id, is_failed','required','numerical', 'integerOnly'=>true,'on'=>'user'),

                        array('grading_level_id, is_failed', 'required','numerical', 'integerOnly'=>true,'on'=>'guest'),

                        array('marks', 'length', 'max'=>7),

                        array('remarks', 'length', 'max'=>255),

                        array('created_at, updated_at', 'safe'),

                        // The following rule is used by search().

                        // Please remove those attributes that should not be searched.

                        array('id, student_id, exam_id, marks, grading_level_id, remarks, is_failed, created_at, updated_at', 'safe', 'on'=>'search'),

                );


$model = new Users('user');

and guest validation u can use the guest


$model = new Users('guest');

Hope it will be done

yes scenarios , but if you have a set of validators , then best way "if"