Skip to content

Instantly share code, notes, and snippets.

@DuaelFr
Created October 4, 2017 08:08
Show Gist options
  • Save DuaelFr/638b7d00b25aeeb288005c04ef430207 to your computer and use it in GitHub Desktop.
Save DuaelFr/638b7d00b25aeeb288005c04ef430207 to your computer and use it in GitHub Desktop.
Hook update to change all content to French in Drupal 8
/**
* Enable language module, delete english and set french as default.
*/
function my_module_update_N() {
\Drupal::service('module_installer')->install(['language']);
// Enable french language and set it as default.
if (NULL === ConfigurableLanguage::load('fr')) {
ConfigurableLanguage::create([
'id' => 'fr',
'label' => 'French',
'direction' => 'ltr',
'weight' => 0,
])->save();
}
\Drupal::configFactory()->getEditable('system.site')->set('default_langcode', 'fr')->save();
// Convert all english entity data to french.
$fsconfigs = FieldStorageConfig::loadMultiple();
$entityTypes = [];
$database = \Drupal::database();
$entityTypeManager = \Drupal::entityTypeManager();
foreach ($fsconfigs as $fsconfig) {
/** @var FieldStorageConfig $fsconfig */
// Ensure fsconfig is translatable, has data and uses the default storage
// (database).
if ($fsconfig->isTranslatable() && $fsconfig->hasData() && !$fsconfig->hasCustomStorage()) {
// Load and save target EntityType for further handling.
$targetEntityTypeId = $fsconfig->getTargetEntityTypeId();
if (!array_key_exists($targetEntityTypeId, $entityTypes)) {
$entityTypes[$targetEntityTypeId] = $entityTypeManager->getDefinition($targetEntityTypeId);
}
// Change langcode in all field tables.
if (empty($entityTypes[$targetEntityTypeId]) || !$entityTypes[$targetEntityTypeId]->isTranslatable()) {
continue;
}
$tables = [
$entityTypes[$targetEntityTypeId]->getBaseTable() . '__' . $fsconfig->getName(),
];
if ($entityTypes[$targetEntityTypeId]->isRevisionable()) {
$tables[] = $entityTypes[$targetEntityTypeId]->getRevisionTable() . '__' . $fsconfig->getName();
}
foreach ($tables as $table) {
$database->update($table)
->fields(['langcode' => 'fr'])
->condition('langcode', 'en')
->execute();
}
}
}
// Convert all english content entities to french.
foreach ($entityTypes as $entityType) {
if (!$entityType->isTranslatable()) {
continue;
}
/** @var \Drupal\Core\Entity\EntityType $entityType */
$tables = [
$entityType->getBaseTable(),
$entityType->getDataTable(),
];
if ($entityType->isRevisionable()) {
$tables[] = $entityType->getRevisionTable();
$tables[] = $entityType->getRevisionDataTable();
}
foreach ($tables as $table) {
$database->update($table)
->fields(['langcode' => 'fr'])
->condition('langcode', 'en')
->execute();
}
}
// Delete english language.
ConfigurableLanguage::load('en')->delete();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment