|
| 1 | +<?php |
| 2 | +namespace app\widgets; |
| 3 | + |
| 4 | +use Yii; |
| 5 | + |
| 6 | +/** |
| 7 | + * Alert widget renders a message from session flash. All flash messages are displayed |
| 8 | + * in the sequence they were assigned using setFlash. You can set message as following: |
| 9 | + * |
| 10 | + * ```php |
| 11 | + * Yii::$app->session->setFlash('error', 'This is the message'); |
| 12 | + * Yii::$app->session->setFlash('success', 'This is the message'); |
| 13 | + * Yii::$app->session->setFlash('info', 'This is the message'); |
| 14 | + * ``` |
| 15 | + * |
| 16 | + * Multiple messages could be set as follows: |
| 17 | + * |
| 18 | + * ```php |
| 19 | + * Yii::$app->session->setFlash('error', ['Error 1', 'Error 2']); |
| 20 | + * ``` |
| 21 | + * |
| 22 | + * @author Kartik Visweswaran <kartikv2@gmail.com> |
| 23 | + * @author Alexander Makarov <sam@rmcreative.ru> |
| 24 | + */ |
| 25 | +class Alert extends \yii\bootstrap\Widget |
| 26 | +{ |
| 27 | + /** |
| 28 | + * @var array the alert types configuration for the flash messages. |
| 29 | + * This array is setup as $key => $value, where: |
| 30 | + * - $key is the name of the session flash variable |
| 31 | + * - $value is the bootstrap alert type (i.e. danger, success, info, warning) |
| 32 | + */ |
| 33 | + public $alertTypes = [ |
| 34 | + 'error' => 'alert-danger', |
| 35 | + 'danger' => 'alert-danger', |
| 36 | + 'success' => 'alert-success', |
| 37 | + 'info' => 'alert-info', |
| 38 | + 'warning' => 'alert-warning' |
| 39 | + ]; |
| 40 | + /** |
| 41 | + * @var array the options for rendering the close button tag. |
| 42 | + */ |
| 43 | + public $closeButton = []; |
| 44 | + |
| 45 | + |
| 46 | + public function init() |
| 47 | + { |
| 48 | + parent::init(); |
| 49 | + |
| 50 | + $session = Yii::$app->session; |
| 51 | + $flashes = $session->getAllFlashes(); |
| 52 | + $appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : ''; |
| 53 | + |
| 54 | + foreach ($flashes as $type => $data) { |
| 55 | + if (isset($this->alertTypes[$type])) { |
| 56 | + $data = (array) $data; |
| 57 | + foreach ($data as $i => $message) { |
| 58 | + /* initialize css class for each alert box */ |
| 59 | + $this->options['class'] = $this->alertTypes[$type] . $appendCss; |
| 60 | + |
| 61 | + /* assign unique id to each alert box */ |
| 62 | + $this->options['id'] = $this->getId() . '-' . $type . '-' . $i; |
| 63 | + |
| 64 | + echo \yii\bootstrap\Alert::widget([ |
| 65 | + 'body' => $message, |
| 66 | + 'closeButton' => $this->closeButton, |
| 67 | + 'options' => $this->options, |
| 68 | + ]); |
| 69 | + } |
| 70 | + |
| 71 | + $session->removeFlash($type); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments