7

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.

20

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);
  • 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 '15 at 0:47
  • 3
    entityManager is deprecated. use \Drupal::service('entity.repository')->getTranslationFromContext($entity); instead – Philipp Michael Apr 11 '16 at 17:59
  • 1
    This is not working giving me undefined error. Can you paste the latest code. – Fazeela Abu Zohra Dec 26 '16 at 12:41
  • @PhilippMichael – Updated answer. – leymannx Dec 20 '17 at 21:23
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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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