Get translated text in custom module Drupal 9

A small note on the theme of multi -language sites in Drupal 9. If in the custom module you need to get a translated field of the node or the Taxonomy term can use such a code

$path_args = explode('/', $current_path);

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

if ($path_args[1] == 'product') {
	$pid = $path_args[2];
	$entity_manager = \Drupal::entityTypeManager();
	$product = \Drupal\commerce_product\Entity\Product::load($pid);
	if (!$product->field_category->isEmpty()) {
		$category_id = $product->field_category[0]->target_id;
		$category = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($category_id);
		if ($category->hasTranslation($language)) {
			$translated_term = $category->getTranslation($language);
			$category_title = $translated_term->name->value;
		} else { 
			$category_title = $category->name->value;
		}
	}
}

In this example, we get the code of the current active language of the site. After that, we check whether our category is translated in a variable $category, if so - in $translated_term the translated title of the Taxonomy term is placed, otherwise the not - translated title will be displayed.

By such an example, you can verify the availability of a translation of any field of a node or taxonomy.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.