Yii2 - flash not visible after redirect

Joe picture Joe · Oct 2, 2014 · Viewed 15.1k times · Source

Flash messages seems to be broken in case of redirecting. I made simple test code:

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', []);
}

I call the action without parameter, it adds a flash and redirects. When it renders the page - flash is not present.

The view part is fine, because if I set flash and make a render without redirect it is rendered properly.

Why?

EDIT: Layout view code:

<?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() ?>

Answer

user5653303 picture user5653303 · Dec 8, 2015

I've gotten the same error until I found out that the return is missing in my code. So, with return $this->redirect() it works just fine and with $this->redirect it does not work well.