How to Translate a String Programmatically In Drupal

When you need to translate a string in different environments and want to automate it

Sergio Guardiola Herrador
2 min readAug 2, 2024
Photo by Bastian Riccardi on Unsplash

When you need to translate a string in Drupal is very easy, normally you head to /admin/config/regional/translate and translate it.

While this takes less than a minute to do for a string, what happens if you need to do the same for many strings and/or environments? Ideally, you’d want to automate this in that case, so you only have to do it once and once it’s deployed on each environment it’ll be done automatically.

To do so, you just need a custom module. In my case, my custom module is called administration and I only need two files:

  • administration.install
  • administration.module

This will be the function that we will call from the install file and this needs to be placed in the administration.module file:

use Drupal\locale\SourceString;

/**
* Helper function for adding translations.
*
* @param array $strings
* The array with strings and their translations.
*/
function _administration_add_translations(array $strings) {
$storage = \Drupal::service('locale.storage');

foreach ($strings as $translation) {
try {
$string = $storage->findString(['source' => $translation['label']]);
if (is_null($string)) {
$string = new SourceString();
$string->setString($translation['label']);
$string->setStorage($storage);
$string->save();
}
foreach ($translation['translations'] as $langcode => $string_translation) {
$storage->createTranslation([
'lid' => $string->lid,
'language' => $langcode,
'translation' => $string_translation,
])->save();
}
}
catch (Exception $e) {
\Drupal::logger('administration')->warning('String @s: @e on line @l could not be found', [
'@s' => $translation['label'],
'@e' => $e->getMessage(),
'@l' => $e->getLine(),
]);
}
}
}

Then, on administration.install, we create our hook_update and call the function passing the values:

/**
* Implements hook_update_N().
*/
function administration_update_9001() {
// Create translations programmatically.
$translations = [
[
'label' => 'Owner of the rights of use',
'translations' => [
'es' => 'Propietario de los derechos de uso',
],
],
];
// Add the translations.
_administration_add_translations($translations);
}

And that’s all, the translations will be created automatically on each environment where your code is deployed.

👉 Find out more about me here: https://sergioguardiola.net 🔥

--

--

Sergio Guardiola Herrador
Sergio Guardiola Herrador

Written by Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net

No responses yet