In this blog post, we will provide a comprehensive guide on how to get the translated node programmatically in Drupal 10. With the increased demand for multilingual websites, understanding how to work with translations in Drupal is crucial. We will walk you through the process step-by-step, providing code examples and best practices to help you implement translations effectively in your Drupal 10 project.
Table of Contents
Prerequisites
Before diving into the code, make sure you have the following prerequisites in place:
- Drupal 10 installed and configured
- Multilingual support enabled
- At least two languages installed and configured
- A content type with translated nodes
Load a Node
First, we need to load a node in Drupal. We can do this using the load()
method of the Node
class. Here's an example:
// Load a node with the ID of 1.
$node = \Drupal\node\Entity\Node::load(1);
Get the Translated Node Programmatically
To get the translated node programmatically, you can use the getTranslation()
method. You'll need to provide the target language code as an argument:
// Get the translated node in French (assuming the language code is 'fr').
$translated_node = $node->getTranslation('fr');
If you're unsure about the target language code, you can retrieve it from the user's language preference using the following code:
// Get the user's preferred language code.
$language_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
Working Example
Here's a full working example to demonstrate how to get the translated node programmatically in Drupal 10:
// Load a node with the ID of 1.
$node = \Drupal\node\Entity\Node::load(1);
// Get the user's preferred language code.
$language_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
// Check if the node has a translation in the user's preferred language.
if ($node->hasTranslation($language_code)) {
// Get the translated node.
$translated_node = $node->getTranslation($language_code);
// Output the title of the translated node.
$translated_title = $translated_node->getTitle();
print $translated_title;
} else {
// Output a message if no translation is available.
print "No translation available for the node in the preferred language.";
}