diff --git a/README.md b/README.md index 7c48d74..6614a3e 100644 --- a/README.md +++ b/README.md @@ -103,3 +103,13 @@ Standalone widget for date only: 'phpDatetimeFormat' => 'yyyy-MM-dd', ]) ; ?> ``` +Add custom JS events: +```php + [ + 'dp.change' => 'function(e){ + console.log('dp.change'); + }', + ], +]) ; ?> +``` diff --git a/src/DateTimeWidget.php b/src/DateTimeWidget.php index 1a16f39..82990d8 100755 --- a/src/DateTimeWidget.php +++ b/src/DateTimeWidget.php @@ -21,6 +21,10 @@ class DateTimeWidget extends InputWidget * @link http://eonasdan.github.io/bootstrap-datetimepicker/#options */ public $clientOptions = []; + /** + * @var array the event handlers for the underlying bootstrap-datetimepicker plugin. + */ + public $clientEvents = []; /** * @var array */ @@ -102,12 +106,27 @@ public function init() ? $this->options['value'] : Yii::$app->formatter->asDatetime($value, $this->phpDatetimeFormat); } - DateTimeAsset::register($this->getView()); - $clientOptions = Json::encode($this->clientOptions); + if (!isset($this->containerOptions['id'])) { $this->containerOptions['id'] = $this->getId(); } - $this->view->registerJs("$('#{$this->containerOptions['id']}').datetimepicker({$clientOptions})"); + + $this->registerJs(); + } + + protected function registerJs() + { + DateTimeAsset::register($this->getView()); + $clientOptions = Json::encode($this->clientOptions); + $this->getView()->registerJs("$('#{$this->containerOptions['id']}').datetimepicker({$clientOptions})"); + + if (!empty($this->clientEvents)) { + $js = []; + foreach ($this->clientEvents as $event => $handler) { + $js[] = "jQuery('#{$this->containerOptions['id']}').on('$event', $handler);"; + } + $this->getView()->registerJs(implode("\n", $js)); + } } /**