Score:1

How to translate the layout builder blocks of a node programmatically?

kr flag

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?

in flag
Is there a reason why you're doing this translation programmatically?
Score:0
kr flag

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();
wranvaud avatar
us flag
What are you doing in the foreach loops? The `$configuration` variable is not used?
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.