8

I have a multilingual site in Drupal 8, and several node, some translated and others not. As I can programmatically get the translated field or by default they give it back from the original language.

I got this:

$service_entities = entity_load_multiple_by_properties('node', array('type' => 'service'));

$services = [];
foreach ($service_entities as $entity) {
  $services[] = [
    'title' => $entity->title->value,
  ];
}

This code work fine, but when the title is translated Drupal give back in the default language in which it was created.

2 Answers 2

30

You can get a specific translation with $translation = $entity->getTranslation('de'), then you can use $translation exactly the same as $entity.

Usually, you don't want to get a specific translation, but the best translation that is available for the current language. For that, use getTranslationFromContext() like this:

 $translation = \Drupal::service('entity.repository')->getTranslationFromContext($entity);
5
  • 1
    @Bedir the last code(getTranslationFromContext) when I'm logged translations work well, but when I logout not working, you know why this happens?
    – rpayanm
    Jan 30, 2015 at 0:47
  • 3
    entityManager is deprecated. use \Drupal::service('entity.repository')->getTranslationFromContext($entity); instead Apr 11, 2016 at 17:59
  • 1
    This is not working giving me undefined error. Can you paste the latest code. Dec 26, 2016 at 12:41
  • @PhilippMichael – Updated answer.
    – leymannx
    Dec 20, 2017 at 21:23
  • And $translation->getTitle() will return the translated version then ?
    – john Smith
    Mar 4, 2022 at 12:32
5

Loading all help_page and return it in the current language:

$elements = [];
$ids = \Drupal::entityQuery('node')
  ->condition('type', 'help_page')
  ->execute();
$nodes = Node::loadMultiple($ids);
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

foreach ($nodes as $node) {
  $translation = $node->getTranslation($language);
  $elements[] = [
    'title' => $translation->title->value,
    'url' => $translation->url(),
    'img' => $translation->field_imagen->entity->url(),
    'text' => $translation->body->value,
  ];
}
return $elements;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.