View source
<?php
namespace Drupal\price\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityTypeManagerInterface;
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 PricePlainFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
protected $currencyStorage;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->currencyStorage = $entity_type_manager
->getStorage('price_currency');
}
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('entity_type.manager'));
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$currency_codes = [];
foreach ($items as $delta => $item) {
$currency_codes[] = $item->currency_code;
}
$currencies = $this->currencyStorage
->loadMultiple($currency_codes);
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#theme' => 'price_plain',
'#number' => $item->number,
'#currency' => $currencies[$item->currency_code],
'#cache' => [
'contexts' => [
'languages:' . LanguageInterface::TYPE_INTERFACE,
'price_country',
],
],
];
}
return $elements;
}
}