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",
21 * constraints = {"DateTimeFormat" = {}}
24 class DateTimeItem extends FieldItemBase implements DateTimeItemInterface {
29 public static function defaultStorageSettings() {
31 'datetime_type' => 'datetime',
32 ] + parent::defaultStorageSettings();
36 * Value for the 'datetime_type' setting: store only a date.
38 const DATETIME_TYPE_DATE = 'date';
41 * Value for the 'datetime_type' setting: store a date and time.
43 const DATETIME_TYPE_DATETIME = 'datetime';
48 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
49 $properties['value'] = DataDefinition::create('datetime_iso8601')
50 ->setLabel(t('Date value'))
53 $properties['date'] = DataDefinition::create('any')
54 ->setLabel(t('Computed date'))
55 ->setDescription(t('The computed DateTime object.'))
57 ->setClass('\Drupal\datetime\DateTimeComputed')
58 ->setSetting('date source', 'value');
66 public static function schema(FieldStorageDefinitionInterface $field_definition) {
70 'description' => 'The date value.',
84 public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
87 $element['datetime_type'] = [
89 '#title' => t('Date type'),
90 '#description' => t('Choose the type of date to create.'),
91 '#default_value' => $this->getSetting('datetime_type'),
93 static::DATETIME_TYPE_DATETIME => t('Date and time'),
94 static::DATETIME_TYPE_DATE => t('Date only'),
96 '#disabled' => $has_data,
105 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
106 $type = $field_definition->getSetting('datetime_type');
108 // Just pick a date in the past year. No guidance is provided by this Field
110 $timestamp = REQUEST_TIME - mt_rand(0, 86400 * 365);
111 if ($type == DateTimeItem::DATETIME_TYPE_DATE) {
112 $values['value'] = gmdate(static::DATE_STORAGE_FORMAT, $timestamp);
115 $values['value'] = gmdate(static::DATETIME_STORAGE_FORMAT, $timestamp);
123 public function isEmpty() {
124 $value = $this->get('value')->getValue();
125 return $value === NULL || $value === '';
131 public function onChange($property_name, $notify = TRUE) {
132 // Enforce that the computed date is recalculated.
133 if ($property_name == 'value') {
136 parent::onChange($property_name, $notify);