model rules depended by user roles-permissions

This wiki article has not been tagged with a corresponding Yii version yet.
Help us improve the wiki by updating the version information.

This is a reference about model validators and user roles. In many cases we want model validators to applied only for some privileged users or not

Suppose you want the user able to submit few fields for the model And a user with admin roles able to submit extra fields for the same model

In addition we want a user to fill the required captcha but we don't want this field for the admin

How to achieve that ?

Here an example

In model

public function rules() { 
return array(
array('verifyCode', 'captcha',  'allowEmpty' => !CCaptcha::checkRequirements(),'except' => 'adminrole'),
array('enabled_user', 'numerical', 'integerOnly' => true, 'on' => 'adminrole'), 

In Controller / action

$model = new YourModel:model->findPyPk($mid);
if (Yii::app()->user->checkAccess('admin')) {
            $model->scenario = 'adminrole';

if (isset($_POST['YourModel'])) {
            $model->attributes = $_POST['YourModel'];
if (!$model->save())
throw new CHttpException(404, 'An error occurred!');                
$this->render('update', array('model' => $model));

In your view (_form.php)

  <?php if (Yii::app()->user->checkAccess('admin')) } ?>
        <div class="row">
            <?php echo $form->labelEx($model, 'enabled_user'); ?>
            <?php echo $form->checkbox($model, 'enabled_user')); ?>
            <?php echo $form->error($model, 'enabled_user'); ?>
   <?php } else { 
 if (CCaptcha::checkRequirements()): 
        <div class="row">
            <?php echo $form->labelEx($model, 'verifyCode'); ?>
                <?php $this->widget('CCaptcha'); ?>
                <?php echo $form->textField($model, 'verifyCode'); ?>
            <?php echo $form->error($model, 'verifyCode'); ?>
    <?php endif;
} ?>