How to set a flash message in Yii2?
Asked Answered
A

5

31

i followed this Link. My code is as follows in controller

public function actionFunction4()
    {
        $this->layout="sintel";
        $model= new Customers();
        \Yii::$app->getSession()->setFlash('success', 'successfully got on to the payment page');
        return $this->render("function4",['model'=>$model]);
    }

in the view

 <div id="message">

          <?= Yii::$app->session->getFlash('success');?>
      </div>

now the result of what i did is not what i expected. I got a message "successfully got on to the payment page" like i have echo ed it. If it is similar to echo then why do we need a flash message in Yii2. I think i may be missing something in my code that make my flash message appear like a regular one.

Adjacent answered 26/9, 2015 at 4:17 Comment(2)
You're confused about what a flash message is (in yii). It's simply a message that will show once, and then gets removed from the session.Hardpressed
yes i was a bit confused.Adjacent
A
66

Setting flash message

A flash message is used in order to keep a message in session through one or several requests of the same user. By default, it is removed from session after it has been displayed to the user.

Flash messages can be set using the setFlash() Method

Add below code in your controller file like:

Yii::$app->session->setFlash('success', "Your message to display.");

Example:

class ProductsController extends \yii\web\Controller
{
    public function actionCreate()
    {
         $model = new User();

         if ($model->load(Yii::$app->request->post())) {
              if ($model->save()) {
                  Yii::$app->session->setFlash('success', "User created successfully."); 
              } else {
                  Yii::$app->session->setFlash('error', "User not saved.");
              }
              return $this->redirect(['index']);
         }
         return $this->render('create', [
             'model' => $model
         ]);
    }
}

Displaying flash message

To check for flash messages we use the hasFlash() Method and to obtain the flash message we use the getFlash() Method.

By default, fetching a message deletes it from the session. This means that a message is meant to be displayed only on the first page served to the user. The fetching methods have a boolean parameter that can change this behavior.

So showing of the flash message defined above in a view is done by

// display success message
<?php if (Yii::$app->session->hasFlash('success')): ?>
    <div class="alert alert-success alert-dismissable">
         <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
         <h4><i class="icon fa fa-check"></i>Saved!</h4>
         <?= Yii::$app->session->getFlash('success') ?>
    </div>
<?php endif; ?>

// display error message
<?php if (Yii::$app->session->hasFlash('error')): ?>
    <div class="alert alert-danger alert-dismissable">
         <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
         <h4><i class="icon fa fa-check"></i>Saved!</h4>
         <?= Yii::$app->session->getFlash('error') ?>
    </div>
<?php endif; ?>
Amaranth answered 26/9, 2015 at 5:36 Comment(4)
thanks it is working. so i now have two ways to do it :-)Adjacent
Nice answer. Thank you.Thanks
This explains a bit more about Yii2 Flash Message.Candycandyce
i think there is a lil bit mistake in here <div class="alert alert-erorr alert-dismissable"> it should be <div class="alert alert-danger alert-dismissable"> just a bootstrap class changes !Gristly
T
9

I know this is old, but it is the first result in google search so I will update it. The setting part is still the same in yii2, all you have to do is add this in your controller

Yii::$app->session->setFlash('danger', 'you message');

first argument of setFlash could be any of :

error,danger,success,info,warning

which will determine the style color of the flash message.

Now for the displaying part, all you have to do is place this in your layout file :

<?= common\widgets\Alert::widget() ?>

if you don't have a layout file, just add it in any view you want to display a falsh message in.

Hope this answer helps others.

Tyne answered 10/9, 2018 at 5:24 Comment(0)
B
3

The advantage of the flash message is that it gets only shown once. You don't need to provide the if/else logic anymore. And if you put the code to display the flash message in the layout view file (often view/layout/main.php) you can set the flash message in every action where it is needed, use normal responses or redirects and you can be sure that it gets displayed only a single time. That makes life a bit easier. That is the idea of the flash messages - not that it disappears after a certain period.

See section about flash messages in the guide.

Binding answered 26/9, 2015 at 5:43 Comment(1)
thanks. my concept of flash messsage was quite differentAdjacent
W
1

Less Code. If you don't want if else condition follow

 Yii::$app->session->setFlash('msg', '
     <div class="alert alert-success alert-dismissable">
     <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
     <strong>Validation error! </strong> Your message goes here.</div>'
  );

And in your view

 <?= Yii::$app->session->getFlash('msg') ?>
Wendalyn answered 13/8, 2017 at 23:18 Comment(0)
F
0

Below is the controller class for adding products

class ProductsController extends \yii\web\Controller
{
    public function actionCreate()
    {
        $ProductsModel = new Products();

        if ($ProductsModel->load(Yii::$app->request->post()) && $ProductsModel->save()) {
            Yii::$app->session->setFlash('success', "Product Added Successfully");
            return $this->redirect(['create']);
        }
        else{ 
            return $this->render('create', [
                'ProductsModel' => $ProductsModel
            ]);
        }
    }
}
Fango answered 19/11, 2017 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.