1 <?php
2 3 4 5 6 7 8 9 10
11 Yii::import('bootstrap.helpers.TbArray');
12
13 class WhSelect2 extends CInputWidget
14 {
15
16 17 18
19 public $data = array();
20
21 22 23
24 public $events = array();
25
26 27 28
29 public $asDropDownList = true;
30
31 32 33
34 public $language;
35
36 37 38
39 public $pluginOptions;
40
41 42 43
44 public function init()
45 {
46 if (empty($this->data) && $this->asDropDownList === true) {
47 throw new CException(Yii::t('zii', '"data" attribute cannot be blank'));
48 }
49
50 $this->attachBehavior('ywplugin', array('class' => 'yiiwheels.behaviors.WhPlugin'));
51 }
52
53 54 55
56 public function run()
57 {
58 $this->renderField();
59 $this->registerClientScript();
60 }
61
62 63 64
65 public function renderField()
66 {
67 list($name, $id) = $this->resolveNameID();
68
69 TbArray::defaultValue('id', $id, $this->htmlOptions);
70 TbArray::defaultValue('name', $name, $this->htmlOptions);
71
72 if ($this->hasModel()) {
73 echo $this->asDropDownList ?
74 TbHtml::activeDropDownList($this->model, $this->attribute, $this->data, $this->htmlOptions) :
75 TbHtml::activeHiddenField($this->model, $this->attribute);
76
77 } else {
78 echo $this->asDropDownList ?
79 TbHtml::dropDownList($this->name, $this->value, $this->data, $this->htmlOptions) :
80 TbHtml::hiddenField($this->name, $this->value);
81 }
82 }
83
84 85 86 87
88 public function registerClientScript()
89 {
90
91 $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets';
92 $assetsUrl = $this->getAssetsUrl($path);
93
94
95 $cs = Yii::app()->getClientScript();
96
97 $cs->registerCssFile($assetsUrl . '/css/select2.css');
98 $cs->registerScriptFile($assetsUrl . '/js/select2.js');
99
100
101 if ($this->language) {
102 $cs->registerScriptFile(
103 $assetsUrl . '/js/locale/select2_locale_' . $this->language . '.js',
104 CClientScript::POS_END
105 );
106 }
107
108
109 $selector = '#' . TbArray::getValue('id', $this->htmlOptions, $this->getId());
110
111 $this->getApi()->registerPlugin('select2', $selector, $this->pluginOptions, CClientScript::POS_READY);
112 $this->getApi()->registerEvents($selector, $this->events, CClientScript::POS_READY);
113 }
114 }
115