-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathChosenSelect.php
93 lines (81 loc) · 2.2 KB
/
ChosenSelect.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
<?php
namespace yii2mod\chosen;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;
/**
* Yii2 wrapper for Chosen plugin {@link http://harvesthq.github.io/chosen)
*
* @author Igor Chepurnoy <chepurnoi.igor@gmail.com>
*
* @since 1.0
*/
class ChosenSelect extends InputWidget
{
/**
* @var array select items
*/
public $items = [];
/**
* @var array plugin options. By default it contains ['width' => '100%']
*/
public $pluginOptions = [];
/**
* @var bool Enable placeholder in Chosen plugin
*/
public $withPlaceHolder = true;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->withPlaceHolder) {
if (!empty($this->options['prompt'])) {
$this->options['data-placeholder'] = $this->options['prompt'];
unset($this->options['prompt']);
}
if (empty($this->options['data-placeholder'])) {
$this->options['data-placeholder'] = 'Please select...';
}
$this->items = ['' => ''] + $this->items;
}
if (empty($this->options['multiple'])) {
$this->options['multiple'] = false;
}
if (empty($this->pluginOptions['width'])) {
$this->pluginOptions['width'] = '100%';
}
}
/**
* @inheritdoc
*/
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);
}
$this->registerAssets();
}
/**
* Register client assets
*/
protected function registerAssets()
{
$view = $this->getView();
ChosenSelectAsset::register($view);
$js = '$("#' . $this->options['id'] . '").chosen(' . $this->getPluginOptions() . ');';
$view->registerJs($js, $view::POS_END);
}
/**
* Return plugin options in json format
*
* @return string
*/
public function getPluginOptions()
{
return Json::encode($this->pluginOptions);
}
}