I created a new custom block type in /admin/structure/block/block-content/types to which I added two fields. Then, I created a block with that block type.

How can I programmatically load this block via code?

How do I get the values of its fields (x, an image field, and y, a text field)?

I tried this code, but it didn't work.

$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityManager()->getViewBuilder('block_content')->view($block);

4 Answers 4


Place the block in the disabled section at admin/structure/block, this creates a block instance with your block_content type, give it a nice easy machine name to remember.

place block in disabled section

By placing it in the disabled section, it won't show up, until you load it programatically.

Then using your machine name:

$machine_name = 'myblock';

$block = \Drupal::entityTypeManager()
if (!empty($block)) {
  $block_content = \Drupal::entityTypeManager()

  $pre_render = $block_content;

If you really want to get the rendered fields, you can do:

$render = \Drupal::entityTypeManager()

But it is more standard practice to use Drupal's formatters and such and perhaps a custom template, rather than building the block and extracting elements from the rendered render array.


There are two questions. How to load and render a configured block is answered perfectly by @oknate.

For the second question, How do I get the values of its fields (x, an image field, and y, a text field)? That's easy, because you've already loaded the block content entity, where the fields are stored in the database.

$block = \Drupal\block_content\Entity\BlockContent::load($bid);

You can access the value from the text field

$text = $block->field_y->value;

and get the url from the image field.

$image_url = file_create_url($block->field_x->entity->uri->value);

Try this code by including EntityInterface:

// Block 
use Drupal\Core\Entity\EntityInterface;
// the last part of the parameter is the block id
$block = \Drupal\block\Entity\Block::load('yourblockid');
$block_content = \Drupal::entityManager()
$block = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);
      if (!empty($block)) {
        $recArticleAdView = \Drupal::entityTypeManager()
        $rendered = \Drupal::service('renderer')->render($recArticleAdView);
        $response = new CacheableResponse($rendered);
        $variables['content']['sponsored_content'] = Markup::create(trim(strip_tags($response->getContent(), '<div>')));

Your Answer

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