DateTimeDefaultFormatter.php 5.67 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\datetime\Plugin\Field\FieldFormatter\DateTimeDefaultFormatter.
6 7
 */

8
namespace Drupal\datetime\Plugin\Field\FieldFormatter;
9

10
use Drupal\Core\Datetime\Date as DateFormatter;
11
use Drupal\Core\Datetime\DrupalDateTime;
12
use Drupal\Core\Entity\EntityStorageInterface;
13 14
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
15
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
16
use Drupal\Core\Field\FormatterBase;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18 19 20 21

/**
 * Plugin implementation of the 'datetime_default' formatter.
 *
22
 * @FieldFormatter(
23 24 25 26 27 28 29
 *   id = "datetime_default",
 *   label = @Translation("Default"),
 *   field_types = {
 *     "datetime"
 *   }
 * )
 */
30 31
class DateTimeDefaultFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

32 33 34 35 36 37 38 39 40
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'format_type' => 'medium',
    ) + parent::defaultSettings();
  }

41
  /**
42
   * The date formatter service.
43 44 45
   *
   * @var \Drupal\Core\Datetime\Date
   */
46
  protected $dateFormatter;
47 48

  /**
49
   * The date storage.
50
   *
51
   * @var \Drupal\Core\Entity\EntityStorageInterface
52 53 54 55 56 57 58 59
   */
  protected $dateStorage;

  /**
   * Constructs a new DateTimeDefaultFormatter.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
60
   * @param mixed $plugin_definition
61
   *   The plugin implementation definition.
62
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
63 64 65 66 67 68 69
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
70 71
   * @param array $third_party_settings
   *   Third party settings.
72 73
   * @param \Drupal\Core\Datetime\Date $date_formatter
   *   The date formatter service.
74 75
   * @param \Drupal\Core\Entity\EntityStorageInterface $date_storage
   *   The date storage.
76
   */
77
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatter $date_formatter, EntityStorageInterface $date_storage) {
78
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
79

80
    $this->dateFormatter = $date_formatter;
81 82 83 84 85 86
    $this->dateStorage = $date_storage;
  }

  /**
   * {@inheritdoc}
   */
87
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
88 89 90 91 92 93 94
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
95
      $configuration['third_party_settings'],
96
      $container->get('date'),
97
      $container->get('entity.manager')->getStorage('date_format')
98 99
    );
  }
100 101

  /**
102
   * {@inheritdoc}
103
   */
104
  public function viewElements(FieldItemListInterface $items) {
105 106 107 108 109 110 111 112

    $elements = array();

    foreach ($items as $delta => $item) {

      $formatted_date = '';
      $iso_date = '';

113
      if ($item->date) {
114
        $date = $item->date;
115 116 117 118 119
        // Create the ISO date in Universal Time.
        $iso_date = $date->format("Y-m-d\TH:i:s") . 'Z';

        // The formatted output will be in local time.
        $date->setTimeZone(timezone_open(drupal_get_user_timezone()));
120
        if ($this->getFieldSetting('datetime_type') == 'date') {
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
          // A date without time will pick up the current time, use the default.
          datetime_date_default_time($date);
        }
        $formatted_date = $this->dateFormat($date);
      }

      // Display the date using theme datetime.
      $elements[$delta] = array(
        '#theme' => 'datetime',
        '#text' => $formatted_date,
        '#html' => FALSE,
        '#attributes' => array(
          'datetime' => $iso_date,
        ),
      );
136 137 138 139 140 141
      if (!empty($item->_attributes)) {
        $elements[$delta]['#attributes'] += $item->_attributes;
        // Unset field item attributes since they have been included in the
        // formatter output and should not be rendered in the field template.
        unset($item->_attributes);
      }
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    }

    return $elements;

  }

  /**
   * Creates a formatted date value as a string.
   *
   * @param object $date
   *   A date object.
   *
   * @return string
   *   A formatted date string using the chosen format.
   */
  function dateFormat($date) {
    $format_type = $this->getSetting('format_type');
159
    return $this->dateFormatter->format($date->getTimestamp(), $format_type);
160 161 162
  }

  /**
163
   * {@inheritdoc}
164 165 166
   */
  public function settingsForm(array $form, array &$form_state) {
    $time = new DrupalDateTime();
167 168
    $format_types = $this->dateStorage->loadMultiple();
    foreach ($format_types as $type => $type_info) {
169
      $format = $this->dateFormatter->format($time->format('U'), $type);
170
      $options[$type] = $type_info->label() . ' (' . $format . ')';
171 172 173 174 175 176 177 178 179 180 181 182 183 184
    }

    $elements['format_type'] = array(
      '#type' => 'select',
      '#title' => t('Date format'),
      '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."),
      '#options' => $options,
      '#default_value' => $this->getSetting('format_type'),
    );

    return $elements;
  }

  /**
185
   * {@inheritdoc}
186 187
   */
  public function settingsSummary() {
188
    $summary = array();
189
    $date = new DrupalDateTime();
190 191
    $summary[] = t('Format: @display', array('@display' => $this->dateFormat($date, FALSE)));
    return $summary;
192 193 194
  }

}