View source
<?php
namespace Drupal\country_state_city\Plugin\Field\FieldFormatter;
use Drupal\Component\Utility\Html;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContryStateCityFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
protected $entityTypeManager;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entityTypeManager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->entityTypeManager = $entityTypeManager;
}
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 static function defaultSettings() {
return [] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
return [] + parent::settingsForm($form, $form_state);
}
public function settingsSummary() {
$summary = [];
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$values = $item
->getValue();
$country = $this->entityTypeManager
->getStorage('countrylist')
->load($values['country']);
$state = $this->entityTypeManager
->getStorage('statelist')
->load($values['state']);
$city = $this->entityTypeManager
->getStorage('citylist')
->load($values['city']);
$elements[$delta] = [
'#markup' => $this
->viewValue($item),
'#theme' => 'country_state_city',
'#country' => !is_null($country) ? !empty($country
->hasTranslation($langcode)) ? $country
->getTranslation($langcode)
->getName() : $country
->getName() : '',
'#state' => !is_null($state) ? !empty($state
->hasTranslation($langcode)) ? $state
->getTranslation($langcode)
->getName() : $state
->getName() : '',
'#city' => !is_null($city) ? !empty($city
->hasTranslation($langcode)) ? $city
->getTranslation($langcode)
->getName() : $city
->getName() : '',
];
}
return $elements;
}
protected function viewValue(FieldItemInterface $item) {
return nl2br(Html::escape($item->countrylist));
}
}