Blocks can be altered in three different ways: the plugin definition can be altered, the build array, or the view array out.
A module can implement hook_block_alter in its .module file and modify the annotation definitions of all the discovered blocks. This will allow a module to change the default user_login_block from user login to Login:
/**
* Implements hook_block_alter().
*/
function mymodule_block_alter(&$definitions) {
$definitions['user_login_block']['admin_label'] = t('Login');
}
A module can implement hook_block_build_alter and modify the build information of a block. The hook is passed through the build array and the \Drupal\Core\Block\BlockPluginInterface instance for the current block. Module developers can use this to add cache contexts or alter the cache ability of the metadata:
/**
* Implements hook_block_build_alter().
*/
function hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
// Add the 'url' cache the block per URL.
if ($block->getBaseId() == 'myblock') {
$build['#contexts'][] = 'url';
}
}
Finally, a module can implement hook_block_view_alter in order to modify the output to be rendered. A module can add content to be rendered or removed. This can be used to remove the contextual_links item, which allows inline editing on the front page of a site:
/**
* Implements hook_block_view_alter().
*/
function hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
// Remove the contextual links on all blocks that provide them.
if (isset($build['#contextual_links'])) {
unset($build['#contextual_links']);
}
}