Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save keopx/19cc87ca327b99dbe555a6433d31eeaa to your computer and use it in GitHub Desktop.
Save keopx/19cc87ca327b99dbe555a6433d31eeaa 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment