How to set a flash message in Yii2?

穿精又带淫゛_ 提交于 2019-11-30 14:39:03

问题


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.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/32793569/how-to-set-a-flash-message-in-yii2

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