Git-able
Git-able

Reputation: 2677

Yii - Displaying specific views depending on field value

Does anyone know how to assign different views to users depending on a field value?

Specifically, I am looking for a function that would give a user with username 'user1' view 'templateA' if field xyz = 'user1'. If user username is anything other than field xyz value, view 'templateB' is displayed to user.

Which direction do you recommend I take?


SOLVED:

A working example is given below for the controller actionUpdate, in case it helps anyone else.

Yii::app()->user->id refers to the id of the logged in user. $model->ownerId is the ownerId field of the table referred to in this model.

The alternative view files 'update1.php' and 'update2.php' are in my protected/views/circle/swatch/ folder.

In my 'CircleController.php':

public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        if (Yii::app()->user->id == $model->ownerId) {
        $template = 'update1';
        } else {
        $template = 'update2';

         }
        if(isset($_POST['Circle'])) 
        {
            $model->attributes=$_POST['Circle'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }
         $this->render('swatch/' . $template,array(
            'model'=>$model,
        ));
    }

Upvotes: 1

Views: 413

Answers (1)

Tim
Tim

Reputation: 963

I think you have two possibilities:

  1. $this->render('/dynamic/' . $template);
  2. $this->render('/static/page', array('with-dynamic' => $variables));

Edit:

In your case:

public function actionDisplayDynamicTemplate()
{
    if (Yii::app()->user->username == 'user1') {
        $template = 'templateA';
    } else {
        $template = 'templateB';
    }

    $this->render('user/' . $template);
}

All you need is a directory named user in your views folder, with the files templateA.php and templateB.php.

Upvotes: 3

Related Questions