How to set a flash message in Yii2?

我与影子孤独终老i 提交于 2019-11-30 11:30:35

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; ?>

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.

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.

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') ?>
Sanju Kaniyamattam

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
            ]);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!