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