Skip to main content

Drupal 9: Make a string programmaticaly translatable

Working with string translations in Drupal can sometimes be challenging. However, in Drupal 9+, the process is relatively straightforward and user-friendly.

Here is a quick snippet on how to find if there is a translation of a string and replace it with its translated text.

use Drupal\locale\SourceString;

    $source_string = $some_text_variable;
    $storage = \Drupal::service('locale.storage');
    $string = $storage->findString(['source' => $source_string]);
    if (is_null($string)) {
      $string = new SourceString();
      $string->setString($source_string);
      $string->setStorage($storage);
      $string->save();
    }

    // Check if translation exists and update the text.
    $translation = $storage->findTranslation(['source' => $source_string]);
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    if ($translation instanceof \Drupal\locale\TranslationString && $translation->language === $language) {
       $some_text_variable = $translation->translation;

    }

 

translation php

Latest Articles

VSCode Drupal Coding Standards Setup (From Scratch) admin_pixelthi… Mon, 12/22/2025 - 16:01 VSCode Drupal Coding Standards Setup (From Scratch)

VSCode Drupal Coding Standards Setup (From Scratch)

vscode
Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter