如何在拒绝访问控制器后在Yii2中设置flash消息

时间:2015-02-08 19:35:51

标签: php redirect yii2 flash-message

如何在拒绝访问控制器后在Yii2中设置flash消息? 以下是拒绝访问http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html的方法:

public function behaviors()
{
    return [
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'only' => ['create', 'update'],
            'rules' => [
                // deny all POST requests
                [
                    'allow' => false,
                    'verbs' => ['POST']
                ],
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied
            ],
        ],
    ];
}

之后,它会重定向到site / login。如何在那里制作flash消息,例如“此部分仅适用于注册用户”?

2 个答案:

答案 0 :(得分:4)

您可以尝试添加拒绝回调吗?我希望这有效:

public function behaviors()
{
    return [
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'only' => ['create', 'update'],
            'rules' => [
                // deny all POST requests
                [
                    'allow' => false,
                    'verbs' => ['POST']
                ],
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied
            ],
            'denyCallback'  => function ($rule, $action) {
                Yii::$app->session->setFlash('error', 'This section is only for registered users.');
                Yii::$app->user->loginRequired();
            },
        ],
    ];
}

答案 1 :(得分:1)

您还可以为每条规则添加denyCallback:

    [
      'allow' => false,
      'roles' => ['@'],
      'denyCallback' => function($rule, $action) {
         // callback logic
       }
    ]