/
Select2.php
101 lines (88 loc) · 2.35 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace maddoger\widgets;
use Yii;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\JsExpression;
use yii\widgets\InputWidget;
/**
* Select2 Widget For Yii2
*
* @author Vitaliy Syrchikov <maddoger@gmail.com>
*/
class Select2 extends InputWidget
{
/**
* @var array
*/
public $items;
/**
* @var array plugin options
*/
public $clientOptions = [];
/**
* @var bool
*/
public $registerBootstrapAsset = true;
/**
* @var string[] Events
*/
public $clientEvents;
/**
* @inheritdoc
* @throws \yii\base\InvalidConfigException
*/
public function init()
{
parent::init();
if (!isset($this->options['class'])) {
$this->options['class'] = 'form-control';
}
if (!isset($this->options['id'])) {
$this->options['id'] = $this->getId();
}
}
/**
* @inheritdoc
*/
public function run()
{
$this->registerClientScript();
if ($this->hasModel()) {
if ($this->items) {
return Html::activeDropDownList($this->model, $this->attribute, $this->items, $this->options);
} else {
return Html::activeTextInput($this->model, $this->attribute, $this->options);
}
} else {
if ($this->items) {
return Html::dropDownList($this->name, $this->value, $this->items, $this->options);
} else {
return Html::textInput($this->name, $this->value, $this->options);
}
}
}
/**
* @inheritdoc
*/
protected function registerClientScript()
{
$clientOptions = Json::encode($this->clientOptions);
$selector = $this->options['id'];
$view = $this->getView();
if ($this->registerBootstrapAsset === true) {
Select2BootstrapAsset::register($view);
} else {
Select2Asset::register($view);
}
$this->getView()->registerJs("$('#{$selector}').select2($clientOptions);");
if (!empty($this->clientEvents)) {
$js = [];
foreach ($this->clientEvents as $event => $handler) {
$js[] = "$('#{$selector}').on('{$event}', {$handler});";
}
$js = implode("\n", $js);
$view->registerJs($js);
}
}
}