Skip to content
block.module 13.6 KiB
Newer Older
Dries Buytaert's avatar
 
Dries Buytaert committed
<?php
Dries Buytaert's avatar
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * @file
 * Controls the visual building blocks a page is constructed with.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */

use Drupal\language\ConfigurableLanguageInterface;
use Drupal\block\Entity\Block;
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function block_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.block':
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Block module allows you to place blocks in regions and to configure their settings. For more information, see <a href="!blocks-documentation">the online documentation for the Blocks module</a>.', array('!blocks-documentation' => 'https://drupal.org/documentation/modules/block/')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Placing and moving blocks') . '</dt>';
      $output .= '<dd>' . t('You can place a block by clicking on its title in the <em>Place blocks</em> list on the <a href="!blocks">Block layout page</a>. You can then choose the appropriate region from the <em>Region</em> dropdown menu. Once a block has been placed, it can also be moved to a different region by choosing a region from the <em>Region</em> dropdown menu on the Block layout page, or by dragging and dropping it to the right position.', array('!blocks' => \Drupal::url('block.admin_display'))) . '</dd>';
      $output .= '<dt>' . t('Demonstrating block regions for a theme') . '</dt>';
      $output .= '<dd>' . t('You can see which region is where in a theme by clicking on the <em>Demonstrate block regions</em> link on the <a href="!blocks">Block layout page</a>. Regions are specific to each theme, so you need to toggle to a different theme first to demonstrate its block regions.', array('!blocks' => \Drupal::url('block.admin_display'))) . '</dd>';
      $output .= '<dt>' . t('Toggling between different themes') . '</dt>';
      $output .= '<dd>' . t('Blocks are placed and configured specifically for each theme. The Block layout page opens with the default theme, but you can toggle to other installed themes.') . '</dd>';
      $output .= '<dt>' . t('Configuring block settings') . '</dt>';
      $output .= '<dd>' . t('To change the settings of an individual block click on the <em>Configure</em> link on the <a href="!blocks">Block layout page</a>. The available options vary depending on the module that provides the block. For all blocks you can change the block title and toggle whether to display it.', array('!blocks' => Drupal::url('block.admin_display'))) . '</dd>';
      $output .= '<dt>' . t('Controlling visibility') . '</dt>';
      $output .= '<dd>' . t('You can control the visibility of a block by restricting it to specific pages, content types, and/or roles by setting the appropriate options under <em>Visibility settings</em> of the block configuration.') . '</dd>';
      $output .= '<dt>' . t('Adding custom blocks') . '</dt>';
      $output .= '<dd>' . t('You can add custom blocks, if the <em>Custom Block</em> module is installed on the <a href="!extend">Extend page</a>. For more information, see the <a href="!blockcontent-help">Custom Block help page</a>.', array('!extend' => \Drupal::url('system.modules_list'), '!blockcontent-help' => \Drupal::url('help.page', array('name' => 'block_content')))) . '</dd>';
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
  if ($route_name == 'block.admin_display' || $route_name == 'block.admin_display_theme') {
    $demo_theme = $route_match->getParameter('theme') ?: \Drupal::config('system.theme')->get('default');
    $output = '<p>' . t('This page provides a drag-and-drop interface for adding a block to a region, and for controlling the order of blocks within regions. To add a block to a region, or to configure its specific title and visibility settings, click the block title under <em>Place blocks</em>. Since not all themes implement the same regions, or display regions in the same way, blocks are positioned on a per-theme basis. Remember that your changes will not be saved until you click the <em>Save blocks</em> button at the bottom of the page.') . '</p>';
    $output .= '<p>' . \Drupal::l(t('Demonstrate block regions (!theme)', array('!theme' => $themes[$demo_theme]->info['name'])), new Url('block.admin_demo', array('theme' => $demo_theme))) . '</p>';
Dries Buytaert's avatar
 
Dries Buytaert committed
}

 * Implements hook_page_top().
function block_page_top(array &$page_top) {
  if (\Drupal::routeMatch()->getRouteName() === 'block.admin_demo') {
    $theme = \Drupal::theme()->getActiveTheme()->getName();
    $page_top['backlink'] = array(
      '#type' => 'link',
      '#title' => t('Exit block region demonstration'),
      '#options' => array('attributes' => array('class' => array('block-demo-backlink'))),
    if (\Drupal::config('system.theme')->get('default') == $theme) {
      $page_top['backlink']['#url'] = Url::fromRoute('block.admin_display');
      $page_top['backlink']['#url'] = Url::fromRoute('block.admin_display_theme', ['theme' => $theme]);
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Returns an array of block class instances by theme.
Dries Buytaert's avatar
 
Dries Buytaert committed
 *
 *   The theme to rehash blocks for. If not provided, defaults to the currently
 *   used theme.
Dries Buytaert's avatar
 
Dries Buytaert committed
 * @return
 *   Blocks currently exported by modules.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
  $theme = $theme ? $theme : \Drupal::config('system.theme')->get('default');
  $regions = system_region_list($theme);
  $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme));
  foreach ($blocks as $block_id => $block) {
    // Remove any invalid block from the list.
    // @todo Remove this check as part of https://drupal.org/node/1776830.
    if (!$block->getPlugin()) {
      unset($blocks[$block_id]);
      continue;
    }
    if (!empty($region) && $region != BlockInterface::BLOCK_REGION_NONE && !isset($regions[$region]) && $status) {
      drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $block_id, '%region' => $region)), 'warning');
      // Disabled blocks are moved into the BlockInterface::BLOCK_REGION_NONE
      // later so no need to move the block to another region.
    // Set region to none if not enabled.
    if (!$status && $region != BlockInterface::BLOCK_REGION_NONE) {
      $block->setRegion(BlockInterface::BLOCK_REGION_NONE);
Dries Buytaert's avatar
 
Dries Buytaert committed
  return $blocks;
}
Dries Buytaert's avatar
 
Dries Buytaert committed

 *
 * @param $theme_list
 *   An array of theme names.
  foreach ($theme_list as $theme) {
    block_theme_initialize($theme);
 * 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
  // Initialize theme's blocks if none already registered.
  $has_blocks = entity_load_multiple_by_properties('block', array('theme' => $theme));
    $default_theme = \Drupal::config('system.theme')->get('default');
    // Apply only to new theme's visible regions.
    $regions = system_region_list($theme, REGIONS_VISIBLE);
    $default_theme_blocks = entity_load_multiple_by_properties('block', array('theme' => $default_theme));
    foreach ($default_theme_blocks as $default_theme_block_id => $default_theme_block) {
      if (strpos($default_theme_block_id, $default_theme . '_') === 0) {
        $id = str_replace($default_theme, $theme, $default_theme_block_id);
      }
      else {
        $id = $theme . '_' . $default_theme_block_id;
      }
      $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));
/**
 * Implements hook_rebuild().
 */
function block_rebuild() {
  foreach (list_themes() as $name => $data) {
    if ($data->status) {
      _block_rehash($name);
    }
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function block_theme_suggestions_block(array $variables) {
  $suggestions = array();

  $suggestions[] = 'block__' . $variables['elements']['#configuration']['provider'];
  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  // Theme suggestions should only contain underscores, because within
  // drupal_find_theme_templates(), underscores are converted to hyphens to
  // match template file names, and then converted back to underscores to match
  // pre-processing and other function names. So if your theme suggestion
  // contains a hyphen, it will end up as an underscore after this conversion,
  // and your function names won't be recognized. So, we need to convert
  // hyphens to underscores in block deltas for the theme suggestions.

  // We can safely explode on : because we know the Block plugin type manager
  // enforces that delimiter for all derivatives.
  $parts = explode(':', $variables['elements']['#plugin_id']);
  $suggestion = 'block';
  while ($part = array_shift($parts)) {
    $suggestions[] = $suggestion .= '__' . strtr($part, '-', '_');
  }

  if (!empty($variables['elements']['#id'])) {
    $suggestions[] = 'block__' . $variables['elements']['#id'];
 * Prepares variables for block templates.
 *
 * Default template: block.html.twig.
 * Prepares the values passed to the theme_block function to be passed
 * into a pluggable template engine. Uses block properties to generate a
 * series of template file suggestions. If none are found, the default
 * Most themes use their own copy of block.html.twig. The default is located
 * inside "core/modules/block/templates/block.html.twig". Look in there for the
 * full list of available variables.
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the properties of the element.
 *     Properties used: #block, #configuration, #children, #plugin_id.
 */
function template_preprocess_block(&$variables) {
  $variables['configuration'] = $variables['elements']['#configuration'];
  $variables['plugin_id'] = $variables['elements']['#plugin_id'];
  $variables['base_plugin_id'] = $variables['elements']['#base_plugin_id'];
  $variables['derivative_plugin_id'] = $variables['elements']['#derivative_plugin_id'];
  $variables['label'] = !empty($variables['configuration']['label_display']) ? $variables['configuration']['label'] : '';
  $variables['content'] = $variables['elements']['content'];
  // A block's label is configuration: it is static. Allow dynamic labels to be
  // set in the render array.
  if (isset($variables['elements']['content']['#title']) && !empty($variables['configuration']['label_display'])) {
    $variables['label'] = $variables['elements']['content']['#title'];
  }
  // Create a valid HTML ID and make sure it is unique.
  if (!empty($variables['elements']['#id'])) {
    $variables['attributes']['id'] = drupal_html_id('block-' . $variables['elements']['#id']);

  // Proactively add aria-describedby if possible to improve accessibility.
  if ($variables['label'] && isset($variables['attributes']['role'])) {
    $variables['title_attributes']['id'] = drupal_html_id($variables['label']);
    $variables['attributes']['aria-describedby'] = $variables['title_attributes']['id'];
 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
 * Removes deleted role from blocks that use it.
  foreach (Block::loadMultiple() as $block) {
    /** @var $block \Drupal\block\BlockInterface */
    $visibility = $block->getVisibility();
    if (isset($visibility['user_role']['roles'][$role->id()])) {
      unset($visibility['user_role']['roles'][$role->id()]);
      $block->getPlugin()->setVisibilityConfig('user_role', $visibility['user_role']);
 * Implements hook_ENTITY_TYPE_delete() for menu entities.
function block_menu_delete(Menu $menu) {
  if (!$menu->isSyncing()) {
    foreach (Block::loadMultiple() as $block) {
      if ($block->getPluginId() == 'system_menu_block:' . $menu->id()) {
 * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
 *
 * Delete the potential block visibility settings of the deleted language.
 */
function block_configurable_language_delete(ConfigurableLanguageInterface $language) {
  // Remove the block visibility settings for the deleted language.
  foreach (Block::loadMultiple() as $block) {
    /** @var $block \Drupal\block\BlockInterface */
    $visibility = $block->getVisibility();
    if (isset($visibility['language']['langcodes'][$language->id()])) {
      unset($visibility['language']['langcodes'][$language->id()]);
      $block->setVisibilityConfig('language', $visibility['language']);