Drupal - How to use daterange field programmatically?

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'
  ],
]);
$node->save();

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.

Tags:

Forms

8