DateRangeCustomFormatter.php in Drupal 10
File
core/modules/datetime_range/src/Plugin/Field/FieldFormatter/DateRangeCustomFormatter.php
View source
<?php
namespace Drupal\datetime_range\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\datetime\Plugin\Field\FieldFormatter\DateTimeCustomFormatter;
use Drupal\datetime_range\DateTimeRangeTrait;
class DateRangeCustomFormatter extends DateTimeCustomFormatter {
use DateTimeRangeTrait;
public static function defaultSettings() {
return [
'separator' => '-',
] + parent::defaultSettings();
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$separator = $this
->getSetting('separator');
foreach ($items as $delta => $item) {
if (!empty($item->start_date) && !empty($item->end_date)) {
$start_date = $item->start_date;
$end_date = $item->end_date;
if ($start_date
->getTimestamp() !== $end_date
->getTimestamp()) {
$elements[$delta] = [
'start_date' => $this
->buildDate($start_date),
'separator' => [
'#plain_text' => ' ' . $separator . ' ',
],
'end_date' => $this
->buildDate($end_date),
];
}
else {
$elements[$delta] = $this
->buildDate($start_date);
}
}
}
return $elements;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['separator'] = [
'#type' => 'textfield',
'#title' => $this
->t('Date separator'),
'#description' => $this
->t('The string to separate the start and end dates'),
'#default_value' => $this
->getSetting('separator'),
];
return $form;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($separator = $this
->getSetting('separator')) {
$summary[] = $this
->t('Separator: %separator', [
'%separator' => $separator,
]);
}
return $summary;
}
}