在 Yii 2 行为中重定向到登录以外的页面 [英] Redirect to a page other than login in Yii 2 behaviors

查看:21
本文介绍了在 Yii 2 行为中重定向到登录以外的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了在 Yii 2 中的行为方法中登录之外,还有其他方法可以重定向到页面吗?

Is there any way to redirect to a page other than login in behaviors method in Yii 2?

我的行为方法内容:

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
            ],
        ],
        'access' => [
            'class' => AccessControl::className(),
            'only' => [ 'create','update' ],
            'rules' => [
                [
                    'allow' => true,
                    'actions' => [ 'create'],
                    'roles' => ['@'],
                ],
                [
                    'allow' => true,
                    'actions' => ['logout'],
                    'roles' => ['?'],
                ],
            ],
        ],
    ];
}

但它重定向到登录.我需要指定另一个重定向页面或调用:

But it redirects to login. I need to specify another redirect page or call:

throw new \yii\web\HttpException(403, 'The requested Item could not be found.');

推荐答案

您需要更改 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 和 <一个 href="http://www.yiiframework.com/doc-2.0/yii-web-controller.html#beforeAction%28%29-detail">事件.

For more details check official documentation about property and event.

这篇关于在 Yii 2 行为中重定向到登录以外的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆