Jan 08, 2020 in Drupal 8, Snippets

String translations are always a bit a pain in the ass for drupal. Luckily, in drupal 8 the function is rather easy. 

use \Drupal\locale\SourceString;

function MYMODULE_auto_string_translation($source_string, $translated_string, $langcode) {
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(array('source' => $source_string));
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }
  // If exists, replace
  $translation = $storage->createTranslation(array(
    'lid' => $string->lid,
    'language' => $langcode,
    'translation' => $translated_string,
  ))->save();
}

Then, you can use the function in your mymodule_install() function:

MYMODULE_auto_string_translation(
  '<p>This is a one-time login for %user_name.</p><p>Click on this button to log in to the site and change your password.</p>',
  '<p>Je account is nu bevestigd. Via de knop hieronder kan je inloggen en je wachtwoord instellen.</p>',
  'nl'
);

Credits to this author on StackOverflow