On a project I just discovered I had to make a change to both how some blocks were configured, but also remove access to some other blocks (with the module Layout builder restrictions). This is a somewhat disruptive change. Even though the editors are not supposed to need or want to use any of the blocks I was going to do disruptive changes to, I had to make sure I was not sabotaging their work somehow. So I wanted to find out what blocks and layouts were actually used on the different pages built with Layout builder.
So I wrote a simple query to find them all, and print them to my console. I then realized this might be handy to have for later. Or heck, maybe it is even handy for other people. Let's just throw it on the blog. It looks like this:
<?php
use Drupal\node\Entity\Node;
$rows = \Drupal::database()
->select('node__layout_builder__layout', 'ns')
->fields('ns', ['entity_id'])
->groupBy('ns.entity_id')
->execute();
$types = [];
$layouts = [];
foreach ($rows as $row) {
/** @var \Drupal\node\Entity\Node $node */
$node = Node::load($row->entity_id);
if (!$node) {
continue;
}
if (!$node->hasField('layout_builder__layout') || $node->get('layout_builder__layout')->isEmpty()) {
continue;
}
$layout = $node->get('layout_builder__layout')->getValue();
foreach ($layout as $item) {
/** @var \Drupal\layout_builder\Section $section */
$section = $item['section'];
$layouts[$section->getLayoutId()] = TRUE;
$section_array = $section->toArray();
foreach ($section_array["components"] as $delta => $component) {
$id = $component["configuration"]["id"];
if (in_array($id, $types)) {
continue;
}
$types[] = $id;
}
}
}
print_r($types);
print_r(array_keys($layouts));
This will now give me the plugin IDs of all of the blocks used on a layout builder page, along with all the layout IDs being used on a layout builder page.
Now I can do disruptive changes without worrying about actually disrupting the work for editors.
Disclaimer: This does not take into account any unsaved work any editors have in their layout. If you have a very active site with very active editors, you might want to add that into the mix. But that is left as an exercise to the reader.
Hope that is useful to someone else. I know I will use it myself later. But if not, here is a useful GIF about it being summer soon (for me anyway).