【发布时间】:2015-10-13 07:47:50
【问题描述】:
我有一个表,其中列for_date 按整数类型保存在数据库中。
为了以 DateTime 格式显示for_date,我使用了带有代码的 ActiveForm:
<?= $form->field($model, 'for_date')->textInput([
'class' => 'form-control datepicker',
'value' => $model->for_date ? date(Yii::$app->params['dateFormat'], $model->for_date) : date(Yii::$app->params['dateFormat'], time()),
'placeholder' => 'Time'])
->label('Attendance Date') ?>
但是当我创建和保存时,Yii 通知了This field must be integer
在模型文件中,我在验证之前有以下两个函数需要转换,但它仍然是错误的。
public function beforeValidate(){
if(!is_int($this->for_date)){
$this->for_date = strtotime($this->for_date);
$this->for_date = date('d/M/Y', $this->for_date);
}
return parent::beforeValidate();
}
public function afterFind(){
$this->for_date = \Yii::t('app', Yii::$app->formatter->asDate($this->for_date));
$this->for_date = date('d/M/Y', $this->for_date);
return parent::afterFind();
}
我怎样才能正确地将整数保存到数据库中?
【问题讨论】:
-
我会将其保留为模型中的
int并使用getter 和setter。您收到的错误消息很可能来自您的规则设置。所以你可以在那里改变你的验证器。
标签: php datetime yii2 yii2-validation