Question

My controller class holds some not-so-easy logic to receive some data from a route parameter I need in a block plugin. As this block will only be rendered on this specific route, I would like to simply get the route controller route with this block which would receive its data from the controller.

Is there any way to get the controller class from any of the services like current_route_match?
I can get the route object or the route name, but I didn't find a way to get the controller class.

Was it helpful?

Solution

You find the controller class in a request attribute:

$controller = \Drupal::request()->attributes->get('_controller');

You need to instantiate the controller and run the code a second time. For not-so-easy logic it might be a better idea to refactor the code to a service which then caches the result for the second run, as @Hudri commented.

Or take a different approach. Place a custom block with a static placeholder on the page and replace it by attaching bubbleable metadata to the controller output. See Add an attribute to $variables from a Controller

Instead of a render array you can also replace the placeholder in a lazy-builder callback. This depends on the structure of the data in controller and block and how dynamic this is. At the end this is all about caching performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top