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.

76 lines
2.3 KiB

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