DateTimeFieldItemList.php 2.53 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Contains \Drupal\datetime\Plugin\Field\FieldType\DateTimeFieldItemList.
 */

namespace Drupal\datetime\Plugin\Field\FieldType;

use Drupal\Core\Datetime\DrupalDateTime;
11
use Drupal\Core\Field\FieldItemList;
12 13 14 15

/**
 * Represents a configurable entity datetime field.
 */
16
class DateTimeFieldItemList extends FieldItemList {
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

  /**
   * Defines the default value as now.
   */
  const DEFAULT_VALUE_NOW = 'now';

  /**
   * {@inheritdoc}
   */
  public function defaultValuesForm(array &$form, array &$form_state) {
    if (empty($this->getFieldDefinition()->default_value_function)) {
      $default_value = $this->getFieldDefinition()->default_value;

      $element = array(
        '#parents' => array('default_value_input'),
        'default_date' => array(
          '#type' => 'select',
          '#title' => t('Default date'),
          '#description' => t('Set a default value for this date.'),
          '#default_value' => isset($default_value[0]['default_date']) ? $default_value[0]['default_date'] : '',
          '#options' => array(static::DEFAULT_VALUE_NOW => t('The current date')),
          '#empty_value' => '',
        )
      );

      return $element;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesFormValidate(array $element, array &$form, array &$form_state) { }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesFormSubmit(array $element, array &$form, array &$form_state) {
    if ($form_state['values']['default_value_input']['default_date']) {
      return array($form_state['values']['default_value_input']);
    }
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultValue() {
    $default_value = parent::getDefaultValue();

    if (isset($default_value[0]['default_date']) && $default_value[0]['default_date'] == static::DEFAULT_VALUE_NOW) {
      // A default value should be in the format and timezone used for date
      // storage.
      $date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
      $storage_format = $this->getFieldDefinition()->getSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE ? DATETIME_DATE_STORAGE_FORMAT: DATETIME_DATETIME_STORAGE_FORMAT;
      $value = $date->format($storage_format);
      // We only provide a default value for the first item, as do all fields.
      // Otherwise, there is no way to clear out unwanted values on multiple value
      // fields.
      $default_value =  array(
        array(
          'value' => $value,
          'date' => $date,
        )
      );
    }
    return $default_value;
  }

}