3 namespace Drupal\datetime\Plugin\Field\FieldType;
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldStorageDefinitionInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\TypedData\DataDefinition;
9 use Drupal\Core\Field\FieldItemBase;
12 * Plugin implementation of the 'datetime' field type.
16 * label = @Translation("Date"),
17 * description = @Translation("Create and store date values."),
18 * default_widget = "datetime_default",
19 * default_formatter = "datetime_default",
20 * list_class = "\Drupal\datetime\Plugin\Field\FieldType\DateTimeFieldItemList"
23 class DateTimeItem extends FieldItemBase {
28 public static function defaultStorageSettings() {
30 'datetime_type' => 'datetime',
31 ] + parent::defaultStorageSettings();
35 * Value for the 'datetime_type' setting: store only a date.
37 const DATETIME_TYPE_DATE = 'date';
40 * Value for the 'datetime_type' setting: store a date and time.
42 const DATETIME_TYPE_DATETIME = 'datetime';
47 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
48 $properties['value'] = DataDefinition::create('datetime_iso8601')
49 ->setLabel(t('Date value'))
52 $properties['date'] = DataDefinition::create('any')
53 ->setLabel(t('Computed date'))
54 ->setDescription(t('The computed DateTime object.'))
56 ->setClass('\Drupal\datetime\DateTimeComputed')
57 ->setSetting('date source', 'value');
65 public static function schema(FieldStorageDefinitionInterface $field_definition) {
69 'description' => 'The date value.',
83 public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
86 $element['datetime_type'] = [
88 '#title' => t('Date type'),
89 '#description' => t('Choose the type of date to create.'),
90 '#default_value' => $this->getSetting('datetime_type'),
92 static::DATETIME_TYPE_DATETIME => t('Date and time'),
93 static::DATETIME_TYPE_DATE => t('Date only'),
95 '#disabled' => $has_data,
104 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
105 $type = $field_definition->getSetting('datetime_type');
107 // Just pick a date in the past year. No guidance is provided by this Field
109 $timestamp = REQUEST_TIME - mt_rand(0, 86400 * 365);
110 if ($type == DateTimeItem::DATETIME_TYPE_DATE) {
111 $values['value'] = gmdate(DATETIME_DATE_STORAGE_FORMAT, $timestamp);
114 $values['value'] = gmdate(DATETIME_DATETIME_STORAGE_FORMAT, $timestamp);
122 public function isEmpty() {
123 $value = $this->get('value')->getValue();
124 return $value === NULL || $value === '';
130 public function onChange($property_name, $notify = TRUE) {
131 // Enforce that the computed date is recalculated.
132 if ($property_name == 'value') {
135 parent::onChange($property_name, $notify);