diff --git a/views/layouts/main.php b/views/layouts/main.php index d0e3b0e..920e60d 100644 --- a/views/layouts/main.php +++ b/views/layouts/main.php @@ -3,6 +3,7 @@ /* @var $this \yii\web\View */ /* @var $content string */ +use app\widgets\Alert; use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; @@ -61,6 +62,7 @@ AppAsset::register($this); isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ]) ?> + diff --git a/widgets/Alert.php b/widgets/Alert.php new file mode 100644 index 0000000..b19d040 --- /dev/null +++ b/widgets/Alert.php @@ -0,0 +1,75 @@ +session->setFlash('error', 'This is the message'); + * Yii::$app->session->setFlash('success', 'This is the message'); + * Yii::$app->session->setFlash('info', 'This is the message'); + * ``` + * + * Multiple messages could be set as follows: + * + * ```php + * Yii::$app->session->setFlash('error', ['Error 1', 'Error 2']); + * ``` + * + * @author Kartik Visweswaran + * @author Alexander Makarov + */ +class Alert extends \yii\bootstrap\Widget +{ + /** + * @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' + ]; + /** + * @var array the options for rendering the close button tag. + */ + public $closeButton = []; + + + public function init() + { + parent::init(); + + $session = Yii::$app->session; + $flashes = $session->getAllFlashes(); + $appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : ''; + + foreach ($flashes as $type => $data) { + if (isset($this->alertTypes[$type])) { + $data = (array) $data; + foreach ($data as $i => $message) { + /* initialize css class for each alert box */ + $this->options['class'] = $this->alertTypes[$type] . $appendCss; + + /* assign unique id to each alert box */ + $this->options['id'] = $this->getId() . '-' . $type . '-' . $i; + + echo \yii\bootstrap\Alert::widget([ + 'body' => $message, + 'closeButton' => $this->closeButton, + 'options' => $this->options, + ]); + } + + $session->removeFlash($type); + } + } + } +}