Alert.php 2.3 KB

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