且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Yii 2 行为中重定向到登录以外的页面

更新时间:2023-12-02 15:05:22

您需要更改 yii\web\User 类的 loginUrl 属性.

You need to change loginUrl property of yii\web\User class.

如果您想全局更改它,请编辑您的配置:

If you want to change it globally, edit your config:

'components' => [
    'user' => [
        'loginUrl' => ['site/sign-in'],  
    ],
],

如果需要在具体的控制器或动作中更改,也可以这样设置:

If you need to change it in the specific controller or action, you can also set it like this:

Yii::$app->user->loginUrl = ['site/sign-in'];

您需要在需要执行此操作的控制器中覆盖 beforeAction() 方法.在此事件中执行所有访问检查.

You need to override beforeAction() method in controller where you need to do this. All access chesks are performed in this event.

/**
 * @inheritdoc
 */
public function beforeAction($action)
{
    if (parent::beforeAction($action)) {
        // If you want to change it only in one or few actions, add additional check

        Yii::$app->user->loginUrl = ['site/sign-in'];

        return true;
    } else {
        return false;
    }
}

有关更多详细信息,请查看关于property 和 事件.

For more details check official documentation about property and event.