Skip to content

Instantly share code, notes, and snippets.

@achraf-jeday
Last active May 11, 2021 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achraf-jeday/240ed6f6855e25b2fe047f83a36c02a6 to your computer and use it in GitHub Desktop.
Save achraf-jeday/240ed6f6855e25b2fe047f83a36c02a6 to your computer and use it in GitHub Desktop.
Drupal 8: How to load available translations of a given node, change some fields and save.
<?php
// Credit to Gábor Hojtsy
// http://hojtsy.hu/blog/2015-nov-11/drupal-8-multilingual-tidbits-19-content-translation-development
use Drupal\node\Entity\Node;
// Load node 4. In terms of language, this will get us an entity
// in the original submission language.
$node = Node::load(4);
// Get a list of all translations and collect titles.
$titles = [];
$languages = $node->getTranslationLanguages();
foreach ($languages as $langcode => $language) {
// The object returned by getTranslation() behaves the same way as $node.
$translation = $node->getTranslation($langcode);
$titles[$langcode] = $translation->title;
}
// If the node has no Hungarian translation, add one.
if (!$node->hasTranslation('hu')) {
$translation = $node->addTranslation('hu', array('title' => 'Hungarian title'));
$translation->save();
}
// If the node has a Spanish translation, update the title. In case of a missing
// Spanish translation this will throw an InvalidArgumentException.
$node->getTranslation('es')->setTitle('Spanish title')->save();
// Remove the Hungarian translation.
$node->removeTranslation('hu');
$node->save();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment