Learn How to Call Custom Blocks into Controllers in Drupal 10

30 / Apr / 2023 by Rajveer Singh 0 comments

I’d recommend referring to the following blogs before proceeding further:

Step-by-Step Guide to Creating a Controller in Drupal 8/9/10

Step-by-Step Guide to Creating a Custom Module in Drupal 9

You can use controllers to generate dynamic pages and return content in response to user requests. Sometimes, you may need to display content from a custom block within a controller. This can be achieved by following the steps below:

First, create a custom block using the Block Plugin API in Drupal 10. You can refer to the official Drupal documentation for a step-by-step guide on creating a custom block.

Once you have created the custom block, you can load it in the controller using the Block Manager service. The Block Manager service is responsible for loading and managing blocks in Drupal. You can inject the Block Manager service into your controller’s constructor via dependency injection to load the block.

Next, you can call the “createInstance()” method on the Block Manager service to create an instance of the custom block by its plugin ID. You can then use the “build()” method on the block object to get the render array for the block. Finally, you can return the render array from your controller’s “content()” method to display the block’s content on your controller’s page.

Here’s an example of how to load and render a custom block in a controller:

use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyController extends ControllerBase implements ContainerFactoryPluginInterface {

/**
* The block manager service.
*
* @var \Drupal\Core\Block\BlockManagerInterface
*/
protected $blockManager;

/**
* MyController constructor.
*
* @param \Drupal\Core\Block\BlockManagerInterface $block_manager
* The block manager service.
*/
public function __construct(BlockManagerInterface $block_manager) {
$this->blockManager = $block_manager;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$container->get('plugin.manager.block')
);
}

/**
* The controller content.
*
* @return array
* A render array containing the page content.
*/
public function content() {
// Load the custom block.
$block = $this->blockManager->createInstance('custom_block_plugin_id');

// Get the render array for the block.
$render_array = $block->build();

// Return the render array for the block.
return $render_array;
}

}

By following these steps, you can easily load and render a custom block in a controller in Drupal 10. This can be useful for displaying dynamic content on your website and customizing the user experience.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *