J
J
JohnDaniels2017-06-09 15:46:22
Web development
JohnDaniels, 2017-06-09 15:46:22

How to set date formatting rules in YII2 model?

Hello.
There is an ActiveRecord model containing the created_at field, the field type in the database is timestamp.
I need to select the desired records and send them as json, that is, like this:

\Yii::$app->response->format = Response::FORMAT_JSON;
        $consultations = Consultation::find()->orderBy('id DESC')->limit(5)->asArray()->all();
        return $consultations;

everything is fine, but the field created_atlooks like "2017-06-09 16:14:09", and I need a short entry "06/09/17".
Ideally, I would like to add my own field to the model formattedDate, which would take data from created_atand format it as I need.
1. How is it done correctly in Yii? In Laravel, for example, you can use mutators for such purposes, I didn’t find anything similar here.
2. How to add custom fields to models? I specified a public property, added it to the rules, but it's still not visible.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-06-09
@JohnDaniels

If you need to make such transformations everywhere, then you can put the logic in afterFind.
If not everywhere but often, make a getter in the model that makes the necessary transformations, for example:

public function getShortDate(){
  return \Yii::$app->formatter->asDate($this->created_at, 'short');
}

If it's only once, then you can:
$consultations = Consultation::find()->orderBy('id DESC')->limit(5)->all();
$data = ArrayHelper::toArray($consultations [
    'app\models\Consultation' => [
        'date' => function ($model) {
             return \Yii::$app->formatter->asDate($model->created_at, 'short');
        },
        'date2' => 'shortDate' //это вариант если геттер есть, который выше описал
    ],
]);
\Yii::$app->response->format = Response::FORMAT_JSON;
return $data

Read about:
www.yiiframework.com/doc-2.0/yii-i18n-formatter.html
www.yiiframework.com/doc-2.0/guide-output-formatti...
www.yiiframework.com/doc-2.0/guide -helper-array.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question