Alert.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace backend\widgets;
  3. use Yii;
  4. use common\helpers\StringHelper;
  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 \yii\bootstrap4\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. $data = (array) $flash;
  57. foreach ($data as $i => $message) {
  58. /* initialize css class for each alert box */
  59. $this->options['class'] = $this->alertTypes[$type] . $appendClass;
  60. /* assign unique id to each alert box */
  61. $this->options['id'] = $this->getId() . '-' . $type . '-' . $i;
  62. $message = StringHelper::replace("'", '"', $message);
  63. $message = StringHelper::replace("\r", '', $message);
  64. $message = StringHelper::replace("\n", '', $message);
  65. // 调用函数
  66. $this->view->registerJs(<<<Js
  67. toastr.{$type}('{$message}')
  68. Js
  69. );
  70. }
  71. $session->removeFlash($type);
  72. }
  73. }
  74. }
粤ICP备19079148号