Create A Dynamic Route And Upcast Its Parameter In Drupal 8

December 1, 2020 | 2 Minute Read

Tags:Performance Optimization,Drupal

The creation of dynamic routes has changed as compared to the past versions of Drupal. Precisely when the routing layer now (in D8 and above) is Symfony based.

In my case, I had to display the basic details of any entity (either existing one or the one that will be created) dynamically. 

How do we create dynamic routes in Drupal 8?

This tutorial assumes you are already familiar with the routing system in Drupal. The routing system overview is an excellent place to start.

Step 1: Create an entry in Routing.yml

In order to provide a dynamic route, you will need to create an entry in your modules routing.yml file.

You can achieve the same using a service as well.

Step 2: Create a routing class

Now you will have to create your routing class and put your logic there. The dynamic routing method either returns an array of \Symfony\Component\Routing\Route objects or a \Symfony\Component\Routing\RouteCollection object. You have to define that in src/Routing/EntityOverview.php.

Step 3: Create a controller

The final step is to create a controller for your route callback. You’ve to define that in src/Controller/EntityDetails.php.

How do we upcast a parameter of a route?

You have created the dynamic route. But did you see the controller? How did the parameter all_entity provide a loaded entity? That is where the parameter upcasting/converter comes into the picture. Let's see how we can do that! 

Step 1: Define a service in services.yml

To upcast a parameter, you need to create a service defined in your modules my_module.services.yml.

Note: you’ll have to tag the service as paramconverter.

Step 2: Create a parameter converter class

Finally, we need to create the class for the parameter converter.

The class MyModuleParamConverter implements ParamConverterInterface, which provides two abstract methods:

  • convert: That’s where you need to write the logic to process your parameters. In my case, I’ve fetched the entity type from the route object and loaded the entity using the entityTypeManager.
  • applies: It is a basic validation of where the conversion is applicable. In my case, it is appropriate where the parameter is of type all_entity.

Note: the variable name in the route and the controller should match.

Cheers! Now your dynamic route with the upcasted parameter is ready to roll. 

Though this required more effort to create it as compared to Drupal 7, it has it's own advantages associated with it, too. I hope this post will help you create your dynamic routes without any hassle. For more on routes in Drupal 8, check our blog here