Alert.php 1.53 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;

use yii\helpers\Html;
11 12
use yii\bootstrap\Widget;
use yii\bootstrap\Alert as BsAlert;
13 14

/**
15 16
 * 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:
17 18 19 20 21 22
 *
 * - \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');
 *
 * @author Alexander Makarov <sam@rmcerative.ru>
23
 * @author Kartik Visweswaran <kartikv2@gmail.com>
24
 */
25
class Alert extends Widget
26
{
27 28 29
	private $_doNotRender = true;
	public $allowedTypes = ['error', 'danger', 'success', 'info', 'warning'];
	
30 31
	public function init()
	{
32 33 34 35 36 37 38
		$this->_doNotRender = true;
		$session = \Yii::$app->getSession();
		$flashes = $session->getAllFlashes();
		foreach ($flashes as $type => $message) {
			if (in_array($type, $this->allowedTypes)) {
				$class = ($type === 'error') ? 'alert-danger' : 'alert-' . $type;
				Html::addCssClass($this->options, $class);
Kartik Visweswaran committed
39
				echo BsAlert::widget([
40 41
					'body' => $message,
					'options' => $this->options
Kartik Visweswaran committed
42
				]);	
43 44 45 46 47 48 49
				$session->removeFlash($type);
				$this->_doNotRender = false;
			}
		}
		
		if (!$this->_doNotRender) {
			parent::init();
50 51
		}
	}
Alexander Makarov committed
52 53 54

	public function run()
	{
Alexander Makarov committed
55
		if (!$this->_doNotRender) {
Alexander Makarov committed
56 57 58 59
			parent::run();
		}
	}
}