In Drupal 8, is there a way to figure out what current block or view machine name you should use?

For example, with the following code, I noticed that 'machine_name_to_determine' could change depending on how many times you have used your block.

$block_id = 'machine_name_to_determine';
$block_config = \Drupal\block\Entity\Block::load($block_id);

I need a way to retrieve this at run-time. How can I retrieve it?


You can query the blocks by the plugin id. This is the id of a block plugin or for derivatives like a view block (which you probably are looking for as you've mentioned a view machine name) with additional parameters:

$plugin_id = 'views_block:' . $view_id . '-' . $display_id;

Where $view_id is the view machine name which you find in the Views UI and $display_id is the display machine name, usually block_1 for the first block of the view.

Then get all blocks placed for this plugin id and print the block machine names or use the loaded blocks in your code:

$blocks = \Drupal::entityTypeManager()->getStorage('block')
  ->loadByProperties(['plugin' => $plugin_id]);
foreach ($blocks as $block) {
  echo $block->id();

Add a theme or region to loadByProperties() if needed:

['theme' => 'bartik', 'region' => 'header']
  • Thanks 4k4 for your response and that has actually given me the right nodge to the answer i need. – afro-Nija Oct 19 '17 at 10:08

This is in accordance to the pointer by @4k4

$plugin_id = 'bookingsystem_block';
$block_id = $this->getCurrentBlockId($plugin_id);
protected function getCurrentBlockId($plugin_id)
    $block_id = NULL;

    $blocks = \Drupal::entityTypeManager()->getStorage('block')
        ->loadByProperties(['plugin' => $plugin_id]);

    $current_route_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    foreach ($blocks as $block)
        $visibility = $block->getVisibility();
        $request_path = $visibility['request_path'];
        $request_path_url_arr = explode("\r\n", $request_path['pages']);

        $node_url_arr = array();

        foreach ($request_path_url_arr as $path_alias)
            $path = \Drupal::service('path.alias_manager')->getPathByAlias($path_alias);
            if(preg_match('/node\/(\d+)/', $path, $matches)) {
                $node_url_arr[] = $path;
            else if($path_alias=='<front>') {
                $node_url_arr[] = '/';

        $request_path_url_arr = array_merge($request_path_url_arr,$node_url_arr);

            $block_id = $block->id();

    return $block_id;

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.