Yii2 Convert from integer to datetime for display and save in integer database

I have a table with a for_date column stored as an integer in the database. To show for_date using the DateTime format, I used ActiveForm with code:

 <?= $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') ?> 

But when I create and save, Yii informed This field must be integer

In the model file, I had 2 functions below for conversion before validation, but this is still an error.

 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(); } 

How can I do it right to save to the database using an integer?

+5
source share
2 answers

I have found a solution. In the model search (my case of AttendanceSearch.php ), find the rule function and move the for_date from the integer line to the lines below safe

My code is:

 public function rules() { return [ [['id', 'user_id', 'project_id', 'commit_time', 'workload_type'], 'integer'], [['comment', 'for_date'], 'safe'], ]; } 
0
source

According to your code, for_date is still in the date format after beforeValidate is executed due to the line:

 $this->for_date = date('d/M/Y', $this->for_date); 

Delete this line and it should work.

However, you still have problems, for example, formatting the date, or someone who enters an incorrect date, for example, 30/02/2015 .

I would suggest creating a separate property, for example. for_date_display and adding a date rule for this. Then in beforeSave convert this date to a timestamp and set this value to for_date as follows:

 public $for_date_display; ... public function afterFind() { $this->for_date_display = \Yii::t('app', Yii::$app->formatter->asDate($this->for_date)) } public function beforeSave($insert = true) { $this->for_date = strtotime($this->for_date_display); return parent::beforeSave($insert); } 
0
source

Source: https://habr.com/ru/post/1233585/


All Articles