Programmatically adding block into layout builder layout?

cn flag

I'm trying to add a block into a layout builder, but it seems the 'getSections' for a node which is currently at the default layout does not output anything, not sure if it's a bug or if that's intended behaviour... getSections will only output items if the layout for the node has deviated fromt he default...


 $entity = \Drupal::entityTypeManager()->getStorage('node')->load('127');
 $layout = $entity->get('layout_builder__layout');
 $sections = $layout->getSections();
 dpm($sections, 'sections'); 

$sections will be empty unless that node has had it's layout that normal behaviour?? seems like a bug, shouldn't the default sections still be outputted?

berliner avatar
bd flag
Welcome to Drupal answers! The title of your question is different to what you are asking in the question. We have a "one post - one question" policy on this site. Can you please decide what your question should be and add the relevant details for that actual question (you can edit your post)? That way you will hugely increase your chances of getting a qualified answer.
bd flag

Until a nodes layout has been overridden, no layout is stored in the node field layout_builder__layout (better use OverridesSectionStorage::FIELD_NAME actually). That is by design and makes a lot of sense if you think about it.

To get the configured sections that make up the layout of a node, be it the default layout or an overridden one, is to use the section storage for a given entity.

$section_storage = $this->getSectionStorageForEntity($node);
$sections = $section_storage->getSections();

The method getSectionStorageForEntity comes from the LayoutEntityHelperTrait.


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.