0

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?

1
  • 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?
    – 4uk4
    Nov 21, 2021 at 16:53

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.