Building a site in yii, where there are 3 types of users. In the UserIdentity::authenticate() I set the type of user like this. $this->setState('role', $user->role->id);
Depending on this type, i want to redirect to a module belonging to this type of user. To be more specific; if Yii::app()->user->role == 3 I want to redirect to the default page of the module called 'tradesman'. This is what I got in SiteController::actionLogin():
/**
* Displays the login page
*/
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()){
switch(Yii::app()->user->role){
case 3:
$this->redirect(Yii::app()->controller->module->tradesman);
break;
default:
$this->redirect(Yii::app()->user->returnUrl);
}
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
The redirect to the module doesn't work this way. I'am getting the Php notice 'Trying to get property of non-object'. I've then made a method 'defaultUrl in the TradesmanModule which returns Yii::app()->createUrl($this->getId() . '/default/index');
. I tried to redirect to Yii::app()->controller->module->defaultUrl
, but the result was the same.
I also tried $this->redirect('tradesman/default/index');
& $this->redirect('application.modules.tradesman');
but then i'am getting a 404 error saying 'The system is unable to find the requested action "tradesman".'.
If I am logged in as a user with role 3, and I navigate to the default url of the module, it does work. But how can i redirect?
Try $this->redirect('/tradesman/default/index')
and make sure that in module exists DefaultController
and it's action actionIndex
UPDATED:
@Николай Конев is right, it's just redirects to the url /tradesman/default/index
, not route. For redirecting by route:
$this->redirect( array('/tradesman/default/index') )
it's absolute route to module tradesman
, controller default
and action index
. If you want redirects to controller in the same module you may use this code:
$this->redirect( array('default/index') )
And if you want redirects to the main application controllers you need to use:
$this->redirect( array('/default/index') ) // with "/" at the beginning
Thanks to @Николай Конев again
To ensure route is working, you have to pass array to CController::redirect()
:
// for example
$this->redirect(['/route/starts/from/slash']);
// your case
$this->redirect(['/tradesman/default/index']);
In other case you will have redirect broken on url rules change.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.