1 <?php
2 3 4 5 6 7 8
9
10 11 12 13
14 class TbAlert extends CWidget
15 {
16
17 const TYPE_SUCCESS = 'success';
18 const TYPE_INFO = 'info';
19 const TYPE_WARNING = 'warning';
20 const TYPE_ERROR = 'error';
21 const TYPE_DANGER = 'danger';
22
23 24 25
26 public $alerts;
27 28 29
30 public $closeText = '×';
31 32 33
34 public $block = true;
35 36 37
38 public $fade = true;
39 40 41
42 public $events = array();
43 44 45
46 public $htmlOptions = array();
47
48 49 50
51 public function init()
52 {
53 if (!isset($this->htmlOptions['id']))
54 $this->htmlOptions['id'] = $this->getId();
55
56 if (is_string($this->alerts))
57 $this->alerts = array($this->alerts);
58
59
60 if (!isset($this->alerts))
61 $this->alerts = array(self::TYPE_SUCCESS, self::TYPE_INFO, self::TYPE_WARNING, self::TYPE_ERROR, self::TYPE_DANGER);
62 }
63
64 65 66
67 public function run()
68 {
69 $id = $this->htmlOptions['id'];
70
71 echo CHtml::openTag('div', $this->htmlOptions);
72
73 foreach ($this->alerts as $type => $alert)
74 {
75 if (is_string($alert))
76 {
77 $type = $alert;
78 $alert = array();
79 }
80
81 if (isset($alert['visible']) && $alert['visible'] === false)
82 continue;
83
84 if (Yii::app()->user->hasFlash($type))
85 {
86 $classes = array('alert in');
87
88 if (!isset($alert['block']))
89 $alert['block'] = $this->block;
90
91 if ($alert['block'] === true)
92 $classes[] = 'alert-block';
93
94 if (!isset($alert['fade']))
95 $alert['fade'] = $this->fade;
96
97 if ($alert['fade'] === true)
98 $classes[] = 'fade';
99
100 $validTypes = array(self::TYPE_SUCCESS, self::TYPE_INFO, self::TYPE_WARNING, self::TYPE_ERROR, self::TYPE_DANGER);
101
102 if (in_array($type, $validTypes))
103 $classes[] = 'alert-'.$type;
104
105 if (!isset($alert['htmlOptions']))
106 $alert['htmlOptions'] = array();
107
108 $classes = implode(' ', $classes);
109 if (isset($alert['htmlOptions']['class']))
110 $alert['htmlOptions']['class'] .= ' '.$classes;
111 else
112 $alert['htmlOptions']['class'] = $classes;
113
114 echo CHtml::openTag('div', $alert['htmlOptions']);
115
116 if ($this->closeText !== false && !isset($alert['closeText']))
117 $alert['closeText'] = $this->closeText;
118
119 if ($alert['closeText'] !== false)
120 echo '<a class="close" data-dismiss="alert">'.$alert['closeText'].'</a>';
121
122 echo Yii::app()->user->getFlash($type);
123
124 echo '</div>';
125 }
126 }
127
128 echo '</div>';
129
130 $selector = "#{$id} .alert";
131
132
133 $cs = Yii::app()->getClientScript();
134 $cs->registerScript(__CLASS__.'#'.$id, "jQuery('{$selector}').alert();");
135
136 foreach ($this->events as $name => $handler)
137 {
138 $handler = CJavaScript::encode($handler);
139 $cs->registerScript(__CLASS__.'#'.$id.'_'.$name, "jQuery('{$selector}').on('{$name}', {$handler});");
140 }
141 }
142 }
143