3

I made a custom block in my custom module. I now want to show that block in the "No results" area of a view, but I can't get it to render (I don't see any error message, and I don't see any output).

Here is the block definition:

/**
 * Provides an 'New User' Block.
 *
 * @Block(
 *   id = "newuser_block",
 *   admin_label = @Translation("New user block"),
 *   category = @Translation("MYMODULE"),
 * )
 *

In my view, in the "No results" section, I added Rendered entity - Block, and set the Block ID to newuser_block.

However, the block does not get rendered.

This is because I did not add the block on the block admin page at /admin/structure/block. When I add the block on the admin page and use the admin page block ID (not the block machine name), the block is rendered correctly.

However, I don't want to add the block to the admin page because I only need this block in a few places on my site, so I was using Layout Builder to inject the block where necessary.

So, is there a way to inject a block by machine name (instead of by the ID used on the block admin page) in Views?

1
  • 1
    Add a new region, name it disabled or something like that and never print it anywhere. Add this block to that region. Done.
    – leymannx
    Nov 7, 2020 at 7:52

2 Answers 2

1

There is an core issue about this, Problems using 'Rendered entity - Block' in header/footer

the block ID only exists as long a the the block is configured to be visible in a region

Until fixed, yes, it is possible without having to add it to a region as long as you solve it via template file. In this case using views-view--[view-name]--[view-display-name].html.twig and using Twig Tweak you can print it with

{{ drupal_form('namespace\\ClassName') }} # except you add an extra `\`

Ex:

{{ drupal_form('Drupal\\search\\Form\\SearchBlockForm') }} 
4

The only purpose of a block plugin is to be placed as a block. It's not an entity. The placed block instance can become an entity of its own but also be part of a layout section.

Since the block is your own custom code you don't need any of the workarounds discussed and linked. It would make more sense to refactor the code and expose it as block plugin to be placed on the page and at the same time as area plugin to be placed in a View.

For sharing the custom code between both plugins you can use classic OOP, or the in Drupal very common traits and services. The service has the advantage that it is more flexible and you can not only share code but also data, for example to cache the result if it is expensive to calculate and used in multiple places.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.