How to get custom block content in drupal 8

user3810914 picture user3810914 · Jul 14, 2014 · Viewed 8.6k times · Source

I have created a custom block "admin/structure/block/block-content".

How to get the field from a custom block by code?

I have tried with block_load function and entity_load but did not get the expected result.

Please help me to solve it.

$block = \Drupal::entityManager()->getStorage('block')->load($block_id);

$block_view = \Drupal::entityManager()->getViewBuilder('block')->view($block);

http://i.stack.imgur.com/fOuSW.png

Thanks

Answer

Peter Boeren picture Peter Boeren · Aug 21, 2015

Your solution is almost right. Custom blocks in Drupal 8 have a different entity name. See example below.

<?php

/**
 * Implements hook_preprocess_html().
 */
function my_module_preprocess_html(&$variables) {
  // You can do some logic like showing your custom block on certain pages or
  // under certain conditions.
  if (\Drupal::routeMatch()->getRouteName() == 'some.path') {
    $block = \Drupal::entityManager()->getStorage('block_content')->load(1);
    $block_view = \Drupal::entityManager()->getViewBuilder('block_content')->view($block);
    $variables['page']['sidebar_first']['custom_block'] = $block_view;
  }
}