Alert.php 2.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace frontend\widgets;

/**
11 12
 * Alert widget renders a message from session flash. All flash messages are displayed
 * in the sequence they were assigned using setFlash. You can set message as following:
13
 *
14 15 16 17 18 19 20 21 22 23 24
 * ```php
 * \Yii::$app->getSession()->setFlash('error', 'This is the message');
 * \Yii::$app->getSession()->setFlash('success', 'This is the message');
 * \Yii::$app->getSession()->setFlash('info', 'This is the message');
 * ```
 *
 * Multiple messages could be set as follows:
 *
 * ```php
 * \Yii::$app->getSession()->setFlash('error', ['Error 1', 'Error 2']);
 * ```
25
 *
26
 * @author Kartik Visweswaran <kartikv2@gmail.com>
Bohdan Shulha committed
27
 * @author Alexander Makarov <sam@rmcreative.ru>
28
 */
Kartik Visweswaran committed
29
class Alert extends \yii\bootstrap\Widget
30
{
31 32 33 34 35 36 37 38 39 40 41 42 43
    /**
     * @var array the alert types configuration for the flash messages.
     * This array is setup as $key => $value, where:
     * - $key is the name of the session flash variable
     * - $value is the bootstrap alert type (i.e. danger, success, info, warning)
     */
    public $alertTypes = [
        'error'   => 'alert-danger',
        'danger'  => 'alert-danger',
        'success' => 'alert-success',
        'info'    => 'alert-info',
        'warning' => 'alert-warning'
    ];
44

45 46 47 48
    /**
     * @var array the options for rendering the close button tag.
     */
    public $closeButton = [];
49

50 51 52
    public function init()
    {
        parent::init();
53

54 55 56
        $session = \Yii::$app->getSession();
        $flashes = $session->getAllFlashes();
        $appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
57

58
        foreach ($flashes as $type => $data) {
59
            if (isset($this->alertTypes[$type])) {
60 61 62 63
                $data = (array) $data;
                foreach ($data as $message) {
                    /* initialize css class for each alert box */
                    $this->options['class'] = $this->alertTypes[$type] . $appendCss;
64

65 66
                    /* assign unique id to each alert box */
                    $this->options['id'] = $this->getId() . '-' . $type;
67

68 69 70 71 72 73
                    echo \yii\bootstrap\Alert::widget([
                        'body' => $message,
                        'closeButton' => $this->closeButton,
                        'options' => $this->options,
                    ]);
                }
74

75 76 77 78
                $session->removeFlash($type);
            }
        }
    }
Alexander Makarov committed
79
}