Drupal 8: Import translations on profile or module installation

Submitted by Peter Majmesku on Fri, 06/01/2018 - 23:11

I wrote this simple function for the deGov installation profile. Drupal handles here the PHP standard object and not the Drupal File object. That fact can be misleading.

function degov_import_translations(): void {
  
$file = new \stdClass();
  
$file->uri drupal_get_path('profile''degov') . '/translations/de-de.po';
  
$file->langcode 'de';

  \
Drupal\locale\Gettext::fileToDatabase($file, [
    
'overwrite_options' => [
      
'not_customized' => TRUE,
    ],
  ]);
}
 

The .po file contents with filename "de-de.po" looked like this:

msgid ""
msgstr ""
"Project-Id-Version: deGov\n"
"Language-Team: German\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n!=1);\n"

msgid "Social Media Settings"
msgstr "Social Media Einstellungen"