You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.2 KiB

8 months ago
  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\bootstrap5\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\bootstrap5\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. }