Skip to content

Instantly share code, notes, and snippets.

@paboden
Created June 15, 2022 02:01
Show Gist options
  • Select an option

  • Save paboden/6c7ee78fcdb7eb68a9347727349866d8 to your computer and use it in GitHub Desktop.

Select an option

Save paboden/6c7ee78fcdb7eb68a9347727349866d8 to your computer and use it in GitHub Desktop.
Drupal 8/9: Get the blocks set to a region, or build selected blocks from a reference field and add them to a region.
// EXAMPLE 1
// Get the blocks normally set to display in a particular region of the active theme.
$block_list = [];
$entity_manager = \Drupal::entityTypeManager();
$block_manager = $entity_manager->getStorage('block');
$theme = \Drupal::theme()->getActiveTheme()->getName();
$region = REGION_NAME; // Set the region you want to get the blocks from.
// Get and load the blocks that are set to a region
$values = ['theme' => $theme, 'region' => $region];
$blocks = $block_manager->loadByProperties($values);
foreach ($blocks as $key => $block) {
// Check that the blocks we pulled are set to actually display for the page.
if ($block->access('view')) {
$block_list[$key] = $entity_manager->getViewBuilder('block')->view($block);
}
}
// EXAMPLE 2
// Get some block id's from a block entity reference field and add them into a region.
if ($sidebar_blocks = $node->get('field_sidebar_blocks')->getValue()) {
foreach ($sidebar_blocks as $delta => $block_info) {
$id = $block_info['target_id'];
$block = $block_manager->load($id);
$block_list[$id] = $entity_manager->getViewBuilder('block')->view($block);
}
// Bring all the system set blocks and the node set blocks together.
$variables['page'][$region] = $block_list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment