Alert.php 1.88 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>
19
 * @author Alexander Makarov <sam@rmcerative.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
		'error'   => 'danger',
		'danger'  => 'danger',
		'success' => 'success',
		'info'    => 'info',
34 35
		'warning' => 'warning'
	];
36
	
37 38 39
	/**
	 * @var array the options for rendering the close button tag.
	 */
40
	public $closeButton = [];
41
	
42 43
	public function init()
	{
44 45
		parent::init();

46
		$session = \Yii::$app->getSession();
47 48
		$flashes = $session->getAllFlashes();
		$appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
49
		
50
		foreach ($flashes as $type => $message) {
Kartik Visweswaran committed
51
			/* initialize css class for each alert box */
52
			$this->options['class'] = 'alert-' . $this->alertTypes[$type] . $appendCss;
53

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

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

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