View source
<?php
namespace Drupal\office_hours\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
class OfficeHoursFormatterTable extends OfficeHoursFormatterBase {
public function settingsSummary() {
$summary = parent::settingsSummary();
$summary[] = $this
->t('Display Office hours in a table.');
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
if (!$items
->getValue()) {
return $elements;
}
$settings = $this
->getSettings();
$isLabelEnabled = $settings['day_format'] != 'none';
$isTimeSlotEnabled = TRUE;
$isCommentEnabled = $this
->getFieldSetting('comment');
$table_rows = [];
$office_hours = $this
->getRows($items
->getValue(), $this
->getSettings(), $this
->getFieldSettings());
foreach ($office_hours as $delta => $item) {
$table_rows[$delta] = [
'data' => [],
'no_striping' => TRUE,
'class' => [
'office-hours__item',
],
];
if ($isLabelEnabled) {
$table_rows[$delta]['data']['label'] = [
'data' => [
'#markup' => $item['label'],
],
'class' => [
'office-hours__item-label',
],
'header' => !$isCommentEnabled,
];
}
if ($isTimeSlotEnabled) {
$table_rows[$delta]['data']['slots'] = [
'data' => [
'#markup' => $item['formatted_slots'],
],
'class' => [
'office-hours__item-slots',
],
];
}
if ($isCommentEnabled) {
$table_rows[$delta]['data']['comments'] = [
'data' => [
'#markup' => $item['comments'],
],
'class' => [
'office-hours__item-comments',
],
];
}
}
$table = [
'#theme' => 'table',
'#attributes' => [
'class' => [
'office-hours__table',
],
],
'#rows' => $table_rows,
'#attached' => [
'library' => [
'office_hours/office_hours_formatter',
],
],
];
if ($isCommentEnabled) {
if ($isLabelEnabled) {
$table['#header'][] = [
'data' => $this
->t('Day'),
'class' => 'visually-hidden',
];
}
$table['#header'][] = [
'data' => $this
->t('Time slot'),
'class' => 'visually-hidden',
];
$table['#header'][] = [
'data' => $this
->t('Comment'),
'class' => 'visually-hidden',
];
}
$elements[] = [
'#theme' => 'office_hours_table',
'#table' => $table,
'#office_hours' => $office_hours,
'#cache' => [
'max-age' => $this
->getStatusTimeLeft($items, $langcode),
'tags' => [
'office_hours:field.table',
],
],
];
if ($settings['schema']['enabled']) {
$elements[0] = $this
->addSchemaFormatter($items, $langcode, $elements[0]);
}
if ($settings['current_status']['position'] != "") {
$elements = $this
->addStatusFormatter($items, $langcode, $elements);
}
return $elements;
}
}