3

I am trying to override block content by using hook_preprocess_block(&$variables). I was expecting to find bundle type in $variable, but not getting anything related to this.

Here is kint display of $variable inside the function - enter image description here

More Info - This is a block type (say content_slider) created from Drupal UI & a block (say content_slider_homepage) is added.

2 Answers 2

4

The UUID from the custom block is in the variable derivative_plugin_id. You can use this UUID to load the block and get the bundle:

$block = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);

if ($block) {
  $block_type = $block->bundle();
}

Or look in $variables['elements']. Here you'll find the custom block entity loaded in the variables and probably the block type as well. You can also use hook_block_content_view() if this is for a module. See the comments from @Berdir.

2
  • there is no preprocess_block_content because there is no block_content template, but there is hook_block_content_view() and .. view_alter() and you can get it in preprocess_block() too
    – Berdir
    Feb 24, 2017 at 10:47
  • Specifically, what you are looking for is in elements, so dump that key to see its content
    – Berdir
    Feb 24, 2017 at 10:47
7

This is how I would do it:

use \Drupal\block_content\BlockContentInterface;


/**
 * Implements HOOK_preprocess_block().
 *
 * @param $variables
 */
function mymodule_preprocess_block(&$variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {

    if ($content['#block_content']->bundle() == 'xxx') {
      // ...
    }

  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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