3 namespace Drupal\views\Entity\Render;
5 use Drupal\Core\Language\LanguageInterface;
6 use Drupal\views\Plugin\views\query\QueryPluginBase;
7 use Drupal\views\ResultRow;
10 * Renders entity translations in their row language.
12 class TranslationLanguageRenderer extends EntityTranslationRendererBase {
15 * Stores the field alias of the langcode column.
19 protected $langcodeAlias;
24 public function query(QueryPluginBase $query, $relationship = NULL) {
25 // In order to render in the translation language of the entity, we need
26 // to add the language code of the entity to the query. Skip if the site
27 // is not multilingual or the entity is not translatable.
28 if (!$this->languageManager->isMultilingual() || !$this->entityType->hasKey('langcode')) {
31 $langcode_key = $this->entityType->getKey('langcode');
32 $storage = \Drupal::entityManager()->getStorage($this->entityType->id());
34 if ($table = $storage->getTableMapping()->getFieldTableName($langcode_key)) {
35 $table_alias = $query->ensureTable($table, $relationship);
36 $this->langcodeAlias = $query->addField($table_alias, $langcode_key);
43 public function preRender(array $result) {
44 $view_builder = $this->view->rowPlugin->entityManager->getViewBuilder($this->entityType->id());
46 /** @var \Drupal\views\ResultRow $row */
47 foreach ($result as $row) {
48 $entity = $row->_entity;
49 $entity->view = $this->view;
50 $langcode = $this->getLangcode($row);
51 $this->build[$entity->id()][$langcode] = $view_builder->view($entity, $this->view->rowPlugin->options['view_mode'], $this->getLangcode($row));
58 public function render(ResultRow $row) {
59 $entity_id = $row->_entity->id();
60 $langcode = $this->getLangcode($row);
61 return $this->build[$entity_id][$langcode];
67 public function getLangcode(ResultRow $row) {
68 return isset($row->{$this->langcodeAlias}) ? $row->{$this->langcodeAlias} : $this->languageManager->getDefaultLanguage()->getId();
74 public function getCacheContexts() {
75 return ['languages:' . LanguageInterface::TYPE_CONTENT];