Magento 2 - How to add the DateTime UI Component
To add the dateTime picker you should use the next directive inside the xml file:
<field name="start_date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="label" xsi:type="string" translate="true">Go Live Start Date</item>
<item name="formElement" xsi:type="string">date</item>
<item name="source" xsi:type="string">page</item>
<item name="sortOrder" xsi:type="number">21</item>
<item name="dataScope" xsi:type="string">start_date</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
</item>
<item name="options" xsi:type="array">
<item name="dateFormat" xsi:type="string">yyyy-MM-dd</item>
<item name="timeFormat" xsi:type="string">HH:mm:ss</item>
<item name="showsTime" xsi:type="boolean">true</item>
</item>
<item name="storeTimeZone" xsi:type="string">string</item>
</item>
</argument>
</field>
Important thing is the showsTime
option.
Result should look like this:
If you want to debug the UI element - use this command inside the browser console (on your page):
require('uiRegistry').get('index = start_date')
It returns your date
element with all initial options and all possible functions:
You can use them when you define the element (inside xml).
As additional info:
The date
(also dateTime
) element could be found here:
app/code/Magento/Ui/view/base/web/js/form/element/date.js
in the static files:
pub/static/adminhtml/Magento/backend/en_US/Magento_Ui/js/form/element/date.js
The date-element class (object) has method prepareDateTimeFormats
, where the important option showsTime
is checked:
/**
* Prepares and converts all date/time formats to be compatible
* with moment.js library.
*/
prepareDateTimeFormats: function () {
this.pickerDateTimeFormat = this.options.dateFormat;
if (this.options.showsTime) {
this.pickerDateTimeFormat += ' ' + this.options.timeFormat;
}
this.pickerDateTimeFormat = utils.normalizeDate(this.pickerDateTimeFormat);
if (this.dateFormat) {
this.inputDateFormat = this.dateFormat;
}
this.inputDateFormat = utils.normalizeDate(this.inputDateFormat);
this.outputDateFormat = utils.normalizeDate(this.outputDateFormat);
this.validationParams.dateFormat = this.outputDateFormat;
}
I hope this answer gives some idea about what you miss
I added the UI component of date time field through php (it works fine)
$fieldset->addField(
'event_date',
'date',
[
'name' => 'event_date',
'label' => __('Date'),
'title' => __('Date'),
'required' => true,
'date_format' => 'yyyy-MM-dd',
'time_format' => 'hh:mm:ss'
]
);
compare to your xml file all values are present except date_format and time_format so you can try to set the both value in your xml file
for more details please refer this full source code