Alert.php 2.5 KB

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