I have a programmatical plugin block defined in theme region. I need to check access to this block in my module hook. The following code creates a new instance, but I need to load an existing plugin block from the theme with its custom visibility settings and find out if it is going to be displayed or not.

$block_manager = \Drupal::service('plugin.manager.block');
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
$access_result = $plugin_block->access(\Drupal::currentUser());

Please advise.

1 Answer 1


Loading a block should be in theme context, because block visibility configured by theme, here is an example to how load system_breadcrumb_block block in your active theme.

   use Drupal\block\Entity\Block;  
    // Get block ids.
        // This will return block ids by theme like the following
        /*  [
              "bartik_breadcrumbs" => "bartik_breadcrumbs"
              "seven_breadcrumbs" => "seven_breadcrumbs"
        $ids = \Drupal::entityQuery('block')
          ->condition('plugin', 'system_breadcrumb_block')
        // Get the active theme name.
        $active_theme_name = \Drupal::service('theme.manager')
        $my_block_id = '';
        foreach ($ids as $id) {
          // Check the if the id start with theme name.
          if (strpos($id, $active_theme_name) === 0) {
            $my_block_id = $id;
        // Load Block.
        $block = Block::load($my_block_id);
        // Get the block visibility array
        // Something like
        //    [
        //      "user_role" => [
        //        "id"    => "user_role",
        //        "roles" => [
        //          "administrator" => "administrator",
        //        ],
        //      ],
        //    ]
        $visibility = $block->getVisibility();
        $currentUser = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
         * TODO: Do your visibility check
        // Example to check if the user has the access by role
        $has_access = FALSE;
        if ($visibility['user_role']['roles']){
          foreach ($visibility['user_role']['roles'] as $role => $name){
            if ($currentUser->hasRole($role)){
              $has_access = TRUE;
  • Thank you for the reply. I see that in this case block access is checked by using visibility values. I have implemented my own way of checking access for the request_path and other properties from visibility array, but I wonder if there is some internal Drupal method to check this all at once.
    – JetSet
    Commented Oct 31, 2019 at 17:19
  • You can also check $block->access ($acciunt)
    – berramou
    Commented Oct 31, 2019 at 18:08

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.