Fra*_*cis 5 php datetime yii2 yii2-validation
我有一个表for_date在数据库中按类型整数保存列.为了for_date使用DateTime格式显示,我使用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') ?>
Run Code Online (Sandbox Code Playgroud)
但是,当我创造和保存时,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();
}
Run Code Online (Sandbox Code Playgroud)
如何使用整数保存到数据库中?
我找到了解决方案。在模型搜索(我的情况是AttendanceSearch.php)中,查找规则功能并for_date从线必须移动integer到线以下safe
我的代码:
public function rules()
{
return [
[['id', 'user_id', 'project_id', 'commit_time', 'workload_type'], 'integer'],
[['comment', 'for_date'], 'safe'],
];
}
Run Code Online (Sandbox Code Playgroud)