fa6549665af569bfdb341fc059f26ee170309e45
[yaffs-website] / src / Plugin / Field / FieldFormatter / DateTimeDefaultFormatter.php
1 <?php
2
3 namespace Drupal\datetime\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Datetime\DrupalDateTime;
6 use Drupal\Core\Form\FormStateInterface;
7
8 /**
9  * Plugin implementation of the 'Default' formatter for 'datetime' fields.
10  *
11  * @FieldFormatter(
12  *   id = "datetime_default",
13  *   label = @Translation("Default"),
14  *   field_types = {
15  *     "datetime"
16  *   }
17  * )
18  */
19 class DateTimeDefaultFormatter extends DateTimeFormatterBase {
20
21   /**
22    * {@inheritdoc}
23    */
24   public static function defaultSettings() {
25     return [
26       'format_type' => 'medium',
27     ] + parent::defaultSettings();
28   }
29
30   /**
31    * {@inheritdoc}
32    */
33   protected function formatDate($date) {
34     $format_type = $this->getSetting('format_type');
35     $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();
36     return $this->dateFormatter->format($date->getTimestamp(), $format_type, '', $timezone != '' ? $timezone : NULL);
37   }
38
39   /**
40    * {@inheritdoc}
41    */
42   public function settingsForm(array $form, FormStateInterface $form_state) {
43     $form = parent::settingsForm($form, $form_state);
44
45     $time = new DrupalDateTime();
46     $format_types = $this->dateFormatStorage->loadMultiple();
47     $options = [];
48     foreach ($format_types as $type => $type_info) {
49       $format = $this->dateFormatter->format($time->getTimestamp(), $type);
50       $options[$type] = $type_info->label() . ' (' . $format . ')';
51     }
52
53     $form['format_type'] = [
54       '#type' => 'select',
55       '#title' => t('Date format'),
56       '#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."),
57       '#options' => $options,
58       '#default_value' => $this->getSetting('format_type'),
59     ];
60
61     return $form;
62   }
63
64   /**
65    * {@inheritdoc}
66    */
67   public function settingsSummary() {
68     $summary = parent::settingsSummary();
69
70     $date = new DrupalDateTime();
71     $summary[] = t('Format: @display', ['@display' => $this->formatDate($date)]);
72
73     return $summary;
74   }
75
76 }