I activated the Datetime Range core module and it works inside a content type, from the BO, but I want to use it in a custom form. I tried :

  $form['training_interval'] = [
    '#type' => 'daterange',
    '#required' => TRUE,
    // '#default_value' => 'TODO',

and also daterange_default, datetime_range and any value which could have been relevant giving the module code, but nothing is displayed. I must confess I feel silly...

  • Datetime Range doesn't provide a form element. Simply provide 2 '#type' => 'date' elements on your own, one for the start date, one for the end date, and then pick them up in your form submit handler. – leymannx Nov 12 '20 at 10:43

The Datetime Range module provides a new field type, 'daterange'. The field is a plugin with provides the Item and List, the Widgets, and the Formatters.

The Item and List are what get actually attached to an entity, either as a base field or a configurable field.

The Widget is what gets used on the entity edit form.

The Formatters get used whenever the field is output, either as part of the parent entity itself or as part of a view.

Note I mentioned entities and not forms. The Datetime Range module does not provide any new form elements. The Widgets themselves are built around the core 'datetime' and 'datelist' elements (which really have nothing to do with the Datetime module; yes this is seriously confusing).

So, if you have a custom form and want a date range, you are going to have to build this yourself with two 'datetime' elements, and then have some validation rules to make this behave the way you want.

  • "you are going to have to build this yourself with two 'datetime' elements". Please note this is not true if you are using baseFieldDefinitions in a custom entity. drupal.org/docs/8/core/modules/datetime-range – arnoldbird Mar 14 '18 at 22:43
  • 1
    @arnoldbird Correct, daterange can be used as a base field on an entity, but not as part of an arbitrary form as an element. A lot of the confusion around this stems from "datetime" being used for three distinct things in core (the field type, the form element, and the object type) and a base PHP feature, – mpdonadio Mar 14 '18 at 22:49

If you programatically need to set a datetime range field when creating a node in a custom form submit handler for example, you need to to fill two values:

The start date value and the end date end_value.

$node = \Drupal\node\Entity\Node::create([
  'type' => $type,
  'title' => $title,
  'field_dates' => [
    'value'=> '2018-02-02T12:12:12',
    'end_value' => '2018-05-05T12:12:12'

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.