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

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
How to remove a primary tab from the admin menu in drupal 10 admin_pixelthi… Wed, 03/27/2024 - 17:39 How to remove a primary tab from the admin menu in drupal 10

How to remove a primary tab from the admin menu in drupal 10

hook
Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide admin_pixelthi… Tue, 09/05/2023 - 14:18 Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

composer drupal9 drupal10