-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSelect2.php
58 lines (48 loc) · 1.52 KB
/
Select2.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace yiicms\widgets;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;
class Select2 extends InputWidget
{
public $items = [];
/**
* @var array
* @see https://select2.github.io/options.html
*/
public $clientOptions = [];
public $clientEvents = [];
public function run()
{
$this->registerPlugin('select2');
Html::addCssClass($this->options, 'form-control');
if ($this->hasModel()) {
return Html::activeDropDownList($this->model, $this->attribute, $this->items, $this->options);
} else {
return Html::dropDownList($this->name, $this->value, $this->items, $this->options);
}
}
protected function registerPlugin($name)
{
$view = $this->getView();
Select2Asset::register($view);
$id = $this->options['id'];
if ($this->clientOptions !== false) {
$options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions);
$js = "jQuery('#$id').$name($options);";
$view->registerJs($js);
}
$this->registerClientEvents();
}
protected function registerClientEvents()
{
if (!empty($this->clientEvents)) {
$id = $this->options['id'];
$js = [];
foreach ($this->clientEvents as $event => $handler) {
$js[] = "jQuery('#$id').on('$event', $handler);";
}
$this->getView()->registerJs(implode("\n", $js));
}
}
}