DateTimeWidgetBase.php in Drupal 10
File
core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php
View source
<?php
namespace Drupal\datetime\Plugin\Field\FieldWidget;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
class DateTimeWidgetBase extends WidgetBase {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['value'] = [
'#type' => 'datetime',
'#default_value' => NULL,
'#date_increment' => 1,
'#date_timezone' => date_default_timezone_get(),
'#required' => $element['#required'],
];
if ($this
->getFieldSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE) {
$element['value']['#date_timezone'] = DateTimeItemInterface::STORAGE_TIMEZONE;
}
if ($items[$delta]->date) {
$element['value']['#default_value'] = $this
->createDefaultValue($items[$delta]->date, $element['value']['#date_timezone']);
}
return $element;
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
$datetime_type = $this
->getFieldSetting('datetime_type');
if ($datetime_type === DateTimeItem::DATETIME_TYPE_DATE) {
$storage_format = DateTimeItemInterface::DATE_STORAGE_FORMAT;
}
else {
$storage_format = DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
}
$storage_timezone = new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE);
foreach ($values as &$item) {
if (!empty($item['value']) && $item['value'] instanceof DrupalDateTime) {
$date = $item['value'];
$item['value'] = $date
->setTimezone($storage_timezone)
->format($storage_format);
}
}
return $values;
}
protected function createDefaultValue($date, $timezone) {
if ($this
->getFieldSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
$date
->setDefaultDateTime();
}
$date
->setTimezone(new \DateTimeZone($timezone));
return $date;
}
}