Alert.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace app\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\bootstrap4\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. $appendClass = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
  50. foreach (array_keys($this->alertTypes) as $type) {
  51. $flash = $session->getFlash($type);
  52. foreach ((array) $flash as $i => $message) {
  53. echo \yii\bootstrap4\Alert::widget([
  54. 'body' => $message,
  55. 'closeButton' => $this->closeButton,
  56. 'options' => array_merge($this->options, [
  57. 'id' => $this->getId() . '-' . $type . '-' . $i,
  58. 'class' => $this->alertTypes[$type] . $appendClass,
  59. ]),
  60. ]);
  61. }
  62. $session->removeFlash($type);
  63. }
  64. }
  65. }