11

在重定向的情况下,Flash 消息似乎被破坏了。我做了简单的测试代码:

public function actionTest($test = 0) {
    if($test == 0) {
        Yii::$app->getSession()->addFlash('success', 'Follow the white rabbit');
        return Yii::$app->getResponse()->redirect(array('test', 'test' => 1));
    }
    return $this->render('test', []);
}

我调用不带参数的动作,它添加了一个闪光和重定向。当它呈现页面时 - flash 不存在。

视图部分很好,因为如果我设置 flash 并在没有重定向的情况下进行渲染,它会正确渲染。

为什么?

编辑:布局视图代码:

<?php

use frontend\widgets\Alert;

$this->beginPage();
echo $this->render('partials/head');
?>

<body class="no-sidebar">
    <?= $this->beginBody() ?>
    <div id="header">
        <?= $this->render('partials/top') ?>
        <?= $this->render(Yii::$app->user->isGuest ? 'menus/guest' : 'menus/registered') ?>
    </div>
    <!-- Main -->
    <div id="main">
        <?= Alert::widget() ?>
        <?= $content ?>

    </div>

    <?= $this->render('partials/footer') ?>
    <?= $this->endBody() ?>
</body>
</html>

<?php $this->endPage() ?>
4

6 回答 6

27

在我发现return我的代码中缺少 之前,我遇到了同样的错误。所以,用return $this->redirect()它工作得很好,用$this->redirect它不能很好地工作。

于 2015-12-08T07:18:45.400 回答
5

您的代码看起来不错,我不确定问题是什么。您可以尝试使用

return $this->redirect(['test', 'test' => 1]);

代替

return Yii::$app->getResponse()->redirect(array('test', 'test' => 1));

这就是大多数 Yii 的例子。但是在查看http://www.yiiframework.com/doc-2.0/yii-web-response.html#redirect()-detail之后,您的代码看起来还不错

你确定你的会话正常工作并且你没有在任何时候破坏它吗?

这对我有用:

public function actionChangeDetails()
    {
        $model = Contact::findOne(Yii::$app->user->identity->id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Form Saved');
            return Yii::$app->getResponse()->redirect(['my-account/change-details']);
        }

        return $this->render('changeDetails', [
            'model' => $model,
        ]);
    }
于 2014-10-06T23:45:50.473 回答
2

我有一个解决方案:您可以在要显示消息的视图文件中添加以下行:

然后您可以在视图文件中添加下面的行,该消息应该出现在其中。

if(Yii::$app->getResponse()->getStatusCode() != 302) {
   Yii::$app->session->getFlash('error');
}

或者,您可以在内容布局中添加以下行

<?= Alert::widget() ?>
// Before the line
<?= $content ?>
// in app/views/layouts/_content.php 
// Depending on how you arranged your files.
于 2016-06-13T18:59:05.897 回答
2

添加return您的redirect

Yii::$app->session->getFlash('key', 'message');

return $this->redirect(['yourAction']);
于 2017-08-10T21:51:51.580 回答
1

在视图页面上,您应该添加: 'session->getFlash('success'); ?>' 就像这里描述的那样:Yii2 Session, Flash messages,然后你会看到你的flash message

于 2015-01-14T12:13:59.567 回答
1

beforeAction在我的情况下,当我从方法重定向时,闪存消息不可用。使用Yii::$app->end()真的帮助了我。这是我的代码:

public function beforeAction($action) {
    if ($someVariableIs === false) {
        Yii::$app->session->addFlash("negative", "My flash message");
        Yii::$app->getResponse()->redirect(["/path/to/redirect"]);
        Yii::$app->end();
    }

    // some of your code...

    return true;
}

希望它会帮助某人。

于 2020-03-03T11:49:20.150 回答