Cómo Traducir Un Texto Automáticamente En Drupal

Cuando necesitas traducir un texto en diferentes entornos y quieres automatizarlo

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

Cuando necesitas traducir un texto en Drupal es muy fácil, normalmente vas a /admin/config/regional/translate y lo traduces.

Si bien esto lleva menos de un minuto para un texto, ¿qué sucede si necesitas hacer lo mismo para muchos textos o entornos? Lo ideal sería automatizarlo en ese caso, de modo que solo tengas que hacerlo una vez y, una vez que se implemente en cada entorno, se realizará automáticamente.

Para ello, solo necesitas un módulo personalizado. En mi caso, mi módulo personalizado se llama administration y solo necesito dos archivos:

  • administration.install
  • administration.module

Esta será la función que llamaremos desde el fichero install y debe colocarse en el archivo administration.module:

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(),
]);
}
}
}

Luego, en administration.install, creamos nuestro hook_update y llamamos a la función pasando los valores:

/**
* 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);
}

Y eso es todo, las traducciones se crearán automáticamente en cada entorno donde se implemente tu código..

👉 Descubre más sobre mi aquí: https://sergioguardiola.net 🔥

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

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

Write a response