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

3

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']);
| improve this answer | |
  • 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);
| improve this answer | |
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);
| improve this answer | |
  • 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? – Sonam Singh May 18 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

| improve this answer | |

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.