Skip to content

Instantly share code, notes, and snippets.

@Erikdekamps
Last active June 6, 2023 07:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Erikdekamps/8f87c5781c4f0478d4b41e03d5ab08a6 to your computer and use it in GitHub Desktop.
Save Erikdekamps/8f87c5781c4f0478d4b41e03d5ab08a6 to your computer and use it in GitHub Desktop.
Drupal 8 - Programmatically translate strings via hook_update_N()
/**
* Helper function for adding translations.
*
* @param array $strings
* The array with strings and their translations.
*/
function _my_module_add_translations(array $strings) {
// Get locale storage service.
$storage = \Drupal::service('locale.storage');
// Loop through the translations.
foreach ($strings as $translation) {
// Find the source string.
try {
$string = $storage->findString(['source' => $translation['label']]);
if (is_null($string)) {
$string = new SourceString();
$string->setString($translation['label']);
$string->setStorage($storage);
$string->save();
}
// Create translation. If one already exists, it will be replaced.
foreach ($translation['translations'] as $langcode => $string_translation) {
$storage->createTranslation([
'lid' => $string->lid,
'language' => $langcode,
'translation' => $string_translation,
])->save();
}
}
catch (Exception $e) {
\Drupal::logger('my_module')->warning('Error trying to find string @s: @e on line @l', [
'@s' => $translation['label'],
'@e' => $e->getMessage(),
'@l' => $e->getLine(),
]);
}
}
}
/**
* Add translations.
*/
function my_module_update_8001() {
// Add the translations.
$translations = [
[
'label' => 'An example',
'translations' => [
'nl' => 'Een voorbeeld',
],
],
];
// Add the translations.
_my_module_add_translations($translations);
}
@renatog-cit
Copy link

Very good man! thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment