7

is there a way (snippet) to programmatically add translations for strings (user interface translation), e.g. in hook_update_N()?

A way in Drupal 7 was http://dropbucket.org/node/323.

/**
 * Helper to manually add a single translation string.
 *
 * After adding strings use locale_clear_cache() for clearing caches.
 */
function locale_add_translation($source, $langcode, $translation, $context = '', $textgroup = 'default') {
  require_once DRUPAL_ROOT . '/includes/locale.inc';

  $report = &drupal_static(__FUNCTION__, array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0));
  _locale_import_one_string_db($report, $langcode, $context, $source, $translation, $textgroup, 'Manual import via helper ' . __FUNCTION__ .'().', LOCALE_IMPORT_OVERWRITE);
}

/**
 * Helper to clear the locale cache.
 */
function locale_clear_cache() {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  // Clear locale cache.
  _locale_invalidate_js();
  cache_clear_all('locale:', 'cache', TRUE);
}

Is there anything like this for Drupal 8?

11

Put the following helper function in your custom module:

use \Drupal\locale\SourceString;

function mymodule_add_translation($source_string, $translated_string, $langcode) {
  // Find existing source string.
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(['source' => $source_string]);
  if (is_null($string)) {
    $string = new SourceString();
    $string
      ->setString($source_string)
      ->setStorage($storage)
      ->save();
  }
  // Create translation. If one already exists, it will be replaced.
  $translation = $storage->createTranslation([
    'lid' => $string->getId(),
    'language' => $langcode,
    'translation' => $translated_string,
  ])->save();
}
1
  • 2
    If i want translate a singular/plural sentence, how I do it?
    – rpayanm
    Jul 24 '19 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.