3
$block = Drupal\block\Entity\Block::load($block_id);
ksm($block);

This code loads only one specific block. But how can I load and display all available blocks?

4 Answers 4

6

Using the service plugin.manager.block we will get all blocks available definition.

$blockManager = \Drupal::service('plugin.manager.block');

$contextRepository = \Drupal::service('context.repository');

// Get blocks definition

$definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());

To get details about one specific block you can use below code.

print_r($definitions['help_block']);
2
  • how can we limit the list of block here. Commented May 24, 2018 at 7:41
  • I wish there was a drush command for that Commented Oct 11, 2022 at 23:25
3

Try this:

$blocks = Drupal\block\Entity\Block::loadMultiple();
ksm($blocks);
1
  • This will help you find all the pluginIds you can then use: function _helper_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) { if($block->getPluginId() === "webform_block"){ dd($block); } } Commented May 1, 2023 at 16:00
1

The core block module using "getFilteredDefinitions" method to list the blocks

$blockManager = \Drupal::service('plugin.manager.block');
$contextRepository = \Drupal::service('context.repository');

// Get blocks definition
$definitions = $blockManager->getFilteredDefinitions('block_ui', $contextRepository->getAvailableContexts());

print_r($definitions);
1
  • Can you please suggest how can we use getFilteredDefinitions to return just the content blocks (the ones created from the Blocks UI) and are visible on a given URL or a content type? Commented May 18, 2020 at 12:13
-2
$query = \Drupal::entityQuery('block_content');
$ids  = $query->execute();

You can also use 'block' instead of 'block_content' to get blocks from code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.