Yii2更新表单中StartYear与EndYear数据库读取显示异常问题
解决Yii2中JUI日期选择器更新时显示异常的问题
问题核心
更新操作时日期显示错误,原因在于:存储的月份名称(如June)无法直接被日期选择器识别为有效日期;视图代码冗余、重复初始化日期选择器导致冲突;EndYear的更新逻辑未处理已有值。
步骤1:修改模型层(Academicyear.php)
在模型中添加日期转换逻辑,自动处理字符串与DateTime对象的互转,让视图无需手动解析:
<?php namespace app\models; use yii\db\ActiveRecord; use DateTime; class Academicyear extends ActiveRecord { // ... 其他已有代码 ... public function afterFind() { parent::afterFind(); // 将数据库存储的"Month Year"字符串转为DateTime对象 if ($this->StartYear) { $this->StartYear = DateTime::createFromFormat('F Y', $this->StartYear); } if ($this->EndYear) { $this->EndYear = DateTime::createFromFormat('F Y', $this->EndYear); } } public function beforeSave($insert) { if (parent::beforeSave($insert)) { // 将DateTime对象转回"Month Year"字符串存储 if ($this->StartYear instanceof DateTime) { $this->StartYear = $this->StartYear->format('F Y'); } if ($this->EndYear instanceof DateTime) { $this->EndYear = $this->EndYear->format('F Y'); } return true; } return false; } }
步骤2:简化并修正视图层(_form.php)
去掉冗余的条件判断和重复初始化,统一配置日期选择器:
<?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; use yii\jui\DatePicker; /* @var $this yii\web\View */ /* @var $model app\models\Academicyear */ /* @var $form yii\widgets\ActiveForm */ ?> <style type="text/css"> .ui-datepicker-calendar { display: none; } </style> <?php $form = ActiveForm::begin()?> <div class="row"> <div class="col-sm-5"> <?= $form->field($model, 'StartYear')->widget(DatePicker::classname(), [ 'options' => ['class' => 'form-control', 'readOnly' => true], 'clientOptions' => [ 'changeMonth' => true, 'changeYear' => true, 'dateFormat' => 'MM yy', 'showButtonPanel' => true, // 关闭选择器时自动设置选中年月对应的日期 'onClose' => 'function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker("setDate", new Date(year, month, 1)); }' ] ]) ?> </div> </div> <div class="row"> <div class="col-sm-5"> <?= $form->field($model, 'EndYear')->widget(DatePicker::classname(), [ 'options' => ['class' => 'form-control', 'readOnly' => true], 'clientOptions' => [ 'changeMonth' => true, 'changeYear' => true, 'dateFormat' => 'MM yy', 'showButtonPanel' => true, 'onClose' => 'function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker("setDate", new Date(year, month, 1)); }' ] ]) ?> </div> </div> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?php ActiveForm::end(); ?>
关键说明
- 模型层转换:通过
DateTime::createFromFormat自动解析存储的月份年份字符串,转为标准日期对象后,日期选择器能直接识别并正确显示;保存时再转回原字符串格式,保证数据库存储不变。 - 视图层优化:移除重复的全局日期选择器初始化(避免与Widget生成的代码冲突),统一处理新增和更新场景,无需区分
isNewRecord。 - 选择器逻辑:保留
onClose事件确保选中年月后,输入框显示正确的MM yy格式,同时内部存储完整日期对象供模型转换。
内容的提问来源于stack exchange,提问作者Prashant
相关产品推荐
相关产品推荐

