Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Session, Flash messages

Tags:

session

yii2

I have a problem with setting flash messages. So, i have an action which in some cases should redirect with flash. It looks like this:

if(!$this->_isSameOrg($reports)){     \Yii::$app->session->setFlash('consol_v_error',\Yii::t('app/consol', 'some_text'));     $this->redirect(\Yii::$app->request->getReferrer());     return; } 

After redirect in view i have this

<div class="col-lg-12">     <?php if(Yii::$app->session->hasFlash('consol_v_error')): ?>         <div class="alert alert-danger" role="alert">             <?= Yii::$app->session->getFlash('consol_v_error') ?>         </div>     <?php endif; ?> </div> 

The problem is i don't see any message here. In Debug panel i see SESSION var populated with good flash, but it doesn't display with this if-statement. Maybe i need to configure session component or something?...

like image 291
Anton Abramov Avatar asked Aug 18 '14 15:08

Anton Abramov


People also ask

How to show flash message in Yii2?

Displaying flash messages. To check for flash messages we use the hasFlash() Method and to obtain the flash message we use the getFlash() Method. Since Yii v1. 1.3, there is also a method getFlashes() to fetch all the messages.

What is session in yii2?

Session is a Web application component that can be accessed via Yii::$app->session . To start the session, call open(); To complete and send out session data, call close(); To destroy the session, call destroy(). Session can be used like an array to set and get session data.

How can I get session data in Yii?

In Yii, you can get access to sessions via the session application component. Step 1 − Add the actionOpenAndCloseSession method to the SiteController. In the above code, we get the session application component, open a session, check whether it is active, close the session, and finally destroy it.


1 Answers

To set flash,try like

  \Yii::$app->getSession()->setFlash('error', 'Your Text Here..');    return $this->redirect('Your Action'); 

And to display it..

   <?= Yii::$app->session->getFlash('error'); ?> 
like image 144
Dency G B Avatar answered Oct 25 '22 08:10

Dency G B