M
M
Mick Coder2015-03-28 21:03:57
MySQL
Mick Coder, 2015-03-28 21:03:57

Yii2. How to store and use the date in a specific format?

Hey! Set the date format for the entire project

'formatter' => [
          'dateFormat' => 'dd-mm-yyyy',
   		],

I use it (form validationb grid), but when saving to the database, an error occurs
atabase Exception – yii\db\Exception

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '18-03-2015' for column 'lock_start' at row 1
The SQL being executed was: INSERT INTO `reservation` (`id_room`, `lock_start`, `lock_finish`, `notes`, `is_cancel`, `cleaning_day`, `group_t`) VALUES (5, '18-03-2015', '27-03-2015', '', NULL, NULL, '')

That is, Mysql only accepts the yyyy-mm-dd format.
How to be in this situation? Maybe some kind of filter to use when saving?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Zhuravlev, 2015-03-29
@lbondodesc

To output the date in your format use:
The asDate method will recognize a string with a date in the mysql format and return a string with a date in the format from the config.
To transfer the model to the form, you will need small dances with a tambourine:

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    // Приводим дату к пользовательскому формату
    $model->lock_start = Yii::$app->formatter->asDate($model->lock_start);
    // Ставим обработчик который после успешной проверки данных в пользовательском формате вернет дату в формат для mysql
    $model->on(ActiveRecord::EVENT_BEFORE_UPDATE, function () use ($model) {
        $model->lock_start = \DateTime::createFromFormat('d-m-Y', $model->lock_start)->format('Y-m-d');
    });
    // Дальше стандартный код
    if ($model->load(Yii::$app->request->post())) {
        if ($model->save()) {
            return $this->redirect(['index']);
        }
    }
    return $this->render('update', [
        'model' => $model,
    ]);
}

This entire sequence can be moved to a separate model method, or connected via behavior.

R
retvizan, 2015-03-28
@retvizan

What about the date format?
Read the error message carefully.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question