選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

80 行
2.5KB

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