-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSelect2.php
69 lines (59 loc) · 1.99 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
<?php
namespace yii\select2;
use yii\helpers\Html;
use yii\web\AssetBundle;
use yii\helpers\ArrayHelper;
use yii\widgets\InputWidget;
class Select2 extends InputWidget {
public $items = [];
public $clientOptions = [];
private $_assetBundle;
public function init()
{
if ($this->hasModel()) {
$this->options['id'] = Html::getInputId($this->model, $this->attribute);
} else {
$this->options['id'] = $this->getId();
}
$this->registerAssetBundle();
$this->registerLocate();
$this->registerScript();
}
public function run()
{
if ($this->hasModel()) {
echo Html::activeDropDownList($this->model, $this->attribute, $this->items, $this->options);
} else {
echo Html::dropDownList($this->name, $this->value, $this->items, $this->options);
}
}
public function registerAssetBundle()
{
$this->_assetBundle = Select2Asset::register($this->getView());
Select2BootstrapAsset::register($this->getView());
}
public function registerLocate()
{
$locate = ArrayHelper::getValue($this->clientOptions, 'locales', FALSE);
if ($locate) {
$locateAsset = 'locates/select2_locale_' . $locate . '.js';
if (file_exists(Yii::getAlias($this->getAssetBundle()->sourcePath . '/' . $locateAsset))) {
$this->getAssetBundle()->js[] = $locateAsset;
} else {
ArrayHelper::remove($this->clientOptions, 'locales');
}
}
}
public function registerScript()
{
$clientOptions = (count($this->clientOptions)) ? Json::encode($this->clientOptions) : '';
$this->getView()->registerJs("jQuery('#{$this->options['id']}').select2({$clientOptions});");
}
public function getAssetBundle()
{
if (!($this->_assetBundle instanceof AssetBundle)) {
$this->registerAssetBundle();
}
return $this->_assetBundle;
}
}