Thursday, August 25, 2011

Setting the returnUrl for a User in Yii

When you have logged in a user in Yii, the default is for them to be redirected to the main home page of the site. But sometimes, you want them to go elsewhere. Here's a forum question (in which the op answers it for himself) that is very helpful in figuring out how to do this (minimally documented) function:

returnUrl question? - Yii Framework Forum:

'via Blog this'

In my case, I needed the user to return to an admin module's home page. Here's what I did:

In SiteController, in the actionLogin function, add a line of code after the user has successfully logged in, like this: Yii::app()->user->setReturnUrl('/admin');

Including the slash on the front of "admin" tells the app to start at the top level (the root of the actual site) when determining the path to take rather than a relative path. For my app, '/admin' means the admin module.

Here is what the entire actionLogin function in SiteController.php looks like:

public function actionLogin()
{
$model=new LoginForm;

// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}

// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
Yii::app()->user->setReturnUrl('/admin');
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}

1 comment: