8

When I use Node::load(10)->toArray() I see that my module thinks that the current language is English. I have the language key (fr) in the url and when I place \Drupal::languageManager()->getCurrentLanguage()->getId() in my code it says (fr). How can I get Node::load(10) to see the current language the user is using?

When I translate the content type into another language, all translations of the same page seem to have the same id to place into the load function.

3 Answers 3

20

You could try the following:

$lang_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
Node::load(10)->getTranslation($lang_code)->toArray();

Good luck!

4

UPDATED ANSWER:

<?php
use Drupal\Core\Language\LanguageInterface;
use Drupal\node\Entity\Node;
$node = Node::load(10);
$langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
$translation = $node->getTranslation($langcode);
// Now deal with the right language from here on.
?>

Hope this works!

3
  • 1
    In this example $langcode is not a string. It cause me an error. Use '$node->getTranslation($langcode->getId());'
    – Pauleau
    Commented May 13, 2019 at 8:49
  • I second that comment from @Pauleau; getCurrentLanguage() returns an object implementing the LanguageInterface Commented Mar 2, 2020 at 15:45
  • $variables['current_language'] = \Drupal::languageManager()->getCurrentLanguage()->getId(); Commented Jun 10, 2021 at 6:31
4

The easiest way to do it:

$entity_translated = \Drupal::service('entity.repository')->getTranslationFromContext($entity);

This will load according to the UI/content language as it was selected, can be fed with any type of entity (content type, comment, media, etc), and if there's no current language it will provide the fallback language content.

Please note if you use getTranslation it will fail (later on your code) if there's no translation, so you need to check always with hasTranslation and if returns true then and only then you use the getTranslation.

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.