forked from 2amigos/yii2-bootstrap-form-helpers-library
/
InputWidget.php
95 lines (82 loc) · 2.67 KB
/
InputWidget.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
<?php
/**
* @copyright Copyright (c) 2013 2amigOS! Consulting Group LLC
* @link http://2amigos.us
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
namespace dosamigos\formhelpers;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
/**
* \dosamigos\formhelpers\Widget is the base class for all Bootstrap Form Helpers.
*
* @author Antonio Ramirez <amigo.cobos@gmail.com>
* @link http://www.ramirezcobos.com/
* @link http://www.2amigos.us/
* @package dosamigos\formhelpers
*/
class InputWidget extends \yii\widgets\InputWidget
{
/**
* @var array the options for the Bootstrap FormHelper plugin.
*/
public $clientOptions = [];
/**
* @var array the event handlers for the underlying Bootstrap FormHelper input JS plugin.
*/
public $clientEvents = [];
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->options = ArrayHelper::merge($this->asDataAttributes($this->clientOptions), $this->options);
$this->clientOptions = false;
if ($this->hasModel()) {
$this->options['data-name'] = Html::getInputName($this->model, $this->attribute);
$this->options['data-value'] = Html::getAttributeValue($this->model, $this->attribute);
} else {
$this->options['data-name'] = $this->name;
$this->options['data-value'] = $this->value;
}
}
/**
* Converts client options to HTML5 data- attributes.
* @param array $options the options to convert
* @return array
*/
protected function asDataAttributes($options)
{
$data = [];
foreach ($options as $key => $value) {
$data["data-$key"] = $value;
}
return $data;
}
/**
* Registers a specific Bootstrap plugin and the related events
* @param string $name the name of the Bootstrap plugin
* @return BootstrapFormHelpersAsset
*/
protected function registerPlugin($name)
{
$view = $this->getView();
$bundle = BootstrapFormHelpersAsset::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);
}
if (!empty($this->clientEvents)) {
$js = [];
foreach ($this->clientEvents as $event => $handler) {
$js[] = "jQuery('#$id').on('$event', $handler);";
}
$view->registerJs(implode("\n", $js));
}
return $bundle;
}
}