3

拒绝访问控制器后如何在 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
            ],
        ],
    ];
}

在此之后它重定向到站点/登录。我怎样才能在那里制作像“此部分仅适用于注册用户”之类的 Flash 消息?

4

2 回答 2

5

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

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();
            },
        ],
    ];
}
于 2015-02-09T13:55:40.153 回答
1

您还可以将 denyCallback 添加到每个规则:

    [
      'allow' => false,
      'roles' => ['@'],
      'denyCallback' => function($rule, $action) {
         // callback logic
       }
    ]
于 2016-12-21T10:33:41.783 回答