function EntityRepository::getTranslationFromContext

Same name in other branches
  1. 9 core/lib/Drupal/Core/Entity/EntityRepository.php \Drupal\Core\Entity\EntityRepository::getTranslationFromContext()
  2. 8.9.x core/lib/Drupal/Core/Entity/EntityRepository.php \Drupal\Core\Entity\EntityRepository::getTranslationFromContext()
  3. 11.x core/lib/Drupal/Core/Entity/EntityRepository.php \Drupal\Core\Entity\EntityRepository::getTranslationFromContext()
2 calls to EntityRepository::getTranslationFromContext()
EntityRepository::getActiveMultiple in core/lib/Drupal/Core/Entity/EntityRepository.php
EntityRepository::getCanonicalMultiple in core/lib/Drupal/Core/Entity/EntityRepository.php

File

core/lib/Drupal/Core/Entity/EntityRepository.php, line 94

Class

EntityRepository
Provides several mechanisms for retrieving entities.

Namespace

Drupal\Core\Entity

Code

public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = []) {
    $translation = $entity;
    if ($entity instanceof TranslatableDataInterface && count($entity->getTranslationLanguages()) > 1) {
        if (empty($langcode)) {
            $langcode = $this->languageManager
                ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
                ->getId();
            $entity->addCacheContexts([
                'languages:' . LanguageInterface::TYPE_CONTENT,
            ]);
        }
        // Retrieve language fallback candidates to perform the entity language
        // negotiation, unless the current translation is already the desired one.
        if ($entity->language()
            ->getId() != $langcode) {
            $context['data'] = $entity;
            $context += [
                'operation' => 'entity_view',
                'langcode' => $langcode,
            ];
            $candidates = $this->languageManager
                ->getFallbackCandidates($context);
            // Ensure the default language has the proper language code.
            $default_language = $entity->getUntranslated()
                ->language();
            $candidates[$default_language->getId()] = LanguageInterface::LANGCODE_DEFAULT;
            // Return the most fitting entity translation.
            foreach ($candidates as $candidate) {
                if ($entity->hasTranslation($candidate)) {
                    $translation = $entity->getTranslation($candidate);
                    break;
                }
            }
        }
    }
    return $translation;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.