4

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);

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

Thanks

Community
  • 1
  • 1
user3810914
  • 425
  • 2
  • 5
  • 9

1 Answers1

5

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;
  }
}
Peter Boeren
  • 76
  • 1
  • 3