View source
<?php
namespace Drupal\commerce_wishlist\Plugin\Field\FieldFormatter;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class WishlistPurchaseDefaultFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
protected $dateFormatter;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatterInterface $date_formatter) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->dateFormatter = $date_formatter;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container
->get('date.formatter'));
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [
'#type' => 'table',
'#caption' => $this
->t('Purchases'),
'#header' => [
$this
->t('Order ID'),
$this
->t('Quantity'),
$this
->t('Purchased'),
],
'#cache' => [
'contexts' => [
'languages:' . LanguageInterface::TYPE_INTERFACE,
],
],
];
foreach ($items as $item) {
$purchase = $item
->toPurchase();
$elements['#rows'][] = [
$purchase
->getOrderId(),
$purchase
->getQuantity(),
$this->dateFormatter
->format($purchase
->getPurchasedTime()),
];
}
return $elements;
}
}