Email us at info@henrytech.org to discuss your Drupal Migration today!
In the case that you have a field on a node that you have some data in, and you wish to add this to the layout builder of the page programmatically, here is how to do so, with a landing page type node that has a field called 'field_accordion':
use Drupal\node\Entity\Node; use Drupal\layout_builder\Plugin\SectionStorage\OverridesSectionStorage; use Drupal\layout_builder\Section; use Drupal\layout_builder\SectionComponent; use Drupal\layout_builder\SectionListTrait; // First load your node $nid = '441'; $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid); // Get sections of layout builder $layoutBuilder = $node->get(OverridesSectionStorage::FIELD_NAME); $sections = $layoutBuilder->getSections(); $section = $sections[0]; // Add field of node to layout builder, in this case, the field is 'field_accordion' that already exists in the node $newBlockConfig = [ "id" => "field_block:node:landing_page:field_accordion", "label" => "Accordion", "label_display" => 0, "provider" => "layout_builder", "formatter" => [ "label" => "above", "type" => "entity_reference_revisions_entity_view", "settings" => [ "view_mode" => "default", ], "third_party_settings" => [], ], "context_mapping" => [ "entity" => "layout_builder.entity", "view_mode" => "view_mode", ], ]; // Create a new section component using the node and plugin config. $component = new SectionComponent($node->uuid(), 'second', $newBlockConfig); // Add the component to the section. $section->appendComponent($component); // Set the sections. $node->layout_builder__layout->setValue($sections); // Save the node. $node->save();
Comments