Yii2 官方未內建日期選擇器,社區主流方案是 2amigos/yii2-date-picker-widget,基於 Bootstrap Datepicker 封裝,支援 Widget 與 ActiveForm 兩種調用方式。本文記錄安裝、配置與常用選項。
composer require "2amigos/yii2-date-picker-widget" "*"
use dosamigos\datepicker\DatePicker;
<?= DatePicker::widget([
'model' => $model,
'attribute' => 'date',
'template' => '{addon}{input}', // 帶圖標加載項
'clientOptions' => [
'autoclose' => true, // 選擇後自動關閉
'format' => 'dd-M-yyyy', // 顯示格式
'language' => 'zh-CN', // 中文語言包
'todayHighlight' => true, // 高亮今天
],
]) ?>
<?= $form->field($model, 'date')->widget(DatePicker::className(), [
'inline' => true, // 內聯模式(直接展開)
'template' => '<div class="well well-sm" style="background:#fff;width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-M-yyyy',
'language' => 'zh-CN',
],
]) ?>
| 參數 | 類型 | 默認 | 說明 |
|---|---|---|---|
| format | string | mm/dd/yyyy | 日期顯示格式(yyyy-mm-dd, dd-M-yy 等) |
| autoclose | bool | false | 選擇日期後自動關閉面板 |
| language | string | en | 語言代碼(需對應語言包文件) |
| todayHighlight | bool | false | 高亮當前日期 |
| startDate / endDate | string|Date | — | 可選範圍限制 |
| daysOfWeekDisabled | array | [] | 禁用星期幾(0=周日) |
| calendarWeeks | bool | false | 顯示周數 |
| clearBtn | bool | false | 顯示清除按鈕 |
| orientation | string | auto | 面板定位:top/left/right/bottom/auto |
若需中文,確保資源文件存在:@vendor/2amigos/yii2-date-picker-widget/src/assets/js/locales/bootstrap-datepicker.zh-CN.min.js,並設置 'language' => 'zh-CN'。
'template' => '{label}{input}{addon}{error}',
'options' => ['class' => 'form-control', 'placeholder' => '請選擇日期'],
'clientEvents' => [
'changeDate' => 'function(e) { console.log("選中: " + e.format()); }',
'show' => 'function(e) { console.log("面板打開"); }',
'hide' => 'function(e) { console.log("面板關閉"); }',
],
幾行代碼即可獲得專業級日期選擇體驗,配合 ActiveForm 驗證規則 ['date', 'date', 'format' => 'php:Y-m-d'] 實現前後端雙重校驗。