TimestampFormatter.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php
  2. namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
  3. use Drupal\Core\Datetime\DateFormatterInterface;
  4. use Drupal\Core\Entity\EntityStorageInterface;
  5. use Drupal\Core\Field\FieldDefinitionInterface;
  6. use Drupal\Core\Field\FieldItemListInterface;
  7. use Drupal\Core\Field\FormatterBase;
  8. use Drupal\Core\Form\FormStateInterface;
  9. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  11. /**
  12. * Plugin implementation of the 'timestamp' formatter.
  13. *
  14. * @FieldFormatter(
  15. * id = "timestamp",
  16. * label = @Translation("Default"),
  17. * field_types = {
  18. * "timestamp",
  19. * "created",
  20. * "changed",
  21. * }
  22. * )
  23. */
  24. class TimestampFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
  25. /**
  26. * The date formatter service.
  27. *
  28. * @var \Drupal\Core\Datetime\DateFormatterInterface
  29. */
  30. protected $dateFormatter;
  31. /**
  32. * The date format entity storage.
  33. *
  34. * @var \Drupal\Core\Entity\EntityStorageInterface
  35. */
  36. protected $dateFormatStorage;
  37. /**
  38. * Constructs a new TimestampFormatter.
  39. *
  40. * @param string $plugin_id
  41. * The plugin_id for the formatter.
  42. * @param mixed $plugin_definition
  43. * The plugin implementation definition.
  44. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  45. * The definition of the field to which the formatter is associated.
  46. * @param array $settings
  47. * The formatter settings.
  48. * @param string $label
  49. * The formatter label display setting.
  50. * @param string $view_mode
  51. * The view mode.
  52. * @param array $third_party_settings
  53. * Third party settings.
  54. * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
  55. * The date formatter service.
  56. * @param \Drupal\Core\Entity\EntityStorageInterface $date_format_storage
  57. * The date format storage.
  58. */
  59. public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatterInterface $date_formatter, EntityStorageInterface $date_format_storage) {
  60. parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
  61. $this->dateFormatter = $date_formatter;
  62. $this->dateFormatStorage = $date_format_storage;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  68. return new static(
  69. $plugin_id,
  70. $plugin_definition,
  71. $configuration['field_definition'],
  72. $configuration['settings'],
  73. $configuration['label'],
  74. $configuration['view_mode'],
  75. $configuration['third_party_settings'],
  76. $container->get('date.formatter'),
  77. $container->get('entity.manager')->getStorage('date_format')
  78. );
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. public static function defaultSettings() {
  84. return [
  85. 'date_format' => 'medium',
  86. 'custom_date_format' => '',
  87. 'timezone' => '',
  88. ] + parent::defaultSettings();
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function settingsForm(array $form, FormStateInterface $form_state) {
  94. $elements = parent::settingsForm($form, $form_state);
  95. $date_formats = [];
  96. foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) {
  97. $date_formats[$machine_name] = $this->t('@name format: @date', ['@name' => $value->label(), '@date' => $this->dateFormatter->format(REQUEST_TIME, $machine_name)]);
  98. }
  99. $date_formats['custom'] = $this->t('Custom');
  100. $elements['date_format'] = [
  101. '#type' => 'select',
  102. '#title' => $this->t('Date format'),
  103. '#options' => $date_formats,
  104. '#default_value' => $this->getSetting('date_format') ?: 'medium',
  105. ];
  106. $elements['custom_date_format'] = [
  107. '#type' => 'textfield',
  108. '#title' => $this->t('Custom date format'),
  109. '#description' => $this->t('See <a href="http://php.net/manual/function.date.php" target="_blank">the documentation for PHP date formats</a>.'),
  110. '#default_value' => $this->getSetting('custom_date_format') ?: '',
  111. ];
  112. $elements['custom_date_format']['#states']['visible'][] = [
  113. ':input[name="fields[' . $this->fieldDefinition->getName() . '][settings_edit_form][settings][date_format]"]' => ['value' => 'custom'],
  114. ];
  115. $elements['timezone'] = [
  116. '#type' => 'select',
  117. '#title' => $this->t('Time zone'),
  118. '#options' => ['' => $this->t('- Default site/user time zone -')] + system_time_zones(FALSE, TRUE),
  119. '#default_value' => $this->getSetting('timezone'),
  120. ];
  121. return $elements;
  122. }
  123. /**
  124. * {@inheritdoc}
  125. */
  126. public function settingsSummary() {
  127. $summary = parent::settingsSummary();
  128. $date_format = $this->getSetting('date_format');
  129. $summary[] = $this->t('Date format: @date_format', ['@date_format' => $date_format]);
  130. if ($this->getSetting('date_format') === 'custom' && ($custom_date_format = $this->getSetting('custom_date_format'))) {
  131. $summary[] = $this->t('Custom date format: @custom_date_format', ['@custom_date_format' => $custom_date_format]);
  132. }
  133. if ($timezone = $this->getSetting('timezone')) {
  134. $summary[] = $this->t('Time zone: @timezone', ['@timezone' => $timezone]);
  135. }
  136. return $summary;
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function viewElements(FieldItemListInterface $items, $langcode) {
  142. $elements = [];
  143. $date_format = $this->getSetting('date_format');
  144. $custom_date_format = '';
  145. $timezone = $this->getSetting('timezone') ?: NULL;
  146. $langcode = NULL;
  147. // If an RFC2822 date format is requested, then the month and day have to
  148. // be in English. @see http://www.faqs.org/rfcs/rfc2822.html
  149. if ($date_format === 'custom' && ($custom_date_format = $this->getSetting('custom_date_format')) === 'r') {
  150. $langcode = 'en';
  151. }
  152. foreach ($items as $delta => $item) {
  153. $elements[$delta] = [
  154. '#cache' => [
  155. 'contexts' => [
  156. 'timezone',
  157. ],
  158. ],
  159. '#markup' => $this->dateFormatter->format($item->value, $date_format, $custom_date_format, $timezone, $langcode),
  160. ];
  161. }
  162. return $elements;
  163. }
  164. }