contacts_events-8.x-1.x-dev/modules/printing/src/Plugin/Field/FieldFormatter/PrintLogFormatter.php
modules/printing/src/Plugin/Field/FieldFormatter/PrintLogFormatter.php
<?php
namespace Drupal\contacts_events_printing\Plugin\Field\FieldFormatter;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'ce_print_log_table' formatter.
*
* @FieldFormatter(
* id = "ce_print_log",
* label = @Translation("Table"),
* field_types = {"ce_print_log"}
* )
*/
class PrintLogFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
/**
* The date formatter.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* The user entity storage.
*
* @var \Drupal\user\UserStorageInterface
*/
protected $userStorage;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$formatter = new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings']
);
$formatter->dateFormatter = $container->get('date.formatter');
$formatter->userStorage = $container->get('entity_type.manager')->getStorage('user');
return $formatter;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
if ($items->isEmpty()) {
return [];
}
$table = [
'#type' => 'table',
'#header' => [
'time' => $this->t('Printed at'),
'uid' => $this->t('Printed by'),
],
];
foreach ($items as $delta => $item) {
$row = [
'time' => [],
'uid' => [],
];
$date = DrupalDateTime::createFromFormat('Y-m-d\TH:i:s', $item->time);
$timestamp = $date->getTimestamp();
$formatted_date = $this->dateFormatter->format($timestamp, 'short');
$iso_date = $this->dateFormatter->format($timestamp, 'custom', 'Y-m-d\TH:i:s') . 'Z';
$row['time'] = [
'#theme' => 'time',
'#text' => $formatted_date,
'#html' => FALSE,
'#attributes' => [
'datetime' => $iso_date,
],
'#cache' => [
'contexts' => [
'timezone',
],
],
];
$user = $this->userStorage->load($item->uid);
$row['uid']['#markup'] = $user ? $user->label() : $item->uid;
$table[$delta] = $row;
}
return [$table];
}
}
