Tuesday, November 4, 2014

Redirect if user is not loggin in Yii

This code shows how to redirect a user that is not loggin.
if(Yii::app()->user->isGuest){
 $this->redirect(array('/post/index')); 
}
change /post/index to your proper model path where you want the user to be redirected if not loggin
 $this->redirect(array('/post/index')); 
Yii::app()->user->isGuest is a built in function of yii to determine if a user is not loggin.
we can put this code in our view but i prefer to put it inside action controller so that it is more easy to maintain and separate the logic between view and controller. ex
public function actionView($id)
{ 
 if(Yii::app()->user->isGuest){
  $this->redirect(array('/post/index')); 
 }
 
 $this->layout = 'column1';
 $this->render('view',array(
  'model'=>$this->loadModel($id),
 ));
}

No comments:

Post a Comment