Is there a function I can use to perform a string translation in hook_update_N()
?
1 Answer
Yes, you can check in the locale module how it's done and replicate to use the same queries like this :
/**
* Translating some pagination strings.
*/
function hook_update_XXXX() {
$translations = array(
'last' => array(
'fr' => 'dernière page',
'en-en' => 'last',
),
'first' => array(
'fr' => 'première page',
'en-en' => 'first',
),
);
foreach ($translations as $string => $values) {
$source = db_query('SELECT lid, source, context, textgroup, location FROM {locales_source} WHERE source = :string', array(':string' => $string))->fetchObject();
if (!$source) {
watchdog('update_hook', 'Translation of string "%string" failed.', array('%string%' => $string));
continue;
}
foreach ($values as $langcode => $translated) {
$translation = db_query('SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language', array(':lid' => $source->lid, ':language' => $langcode))->fetchField();
if (is_string($translation)) {
db_update('locales_target')
->fields(array('translation' => $translated))
->condition('lid', $source->lid)
->condition('language', $langcode)
->execute();
}
else {
db_insert('locales_target')
->fields(array(
'lid' => $source->lid,
'translation' => $translated,
'language' => $langcode,
))
->execute();
}
}
}
}
I'm using such code to update strings in code instead of having to this manually when deploying code. So a simple "drush updb" can do the job for me.
OR as I've found out recently, a faster version exists like this :
/**
* Translating some strings.
*/
function hook_update_X() {
$report = array(
'skips'=> 0,
'updates'=> 0,
'deletes'=> 0,
'additions'=> 0
);
// Translate strings.
_locale_import_one_string_db($report, 'fr', '', 'Your shipping address book is currently empty.', 'Votre carnet d\'adresses de livraison est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);
_locale_import_one_string_db($report, 'fr', '', 'Your billing address book is currently empty.', 'Votre carnet d\'adresses de facturation est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);
// Clear locale cache.
cache_clear_all('locale:', 'cache', TRUE);
}
For Drupal 8, please see this answer : https://drupal.stackexchange.com/a/220608/61138
t()
? It should work on an installed site, otherwise usest()
which is designed for installation. If you don't want to make the choice, useget_t()
to be sure