function BlockHooks::themeInitialize

Same name and namespace in other branches
  1. 11.x core/modules/block/src/Hook/BlockHooks.php \Drupal\block\Hook\BlockHooks::themeInitialize()

Assigns an initial, default set of blocks for a theme.

This function is called the first time a new theme is installed. The new theme gets a copy of the default theme's blocks, with the difference that if a particular region isn't available in the new theme, the block is assigned to the new theme's default region.

Parameters

string $theme: The name of a theme.

2 calls to BlockHooks::themeInitialize()
BlockHooks::modulesInstalled in core/modules/block/src/Hook/BlockHooks.php
Implements hook_modules_installed().
BlockHooks::themesInstalled in core/modules/block/src/Hook/BlockHooks.php
Implements hook_themes_installed().

File

core/modules/block/src/Hook/BlockHooks.php, line 317

Class

BlockHooks
Hook implementations for block.

Namespace

Drupal\block\Hook

Code

protected function themeInitialize(string $theme) : void {
  $storage = \Drupal::entityTypeManager()->getStorage('block');
  // Initialize theme's blocks if none already registered.
  $has_blocks = $storage->loadByProperties([
    'theme' => $theme,
  ]);
  if (!$has_blocks) {
    $default_theme = \Drupal::configFactory()->get('system.theme')
      ->get('default');
    // Apply only to new theme's visible regions.
    $regions = system_region_list($theme, REGIONS_VISIBLE);
    $default_theme_blocks = $storage->loadByProperties([
      'theme' => $default_theme,
    ]);
    $block_repository = \Drupal::service('block.repository');
    foreach ($default_theme_blocks as $default_theme_block_id => $default_theme_block) {
      if (str_starts_with($default_theme_block_id, $default_theme . '_')) {
        $id = str_replace($default_theme . '_', '', $default_theme_block_id);
      }
      else {
        $id = $default_theme_block_id;
      }
      $id = $block_repository->getUniqueMachineName($id, $theme);
      $block = $default_theme_block->createDuplicateBlock($id, $theme);
      // If the region isn't supported by the theme, assign the block to the
      // theme's default region.
      if (!isset($regions[$block->getRegion()])) {
        $block->setRegion(system_default_region($theme));
      }
      $block->save();
    }
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.