Either I'm stupid or I can't search. Sorry if this is a duplicate, but I can't find any answer to my problem. I made a custom block type in admin panel, named it content_under_listing, and then I made two blocks of it - the first has id 1, the second has id 2. Then I made a Plugin / Block with file ContentBlock.php. I render it in my twig.html file with line {{ drupal_block('content_block') }} - and it works, it displays what I have in build() function in my ContentBlock.php file. And now: how the hell can I display in that block every blocks of type content_under_listing, which I created in admin panel?

Here is the code of ContentBlock.php:

1) this way I can display every block, but with it id, and I don't want to write it by hand 1, 3 or 54. I want to display all of blocks of type content_under_listing. Is it possible?

  public function build() {
    $bid = 1;
    $block = \Drupal\block_content\Entity\BlockContent::load($bid);
    $render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
    return $render;

2) So I tried with sth like work with nodes, but it doesn't work:

public function build() {
    $build = [];

    $storage = $this->entityTypeManager->getStorage('block');
    $query = $storage->getQuery()->condition('type', 'content_under_lisitng');
    $bids = $query->execute();
    $blocks = $storage->load($bids);

    $build['#theme'] = 'content_block';
    return $build;

$blocks is empty. Please help.

EDIT Code after edit:

  public function build() {
    $storage = $this->entityTypeManager->getStorage('block_content');
    $query = $storage->getQuery()->condition('type', 'content_under_lisitng');
    $bids = $query->execute();
    $blocks = $storage->loadMultiple($bids);
    $result = $this->entityTypeManager->getViewBuilder('block_content')->viewMultiple($blocks);


    return $result;

and the result:

enter image description here

  • 1
    The second code contains some errors, block needs to be block_content. load() loadMultiple() and you miss the final step of the first code snippet, which then should be the multiple version viewMultiple($blocks) as well.
    – 4uk4
    Commented Feb 28, 2020 at 13:12
  • @4k4 So... after your help it is: $storage = $this->entityTypeManager->getStorage('block_content'); and $blocks = $storage->loadMultiple($bids); But what should I do with this viewMultiple($blocks)?
    – sailormoon
    Commented Feb 28, 2020 at 13:35
  • 2
    – 4uk4
    Commented Feb 28, 2020 at 13:40
  • @4k4 I have still no result... I edited my post, please see.
    – sailormoon
    Commented Feb 28, 2020 at 13:46
  • 1
    You have a typo in the condition: content_under_lisitng
    – 4uk4
    Commented Feb 28, 2020 at 13:49


Your Answer

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

Browse other questions tagged or ask your own question.