function DateTimeWidgetBase::createDefaultValue

Same name in other branches
  1. 9 core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php \Drupal\datetime\Plugin\Field\FieldWidget\DateTimeWidgetBase::createDefaultValue()
  2. 8.9.x core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php \Drupal\datetime\Plugin\Field\FieldWidget\DateTimeWidgetBase::createDefaultValue()
  3. 11.x core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php \Drupal\datetime\Plugin\Field\FieldWidget\DateTimeWidgetBase::createDefaultValue()

Creates a date object for use as a default value.

This will take a default value, apply the proper timezone for display in a widget, and set the default time for date-only fields.

Parameters

\Drupal\Core\Datetime\DrupalDateTime $date: The UTC default date.

string $timezone: The timezone to apply.

Return value

\Drupal\Core\Datetime\DrupalDateTime A date object for use as a default value in a field widget.

2 calls to DateTimeWidgetBase::createDefaultValue()
DateRangeWidgetBase::formElement in core/modules/datetime_range/src/Plugin/Field/FieldWidget/DateRangeWidgetBase.php
Returns the form for a single field widget.
DateTimeWidgetBase::formElement in core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php
Returns the form for a single field widget.

File

core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php, line 86

Class

DateTimeWidgetBase
Base class for the 'datetime_*' widgets.

Namespace

Drupal\datetime\Plugin\Field\FieldWidget

Code

protected function createDefaultValue($date, $timezone) {
    // The date was created and verified during field_load(), so it is safe to
    // use without further inspection.
    $year = $date->format('Y');
    $month = $date->format('m');
    $day = $date->format('d');
    $date->setTimezone(new \DateTimeZone($timezone));
    if ($this->getFieldSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
        $date->setDefaultDateTime();
        // Reset the date to handle cases where the UTC offset is greater than
        // 12 hours.
        $date->setDate($year, $month, $day);
    }
    return $date;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.