Drupal - How do I get a field translated in Drupal 8
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')->getTranslationFromContext($entity);
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;