daterangepicker 还是比较强大的,既能选择时间段,也能选择作为单个日期时间选择器使用,最重要的是可以选择秒,因为业务需要,有的地方需要选择到秒
http://www.daterangepicker.com/#options
首先,我使用yii2-bootstrap,所以input widget是继承自yii\bootstrap\InputWidget
daterangepicker一些参数可参考官网,我这里使用到了
singleDatePicker: 单个选择器
autoUpdateInput: 不自动赋值表单,因为我初始值需要为空。
locale: 本地化
timePicker: 支持时间选择
timePicker24Hour: 按24小时制选择
timePickerSeconds: 支持秒选择
daterangepicker是有默认值的,要让默认值为空,需要设置1个参数:
autoUpdateInput: 不自动赋值表单,因为我初始值需要为空。
但是设置了这个点击确认按钮是不会把值提交给input,所以需要手动提交
可参考官网的Input Initially Empty例子
代码:
use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\bootstrap\InputWidget;
use yii\web\AssetBundle;
class DatetimePicker extends InputWidget {
public $pluginOptions = [];
public function init()
{
parent::init();
}
public function run()
{
$view = $this->getView();
$input = Html::input('text', $this->name, $this->value, $this->options);
if ($this->hasModel()) {
$input = Html::activeInput('text', $this->model, $this->attribute, $this->options);
}
echo $input;
DatetimeAsset::register($view);
$this->clientOptions = array_replace_recursive([
'singleDatePicker' => true,
'autoUpdateInput' => false,
'locale' => [
'format' => 'YYYY-MM-DD HH:mm:ss',
'applyLabel' => Yii::t('backend', 'sure'),
'cancelLabel' => Yii::t('backend', 'clear_all'),
'daysOfWeek' => [
Yii::t('backend', 'week7'),
Yii::t('backend', 'week1'),
Yii::t('backend', 'week2'),
Yii::t('backend', 'week3'),
Yii::t('backend', 'week4'),
Yii::t('backend', 'week5'),
Yii::t('backend', 'week6'),
],
'monthNames' => [
Yii::t('backend', 'month1'),
Yii::t('backend', 'month2'),
Yii::t('backend', 'month3'),
Yii::t('backend', 'month4'),
Yii::t('backend', 'month5'),
Yii::t('backend', 'month6'),
Yii::t('backend', 'month7'),
Yii::t('backend', 'month8'),
Yii::t('backend', 'month9'),
Yii::t('backend', 'month10'),
Yii::t('backend', 'month11'),
Yii::t('backend', 'month12')],
]
], $this->pluginOptions);
$js = "jQuery('#" . $this->options['id'] . "').on('apply.daterangepicker', function(ev, picker) {jQuery(this).val(picker.startDate.format('YYYY-MM-DD HH:mm:ss'))});";
$js .= "jQuery('#" . $this->options['id'] . "').on('cancel.daterangepicker', function(ev, picker) {jQuery(this).val('')});";
$this->registerPlugin('daterangepicker');
$view->registerJs($js);
}
}
class DatetimeAsset extends AssetBundle
{
public $js = [
'plugins/moment/moment.min.js',
'plugins/daterangepicker/daterangepicker.js',
];
public $css = [
'plugins/daterangepicker/daterangepicker.css',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
public function init()
{
parent::init();
}
}
需要说明的是,代码里的jquery不要使用$, 因为$是php的变量标识,同时双引号是支持变量的,所以如果使用$会报错。
使用:
use common\widgets\DatetimePicker;
$form->field($model, 'brithday')->widget(DatetimePicker::classname(), [
'options' => ['placeholder' => Yii::t('backend', 'brithday'), 'autocomplete' => 'off'],
'pluginOptions' => [
'timePicker' => true,
'timePicker24Hour' => true,
'timePickerSeconds' => true,
]
]);