I need to alter all the blocks of custom type 'my_custom_block_type' that get displayed on my site. In order to achieve this, i added a custom prerender in which i filter on the block bundle :

function my_module_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = '_custom_block_custom_prerender';

function _custom_block_custom_prerender(array $build) {
  if ($build['content']['#block_content']) {
    $block_bundle = $build['content']['#block_content']->bundle();

    if ($build['content']['#block_content']->bundle() === 'my_custom_block_type') {
      // do your thing here
  return $build;

I think it's not the most elegant way to do this.

I tried to enhance this, but i did not manage, after several attempts, to retrieve the block type directly inside a hook_block_view_alter or a hook_block_build_alter ...

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

Is there a way to easily get the custom block type inside those two hooks ?

  • Try hook_block_content_view()/view_alter(), that gives you the block_content entity as an argument, just like hook_node_view(). Depends on what you need to do – Berdir Feb 21 '17 at 12:15
  • thanks @Berdir, hook_ENTITY_TYPE_view did the trick and is more straightforward. – tYb Feb 21 '17 at 13:15
  • Hey, could you move the solution into a desired answer and mark that as accepted? – leymannx Feb 21 '17 at 14:05

Try hook_ENTITY_TYPE_view()/hook_ENTITY_TYPE_view_alter(), that gives you the block_content $entity as an argument, just like hook_node_view().

  • @leymannx Thanks for improving, but as I commented, you should then actually use $entity and you can also type hint it on BlockContentInterface to get more specific method autocomplete. – Berdir Feb 21 '17 at 15:47
  • I see! Removed OP's code. – leymannx Feb 21 '17 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.