Yii2 - flash is not visible after redirection

Flash redirects may be corrupted if redirected. I made a 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 an action without a parameter, it adds a flash and redirects. When it displays a page, there is no flash.

The view element is beautiful, because if I install flash and render without redirection, it displays correctly.

Why?

EDIT: Layout view format:

 <?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() ?> 
+8
redirect php yii2
source share
5 answers

I got the same error until I found out that there is no return in my code. So, with return $this->redirect() it works fine, but with $this->redirect it doesn't work that way.

+18
source share

Your code looks fine, I'm not sure what the problem is. You can try using

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

Instead

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

Here is how most examples of Yii are. But your code looks fine after watching http://www.yiiframework.com/doc-2.0/yii-web-response.html#redirect()-detail

Are you sure that your session is working correctly and that you are not destroying it at any time?

This works for me:

 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, ]); } 
+4
source share

On the browse page, you should add: 'session-> getFlash (' success') ;? > ', as described here: Yii2 Session, Flash messages , then you will see your flash message

+1
source share

Add return to your redirect

 Yii::$app->session->getFlash('key', 'message'); return $this->redirect(['yourAction']); 
+1
source share

I have a solution

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

All Articles