5

I've managed to create an Adminhtml form extending \Magento\Backend\Block\Widget\Form\Generic.
I've added each field inside _prepareForm() method using $fieldset->addField() method.
One of the fields is

  $fieldset->addField(
             'birthdate',
             'date',
             [
                 'name' => 'birthdate',
                 'label' => __('Birthdate'),
                 'title' => __('Birthdate'),
                 'required' => true,
                 'class' => '',
                 'singleClick'=> true,
                 'format'=>'dd-MM-yyyy',
                 'time'=>false
                //'format' =>$this->_localeDate->getDateFormat(\IntlDateFormatter::LONG)
             ]
         );

Now... neither formats is taken into account when the form is populated (editing a record). The default value that is read from DB is 1995-12-12.
but the form displays Tuesday, December 12, 1995 at 12:00:00 AM Eastern European Standard Time. When I'm setting the date from the calendar, the format is the desired one.

How can I specify the form to load the data with proper format?

6

For correct date's output use date_format property

  $fieldset->addField(
         'birthdate',
         'date',
         [
             'name' => 'birthdate',
             'label' => __('Birthdate'),
             'title' => __('Birthdate'),
             'required' => true,
             'class' => '',
             'singleClick'=> true,
             'date_format' => 'yyyy-MM-dd', **//Like this one**
             'time'=>false
            //'format' =>$this->_localeDate->getDateFormat(\IntlDateFormatter::LONG)
         ]
     );
1

You can use: beforeSave() in your Model to convert the input.

for Example: inject Magento\Framework\Stdlib\DateTime as $this->_date than:

  1. convert Timestamp<br> $timestamp = $this->_date->timestamp($this->getDate();
  2. convert gmtDate<br> $birthdate = $this->_date->gmtDate('y-m-d',$timestamp);
  3. $birthdate to object<br> $this->setBirthdate($birthdate);

$this->setBirthdate($this->_date->gmtDate('y-m-d',$this->_date->timestamp($this->getDate())));

//*dirty workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.