0

I have a couple of blocks that have been created using the ... extends BlockBase syntax in my module. They work perfectly fine, and I can add them on the blocks layout page, can add them into DS as a field, etc. They definitely exist fine.

However, when I try and render them using Block::load(), they won't show up, unlike other blocks that work fine.

For example, if I have the following docblock:

/**
 * Provides a 'Cute Cats' Block.
 *
 * @Block(
 *   id = "cute_cats",
 *   admin_label = @Translation("Cute cats yo"),
 * )
 */
 class CuteCats extends BlockBase { ... }

... and then try and call it like this:

$block = \Drupal\block\Entity\Block::load('cute_cats');
return render(\Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block));

Any idea why? Thanks in advance.

1

Block::load() loads a configured block, that means a block that is placed in the block layout. It does not load plugins.

The name of the configured block is displayed in the block layout as Machine name.

You can place the block in the Disabled section, if you only want to configure the block, but don't want to show the block in a region.

  • Thanks, I found the code for plugin blocks and so have answered my own question. Appreciate the response though :) – Matt Fletcher Sep 14 '16 at 14:11
1

It turns out that I was using the wrong syntax, and should have used a different one for plugin blocks (as @4x4 mentioned). The correct code for plugin blocks is:

$plugin_manager = \Drupal::service('plugin.manager.block');
$block = $plugin_manager->createInstance($block_id, array());
return render($block->build());
  • Got the info from drupal.stackexchange.com/a/171733/14151, so thanks to @googletorp for that one – Matt Fletcher Sep 14 '16 at 14:12
  • That's basically the same, you configure the block on the fly with an empty configuration. You simply skip the step to configure the block. – 4k4 Sep 14 '16 at 16:34

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.