How do I get a field translated in Drupal 8

by rpayanm   Last Updated December 19, 2017 12:07 PM

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.



Answers 2


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():

 $translation = \Drupal::service('entity.repository')->getTranslationFromCon‌​text($entity);
Berdir
Berdir
January 29, 2015 00:01 AM

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;
estoyausente
estoyausente
February 03, 2016 10:00 AM

Related Questions



How to translate Entityform type name

Updated August 09, 2016 09:03 AM

Entity Translation for custom entity

Updated March 24, 2017 16:07 PM