public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if (trim($this->date)){
$this->date = Yii::$app->formatter->asDate($this->date, 'php:Y-m-d');
}
return true;
} else {
return false;
}
}
public function afterFind()
{
if (trim($this->date)):
$this->date = Yii::$app->formatter->asDate($this->date, 'php:d.m.Y');
endif;
parent::afterFind(); // TODO: Change the autogenerated stub
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'DateToTimeBehavior' => [
'class' => DateToTimeBehavior::className(),
'dateAttribute' => ['date']
],
];
}
<?php
namespace common\behaviors;
use yii;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
class DateToTimeBehavior extends Behavior
{
/*
* Атрибут даты, которую
* необходимо конвектировать
* */
public $dateAttribute = null;
...
тут не знаю что
...
}
<?php
namespace common\behaviors;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\db\ActiveRecord;
use yii\base\Event;
/**
* Class DateFormatTranslator
* @package common\behaviors
*/
class DateFormatTranslator extends Behavior
{
public $machineFormat = 'php:Y-m-d';
public $humanFormat = 'php:d.m.Y';
public $attributes;
/**
* @throws InvalidConfigException
*/
public function init()
{
if(empty($this->attributes)){
throw new InvalidConfigException('attributes can not be empty');
}
return parent::init();
}
/**
* @return array
*/
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_UPDATE => 'toMachineFormat',
ActiveRecord::EVENT_BEFORE_INSERT => 'toMachineFormat',
ActiveRecord::EVENT_AFTER_INSERT => 'toHumanFormat',
ActiveRecord::EVENT_AFTER_FIND => 'toHumanFormat',
];
}
/**
* @param $event Event
* @var $owner ActiveRecord
*/
public function toHumanFormat(Event $event){
$formatter = \Yii::$app->formatter;
$owner = $event->sender;
foreach ($this->attributes as $attribute){
if(!empty($owner->$attribute)){
$owner->$attribute = $formatter->asDate($owner->$attribute, $this->humanFormat);
}
}
}
/**
* @param Event $event
*/
public function toMachineFormat(Event $event){
$formatter = \Yii::$app->formatter;
$owner = $event->sender;
foreach ($this->attributes as $attribute){
if(!empty($owner->$attribute)) {
$owner->$attribute = $formatter->asDate($owner->$attribute, $this->machineFormat);
}
}
}
}