View source
<?php
namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LanguageFormatter extends StringFormatter {
protected $languageManager;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings, $entity_manager);
$this->languageManager = $language_manager;
}
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.manager'), $container
->get('language_manager'));
}
public static function defaultSettings() {
$settings = parent::defaultSettings();
$settings['native_language'] = FALSE;
return $settings;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['native_language'] = array(
'#title' => $this
->t('Display in native language'),
'#type' => 'checkbox',
'#default_value' => $this
->getSetting('native_language'),
);
return $form;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($this
->getSetting('native_language')) {
$summary[] = $this
->t('Displayed in native language');
}
return $summary;
}
protected function viewValue(FieldItemInterface $item) {
$languages = $this
->getSetting('native_language') ? $this->languageManager
->getNativeLanguages(LanguageInterface::STATE_ALL) : $this->languageManager
->getLanguages(LanguageInterface::STATE_ALL);
return [
'#plain_text' => $item->language && isset($languages[$item->language
->getId()]) ? $languages[$item->language
->getId()]
->getName() : '',
];
}
}