initSetting(); $this->registerAsset(); echo $this->renderHiddenInput(); echo $this->renderDatapickerInput(); } /** * 初始化小物件的配置 */ protected function initSetting() { //初始化日期格式 if (empty($this->format)) { $this->format = Yii::$app->formatter->dateFormat; } //关闭自动完成 $this->options["autocomplete"] = "off"; //生成一个picker input的 id $this->pickerInputId = $this->options['id'] . "_" . Yii::$app->security->generateRandomString(32); } /** * 注册js和css */ protected function registerAsset() { $view = $this->getView(); DatepickBootstrapAsset::register($view); $options = [ "format" => $this->convertDateFormat($this->format), "language" => "zh-CN" ]; $jsOptions = Json::encode($options); $js = <<< SCRIPT $('#{$this->pickerInputId}').datepicker({$jsOptions}).on('changeDate', function(e) { $('#{$this->options['id']}').val(String(e.date.getTime()).substring(0,10)); });; SCRIPT; $view->registerJs($js); } /** * 渲染一个用作保存Datepicker Unix时间错的hidden input * @return string */ protected function renderHiddenInput() { if ($this->hasModel()) { return Html::activeInput('hidden', $this->model, $this->attribute, $this->options); } return Html::input('hidden', $this->name, $this->value, $this->options); } /** * TODO:自动填充了今天为默认日期 * 渲染一个用作显示日期的字符格式 text input * @return string */ protected function renderDatapickerInput() { $value = ''; $options = $this->options; $options['id'] = $this->pickerInputId; if ($this->hasModel()) { $timestamp = ArrayHelper::getValue($this->model, $this->attribute); if (!empty($timestamp)) { $value = date($this->format, $timestamp); } } if (empty($timestamp) && $this->autoFill) { $timestamp = time(); $value = date($this->format, $timestamp); } return Html::input('text', $this->name, $value, $options); } /** * 转换php日期格式为bootstrap日期格式 * * TODO:没有弄清所有格式的转换,后续添加 * * @param string $format PHP日期格式字符串 * @return string */ protected static function convertDateFormat($format) { $conversions = [ 'd' => 'dd', 'm' => 'mm', 'Y' => 'yyyy', ]; return strtr($format, $conversions); } }