Score:0

Update node and all translations programmatically

gu flag

I need to add tags as taxonomy terms to already created nodes in 7 languages.

If I do this:

$node = Node::load($nid);
$node->set('field_tags', getTerms($terms));
$node->save();

Just default node in English is updated, however, all terms are created in all languages.

getTerms() - is my own function, which is getting term ids and creating them if they don't exist.

I need to update all node translations. But how?

Tried this:

foreach (getLanguages() as $key => $value) {
  $node_translation = $node->addTranslation($key, $node->toArray());
  $node_translation->set('field_tags', getTerms($terms));
  $node_translation->save();
}

Gives me this error: [error] Invalid translation language (ru) specified. But 'ru' language is active.

getLanguages() - return array of all languages. The same function is used to create nodes and terms and it's working fine there.

How to update a node and all its translations?

4uk4 avatar
cn flag
Can you add the location where the error is raised and the stack trace down to the point where it connects with your code? You want to update translations when your code is adding translations. How did you configure the reference field and the vocabulary? Are both translatable?
Score:0
gu flag

Finally found the right solution to update node translation programmatically:

if ($node->hasTranslation($key)) {
  $translation = $node->getTranslation($key);
  $translation->set('field_tags', $terms);
  $translation->save();
}

$key - language tag, for example 'en', 'es', 'ru', etc.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.