8.5.x block.api.php hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)
8.0.x block.api.php hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)
8.1.x block.api.php hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)
8.2.x block.api.php hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)
8.3.x block.api.php hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)
8.4.x block.api.php hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)
8.6.x block.api.php hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)

Alter the result of \Drupal\Core\Block\BlockBase::build().

Unlike hook_block_view_alter(), this hook is called very early, before the block is being assembled. Therefore, it is early enough to alter the cacheability metadata (change #cache), or to explicitly placeholder the block (set #create_placeholder).

In addition to hook_block_build_alter(), which is called for all blocks, there is hook_block_build_BASE_BLOCK_ID_alter(), which can be used to target a specific block or set of similar blocks.

Parameters

array &$build: A renderable array of data, only containing #cache.

\Drupal\Core\Block\BlockPluginInterface $block: The block plugin instance.

See also

hook_block_build_BASE_BLOCK_ID_alter()

Entity CRUD, editing, and view hooks

Related topics

File

core/modules/block/block.api.php, line 151
Hooks provided by the Block module.

Code

function hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {

  // Add the 'user' cache context to some blocks.
  if ($some_condition) {
    $build['#cache']['contexts'][] = 'user';
  }
}