1 <?php
2 3 4 5 6 7 8 9 10 11 12 13
14 Yii::import('bootstrap.helpers.TbArray');
15 Yii::import('bootstrap.helpers.TbHtml');
16
17 class WhSwitch extends CInputWidget
18 {
19 20 21
22 public $inputType = 'checkbox';
23
24 25 26
27 public $size = 'small';
28
29 30 31
32 public $onColor = 'primary';
33
34 35 36
37 public $offColor = 'warning';
38
39 40 41
42 public $animated = true;
43
44 45 46
47 public $onLabel;
48
49 50 51
52 public $offLabel;
53
54 55 56
57 public $textLabel;
58
59 60 61
62 public $events = array();
63
64 65 66
67 public $debugMode = false;
68
69
70 71 72 73
74 public function init()
75 {
76 if (!in_array($this->inputType, array('radio', 'checkbox'))) {
77 throw new CException(Yii::t('zii', '"inputType" attribute must be of type "radio" or "checkbox"'));
78 }
79 if (!in_array($this->size, array('mini', 'small', 'normal', 'large'))) {
80 throw new CException(Yii::t('zii', 'Unknown value for attribute "size".'));
81 }
82 $this->attachBehavior('ywplugin', array('class' => 'yiiwheels.behaviors.WhPlugin'));
83
84 if (!$this->animated) {
85 $this->htmlOptions['data-animate'] = 'false';
86 }
87 $this->htmlOptions['data-on-text'] = $this->onLabel;
88 $this->htmlOptions['data-off-text'] = $this->offLabel;
89 $this->htmlOptions['data-label-text'] = $this->textLabel;
90 $this->htmlOptions['data-on-color'] = $this->onColor;
91 $this->htmlOptions['data-off-color'] = $this->offColor;
92 $this->htmlOptions['data-size'] = $this->size;
93 }
94
95 96 97
98 public function run()
99 {
100 $this->renderField();
101 $this->registerClientScript();
102 }
103
104 105 106
107 public function renderField()
108 {
109 list($name, $id) = $this->resolveNameID();
110
111 TbArray::defaultValue('id', $id, $this->htmlOptions);
112 TbArray::defaultValue('name', $name, $this->htmlOptions);
113
114 if ($this->hasModel()) {
115 echo $this->inputType == 'radio'
116 ? CHtml::activeRadioButton($this->model, $this->attribute, $this->htmlOptions)
117 : CHtml::activeCheckBox($this->model, $this->attribute, $this->htmlOptions);
118 } else {
119 echo $this->inputType == 'radio'
120 ? CHtml::radioButton($this->name, $this->value, $this->htmlOptions)
121 : CHtml::checkBox($this->name, $this->value, $this->htmlOptions);
122 }
123 }
124
125 126 127 128
129 public function registerClientScript()
130 {
131
132 $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets';
133 $assetsUrl = $this->getAssetsUrl($path);
134 $id = TbArray::getValue('id', $this->htmlOptions);
135
136
137 $cs = Yii::app()->getClientScript();
138
139 $min = $this->debugMode
140 ? '.min'
141 : '';
142
143 $cs->registerCssFile($assetsUrl . '/css/bootstrap-switch.css');
144 $cs->registerScriptFile($assetsUrl . '/js/bootstrap-switch' . $min . '.js', CClientScript::POS_END);
145 $selector = '#' . $id;
146
147 $this->getApi()->registerPlugin('bootstrapSwitch', $selector);
148 $this->getApi()->registerEvents($selector, $this->events);
149
150 }
151 }