1

I am translating the nodes programmatically. Everything works fine except the layout builder blocks.

When I try to translate it, it also changes on the source node.

I have created a node in language en. Now I am translating it to nl. Here is my code.

if ($node->hasTranslation($language)) {
  $translated_entity =  $node->getTranslation($language);
}
else {
  $translated_entity =  $entity->addTranslation($language);
}

$translated_layout = $node->get('layout_builder__layout')->getValue();

foreach ($translated_layout as $section) {
  /** @var \Drupal\layout_builder\Section $section */
  $section = reset($section);

  foreach ($section->getComponents() as $component) {
    $configuration = $component->get('configuration');

    $component->setConfiguration($translated_configurations);
  }
}

$translated_entity->set('layout_builder__layout', $translated_layout);
$translated_entity->save();
$node->save();

Is there any way to retain the original blocks as it is on the source node and the save function only added the changes to the translated node?

1
  • Is there a reason why you're doing this translation programmatically?
    – Joseph
    Nov 10 at 14:48
0

I have done it myself. Here is the solution.

You first need to copy the layout from the source node to the translated node.

Then get the layout of the translated node and translate it.

if ($node->hasTranslation($language)) {
  $translated_entity =  $node->getTranslation($language);
}
else {
  $translated_entity =  $entity->addTranslation($language);
}

$translated_entity->set('layout_builder__layout', $node->get('layout_builder__layout')->getValue());
$translated_entity->save();

$translated_layout = $translated_entity->get('layout_builder__layout')->getValue();

foreach ($translated_layout as $section) {
  /** @var \Drupal\layout_builder\Section $section */
  $section = reset($section);

  foreach ($section->getComponents() as $component) {
    $configuration = $component->get('configuration');

    $component->setConfiguration($translated_configurations);
  }
}

$translated_entity->set('layout_builder__layout', $translated_layout);     
$node->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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