Alert.php 1.95 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
 *
 * - \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');
 *
18
 * @author Kartik Visweswaran <kartikv2@gmail.com>
Bohdan Shulha committed
19
 * @author Alexander Makarov <sam@rmcreative.ru>
20
 */
Kartik Visweswaran committed
21
class Alert extends \yii\bootstrap\Widget
22
{
23
	/**
24 25 26 27
	 * @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)
28
	 */
29
	public $alertTypes = [
30 31 32 33 34
		'error'   => 'alert-danger',
		'danger'  => 'alert-danger',
		'success' => 'alert-success',
		'info'    => 'alert-info',
		'warning' => 'alert-warning'
35
	];
36

37 38 39
	/**
	 * @var array the options for rendering the close button tag.
	 */
40
	public $closeButton = [];
41

42 43 44
	public function init()
	{
		parent::init();
45

46 47 48
		$session = \Yii::$app->getSession();
		$flashes = $session->getAllFlashes();
		$appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
49

50 51 52 53
		foreach ($flashes as $type => $message) {
			if (isset($this->alertTypes[$type])) {
				/* initialize css class for each alert box */
				$this->options['class'] = $this->alertTypes[$type] . $appendCss;
54

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

58
				echo \yii\bootstrap\Alert::widget([
Jason Ragsdale committed
59 60 61
					'body' => $message,
					'closeButton' => $this->closeButton,
					'options' => $this->options,
62
				]);
63

64 65
				$session->removeFlash($type);
			}
66 67
		}
	}
Alexander Makarov committed
68
}