Since an administrator of the website I am building is visually impaired, I need to create a custom date field widget rather than use the one provided by Drupal.
I am trying to implement a datelist
element.
<?php namespace Drupalmy_modulePluginFieldFieldWidget; use DrupalCoreDatetimeDrupalDateTime; use DrupalCoreFieldFieldItemListInterface; use DrupalCoreFieldWidgetBase; use DrupalCoreFormFormStateInterface; /** * Accessible date field widget. * * @FieldWidget( * id = "accessible_date", * label = @Translation("Accessible date widget"), * field_types = { * "datetime" * } * ) */ class AccessibleDate extends WidgetBase { /** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $max_year = date('Y') + 1; $default_date = new DrupalDateTime(); if (isset($items[$delta]->value)) { $default_date = new DrupalDateTime($items[$delta]->value); } $element += [ '#type' => 'datelist', '#default_value' => $default_date, '#date_part_order' => [ 'day', 'month', 'year', 'hour', 'minute', ], '#date_year_range' => '2000:' . $max_year, ]; return ['value' => $element]; } }
The widget is displayed correctly but when I submit the form to add or edit a node, I have the following error on each of the datelist fields: "The datetime value must be a string."
Do you know how to fix this?