在重定向的情况下,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并进行渲染而没有重定向,则会正确渲染。
为什么?
编辑: 布局视图代码:
<?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() ?>
答案 0 :(得分:23)
我发现同样的错误,直到我发现我的代码中缺少return
。因此,使用return $this->redirect()
它可以很好地使用$this->redirect
,但效果不佳。
答案 1 :(得分: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,
]);
}
答案 2 :(得分: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.
答案 3 :(得分:1)
在视图页面上,您应该添加:&#39; session-&gt; getFlash(&#39; success&#39;); ?&GT;&#39;就像在这里描述的那样:Yii2 Session, Flash messages,然后你会看到你的flash消息
答案 4 :(得分:1)
在我的情况下,当我从beforeAction
方法重定向时,Flash消息不可用。使用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;
}
希望它会帮助某人。