Create A Dynamic Route in Drupal 8 & 9

24 / Aug / 2023 by Yogesh Pratap Singh 0 comments

As we know providing routes in the routing.yml file is the simplest way to achieve the static routes. Creating dynamic routes is a bit different from the way we achieve static routes.

So In Drupal 8 or 9, we can achieve this by following below few steps below.

Step 1. Create an entry in custom.routing.yml

So we need to add an entry in the method “route_callbacks” in our routing file.

route_callbacks:
- '\Drupal\custom\Routing\DynamicListingRoutes::routes'

Step2. Create a routing class

Now we need to create a Routing class “DynamicListingRoutes”  and add our logic.

The dynamic routing method can return either an array of Route objects or a RouteCollection Object.

1. Symfony\Component\Routing\Route object

 

2. \Symfony\Component\Routing\RouteCollection object

In the above routing class, I’ve tried to create multiple routes based on the location of the hospitals.

Step 3. Create a Controller class

So, the last and 3rd step is to write a controller in which we describe the functionality or our logic.

So in this case we’ve rendered a hospital listing view based on the location which we’re getting from our dynamic routing.

Conclusion
So using this method, we can create dynamic routes and render data according to the dynamic values.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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