Last active
June 6, 2023 07:40
-
-
Save Erikdekamps/8f87c5781c4f0478d4b41e03d5ab08a6 to your computer and use it in GitHub Desktop.
Drupal 8 - Programmatically translate strings via hook_update_N()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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
Very good man! thanks