Using yii2-datecontrol within yii2-detail-view

About DateControl and DetailView:

The yii2-datecontrol extension allows you to control separate date formats for display and saving for form inputs.

The yii2-detail-view extension, enhances the yii DetailView and enables you to toggle between VIEW and EDIT modes with other features.

This article explains you how you combine both. That is, how you can enable date formats for display and save using the DateControl extension within yii2-detail-view.

NOTE: To setup the controller and view to work with yii2-detail-view extension for update and delete, you can refer this article.

Scenario

Let’s assume you want to display dates as “d-m-Y” format and save dates as “Y-m-d” format to db.

DateControl Module Settings

Setup your yii2-datecontrol module as follows:

'modules' => [
    'datecontrol' => [
        'class' => 'kartik\datecontrol\Module',

        // format settings for displaying each date attribute
        'displaySettings' => [
            'date' => 'php:d-M-Y',
            'time' => 'php:H:i:s A',
            'datetime' => 'php:d-m-Y H:i:s A',
        ],

        // format settings for saving each date attribute
        'saveSettings' => [
            'date' => 'php:Y-m-d', 
            'time' => 'php:H:i:s',
            'datetime' => 'php:Y-m-d H:i:s',
        ],

        // automatically use kartikwidgets for each of the above formats
        'autoWidget' => true,
    ],
],

DetailView Attributes Configuration

Setup your yii2-detail-view date related attributes to use the DateControl extension as mentioned below:

use kartik\detail\DetailView;
use kartik\datecontrol\DateControl;

echo DetailView::widget([
    'model'=>$model,
    'panel'=>$panel
    'attributes'=>[
        'code',
        [
            'attribute'=>'publish_date', 
            'format'=>['date', 'php:d-m-Y'],
            'type'=>DetailView::INPUT_WIDGET, // setup custom widget
            'widgetOptions'=>[
                'class'=>DateControl::classname(),
                'type'=>DateControl::FORMAT_DATE
            ]
        ],
    ]
]);

With the above settings, you should see the dates getting displayed in ‘d-m-Y’ format and saved in ‘Y-m-d’ format.