Skip to content
Advertisement

Yii2 kartik/date/datepicker shows wrong format while update

I use kartik DatePicker in my activeform.

use kartikdateDatePicker;

My activeform field:

    <?= $form->field($model, 'transferred_date')->widget(DatePicker::className(), [
                        'value' => date('d-M-Y', strtotime('+2 days')),
                        'options' => ['placeholder' => 'Select date ...'],
                        'pluginOptions' => [
                            'format' => 'dd-mm-yyyy',
                            'todayHighlight' => true
                        ]
    ])->label('Transferred Date');
?>

While creating I save it as a UTC date format :

$model->transferred_date = new MongoDBBSONUTCDateTime(strtotime($postModel['transferred_date'])*1000);

When I update, it shows as

enter image description here

I need this as

enter image description here

Advertisement

Answer

You have to provide the formatted date to the widget.

  • When using ActiveForm you can override afterFind() for the specific model to format the date and override the default timestamp value for the transferred_date field.

  • For Formatting, you can use the yii-i18n-formatter component by defining inside the config file common/config/main.php if using advanced-app, or config/web.php if using basic-app.

    Add below in the config file

      'components'=>[
          'formatter' => [
              'dateFormat'=>'dd-MM-yyyy',
              'datetimeFormat' => 'yyyy-MM-dd HH:mm:ss',
          ],
      ]
    

    Add below into your model

      public function afterFind() {
          parent::afterFind();
          $this->transferred_date=Yii::$app->formatter->asDate($this->transferred_date);
      }
    

Now change the field definition to below and refresh the page

<?php echo $form->field($model, 'transferred_date')->widget(DatePicker::class, [
    'options' => ['placeholder' => 'Select date ...'],
    'pluginOptions' => [
        'format' => 'dd-mm-yyyy',
        'todayHighlight' => true,
    ],
])->label('Transferred Date');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement