Reputation: 69
I have created a custom block and am trying to load it in a controller to ultimately be rendered in a twig template. I know that the block code works, because I can place it on the page using the block ui and the content renders perfectly. But when I try to load it in the controller it returns NULL. Hopefully someone can see what is wrong.
Here is my block code:
/**
* Provides a 'homepage search' block.
*
* @Block(
* id = "home_search_block",
* admin_label = @Translation("Home Search block"),
* category = @Translation("Custom home search block example")
* )
*/
class HomeSearchBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$form = \Drupal::formBuilder()->getForm('Drupal\homepage\Form\HomeSearchForm');
return $form;
}
}
And here is my controller code:
class HomeController extends ControllerBase {
public function content() {
$config = $this->config('nl_admin.settings');
$image_text = $config->get('nl_admin.homepage_image_text');
$block = Block::load('home_search_block');
$search_form = \Drupal::entityTypeManager()
->getViewBuilder('block')
->view($block);
$build = array(
'#theme' => 'homepage',
'#image_text' => $image_text,
'#search_form' => $search_form,
'#cache' => array('max-age' => 0)
);
return $build;
}
}
If I kint($block) in the controller, it returns NULL.
Upvotes: 2
Views: 3191
Reputation: 46
Custom blocks are of entity_type "block_content" and not "block".
You need to change your code in the following way:
$block = BlockContent::load('home_search_block');
$search_form = \Drupal::entityTypeManager()
->getViewBuilder('block_content')
->view($block);
A useful guide to creating a custom block is also on the Drupal documentation if you want to go that way: https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-block
Custom templates for custom blocks are also tricky, some tips were in this post: https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-block
And a good discussion here: https://www.drupal.org/forum/support/theme-development/2016-05-15/drupal-8-custom-block-twig-template-naming-not-working
Upvotes: 3