View source
<?php
namespace Drupal\address\Plugin\Field\FieldFormatter;
use CommerceGuys\Addressing\Country\CountryRepositoryInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CountryDefaultFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
protected $countryRepository;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, CountryRepositoryInterface $country_repository) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->countryRepository = $country_repository;
}
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('address.country_repository'));
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$countries = $this->countryRepository
->getList();
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#plain_text' => isset($countries[$item->value]) ? $countries[$item->value] : $item->value,
'#cache' => [
'contexts' => [
'languages:' . LanguageInterface::TYPE_INTERFACE,
],
],
];
}
return $elements;
}
}