Last active
May 11, 2021 12:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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