1
$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?

2

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']);
  • how can we limit the list of block here. – Maneesh Mehta May 24 '18 at 7:41
0

Try this:

$blocks = Drupal\block\Entity\Block::loadMultiple();
ksm($blocks);
0

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
$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, privacy policy and cookie policy

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