1

What is the correct way to check if a block has an associated block_content instance, and if so, get the block_content object? What I have does not feel particularly intuitive or efficient:

/** @var \Drupal\block\Entity\Block $block */
$block;
$block_plugin = $block->getPlugin();
if ($block_plugin->getBaseId() == 'block_content') {
  /** @var \Drupal\block_content\Entity\BlockContent $block_content */
  $block_content = $block->getPlugin()->build()['#block_content'];
}

It feels weird to build the render array for the $block_plugin just to get access to the block content, but there doesn't seem to be a more helpful method on $block or $block_plugin.

For context: I'm conditionally updating block configuration in a deploy hook based on the block_content bundle, so I'm not rendering anything. Given that, it feels like I shouldn't be using the render array.

2

1 Answer 1

2

@4uk4's comment on the original problem pointed me to a better answer:

$block_plugin = $block->getPlugin();

$uuid = $block_plugin->getDerivativeId() ? $block_plugin->getDerivativeId() : '';

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

if ($block_content) {...}

Thanks for pointing me in the right direction!

Your Answer

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

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