2022-11-07

Yii2 Преобразование данных в модели для БД и формы

public function behaviors()
{
    return [
        'typecast_get' => [
            'class' => AttributeTypecastBehavior::className(),
            'attributeTypes' => [
                'date_from' => function ($value) {
                    return $value?date('d.m.Y',$value):'';
                },
                'date_to' => function ($value) {
                    return $value?date('d.m.Y',$value):'';
                },
            ],
            'typecastAfterValidate' => false,
            'typecastBeforeSave' => false,
            'typecastAfterFind' => true,
        ],
        'typecast_set' => [
            'class' => AttributeTypecastBehavior::className(),
            'attributeTypes' => [
                'date_from' => function ($value) {
                    return $value?strtotime($value):null;
                },
                'date_to' => function ($value) {
                    return $value?strtotime($value):null;
                },
            ],
            'typecastAfterValidate' => false,
            'typecastBeforeSave' => true,
            'typecastAfterFind' => false,
        ],
    ];
}

Комментарии