Error: Call to a member function getRegion() on null in bootstrap5_preprocess_block()

Created on 1 February 2023, almost 2 years ago
Updated 6 February 2023, almost 2 years ago

Problem/Motivation

When Bootstrap5 und subtheme is enabled and I land on a page with a fixed block, I get this error:
Error: Call to a member function getRegion() on null in bootstrap5_preprocess_block() (line 294 of themes/contrib/bootstrap5/bootstrap5.theme).
The issue lies in the block not being loaded (NULL):

$block = Block::load($variables['elements']['#id'])

I think its ID comes in a different format.

function bootstrap5_preprocess_block(&$variables) {
  if (isset($variables['elements']['#id'])) {
    $region = Block::load($variables['elements']['#id'])->getRegion();
    if (!empty($region)) {
      $variables['content']['#attributes']['data-block']['region'] = $region;
    }
  }
}

Steps to reproduce

  1. Upgrade to Drupal 9.5.2.
  2. Enable Bootstrap5 3.0.0 and subtheme.
  3. Use Context module to place blocks in regions.
  4. Go to page with the context regions and blocks.

Proposed resolution

Wrapping the code in bootstrap5_preprocess_block() in bootstrap5.theme with a simple check sorts the issue.

function bootstrap5_preprocess_block(&$variables) {
  If ($block = Block::load($variables['elements']['#id'])) {
    if (isset($variables['elements']['#id'])) {
      $region = Block::load($variables['elements']['#id'])->getRegion();
      if (!empty($region)) {
        $variables['content']['#attributes']['data-block']['region'] = $region;
      }
    }
  }
}
🐛 Bug report
Status

Fixed

Version

3.0

Component

Code

Created by

🇺🇸United States nsuit

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024