arrow_back
Back

Yii2 flash messages: setFlash, hasFlash, and the Alert widget

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Set a flash message in a controller and redirect:

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 messages in a view:

<?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">&times;</button>
        <h4><i class="icon fa fa-check"></i>Saved!</h4>
        <?= Yii::$app->session->getFlash('success') ?>
    </div>
<?php endif; ?>

<?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">&times;</button>
        <h4><i class="icon fa fa-ban"></i>Error!</h4>
        <?= Yii::$app->session->getFlash('error') ?>
    </div>
<?php endif; ?>

Using the Alert widget

The basic application template ships with an Alert widget that renders all flash messages at once:

<?= \app\widgets\Alert::widget(); ?>
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward