登录 Yii 后重定向到模块


Redirect to module after login Yii

在yii中建立一个网站,其中有3种类型的用户。在UserIdentity::authenticate()中,我像这样设置了用户类型。 $this->setState('role', $user->role->id); 根据这种类型,我想重定向到属于此类用户的模块。更具体地说;如果 Yii::app()->user->role == 3 我想重定向到名为"tradesman"的模块的默认页面。这是我在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));
}

重定向到模块无法以这种方式工作。我收到 Php 通知"试图获取非对象的属性"。然后,我在商人模块中创建了一个方法'defaultUrl,该方法返回Yii::app()->createUrl($this->getId() . '/default/index'); .我试图重定向到Yii::app()->controller->module->defaultUrl,但结果是一样的。

我也尝试了$this->redirect('tradesman/default/index');&$this->redirect('application.modules.tradesman');,但后来我收到一个404错误,说"系统无法找到请求的操作'商人'。

如果我以角色 3 的用户身份登录,并且导航到模块的默认 URL,它确实有效。但是我该如何重定向?

尝试$this->redirect('/tradesman/default/index')并确保 in 模块存在DefaultController并且它是操作actionIndex

更新:
@Николай Конев 是对的,它只是重定向到 url /tradesman/default/index,而不是路由。对于按路由重定向:

$this->redirect( array('/tradesman/default/index') )

它是模块tradesman、控制器default和动作index的绝对路由。如果你想重定向到同一模块中的控制器,你可以使用以下代码:

$this->redirect( array('default/index') )

如果要重定向到主应用程序控制器,则需要使用:

$this->redirect( array('/default/index') ) // with "/" at the beginning

再次感谢@Николай Конев

为了确保路由正常工作,您必须将数组传递给CController::redirect()

    // for example
    $this->redirect(['/route/starts/from/slash']);
    // your case
    $this->redirect(['/tradesman/default/index']);

在其他情况下,您将在 url 规则更改时破坏重定向。