简体   繁体   English

如何使用yii2将注册用户重定向到其主页

[英]How to redirect registered users to their homepage using yii2

I'm a front-end designer, and to be honest, i'm still new to Yii2. 我是前端设计师,说实话,我还是Yii2的新手。

I have to create two home page. 我必须创建两个主页。 One for the non-registered users and one for registered users. 一种用于非注册用户,一种用于注册用户。

I am able to create a homepage for non-registered users, the one that is in site/index . 我可以为未注册用户创建一个主页,该主页位于site/index

Now, I am having trouble with regards to routing registered users to their own homepage. 现在,在将注册用户路由到他们自己的主页方面,我遇到了麻烦。 I have read the docs on yii2 documentation but it's quite confusing for a newbie like me. 我已经阅读了yii2文档上的文档,但是对于像我这样的新手来说却很困惑。

If a registered user logs in, i'd like to show them their own home page which is on the app/index . 如果注册用户登录,我想向他们显示他们自己的主页,该主页位于app/index But it's not working for me. 但这对我不起作用。

here's the code: 这是代码:

public function actionLogin()
{

    $this->layout='login-main';

    if (!Yii::$app->user->isGuest) {
        $this->layout='app-main';
        return $this->redirect( array('app/index') );
    }

    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) {
         $this->layout='app-main'; 
         return $this->redirect( array('app/index') );
    } else {
        return $this->render('login', [
            'model' => $model,
        ]);
    }
}

When I implement this code, I get this error. 当我实现此代码时,会出现此错误。 (please see attached image) (请看附件图片)

error 错误

can you let me know if this is right? 你能告诉我这是否正确吗? or any other suggestions? 或其他建议?

Thank you! 谢谢!

create AppController and this is the code that u should redirect logged in user to their private area 创建AppController,这是您应该将登录用户重定向到其私有区域的代码

if (!Yii::$app->user->isGuest) {

    return $this->redirect( ['/app'] );
}

and the layout of the logged in user (app controller) should set in app controller 并且已登录用户(应用程序控制器)的布局应在应用程序控制器中设置

 $this->layout='app-main';

In login action write the below code 在登录操作中,编写以下代码

if ( !Yii::$app->user->isGuest )
{
  return $this->goHome();
}

My suggestion is create two alias of url once for guest user and second for registred user then you need to check on logiin action that user is guest or not. 我的建议是为访客用户创建两个URL别名,为注册用户创建第二个URL,然后您需要检查用户是否为访客的登录操作。 Accordingly you can redirect with url. 因此,您可以使用url重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM