user3810914
user3810914

Reputation: 425

How to get custom block content in drupal 8

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.sstatic.net/fOuSW.png

Thanks

Upvotes: 4

Views: 11493

Answers (1)

Peter Boeren
Peter Boeren

Reputation: 76

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

Upvotes: 5

Related Questions