Creating Dynamic paths in Drupal 8

posted in: Drupal | 0

In Drupal 8 we can define the paths by creating a modulename.routing.yml file and add each path as a unique route to it. Drupal 8 borrows this feature from Symphony. We can also create paths dynamically after Drupal is loaded using route callbacks.

We need to define where our route callbacks exist by adding route callback parameter to our routing.yml file.

lndynamicroutes.testroute:
    path: 'lndynamicroutes/testroute'
    defaults:
        _controller: 'Drupal\lndynamicroutes\Controller\LearnDynamicRoutesController::testroute'
        _title: 'This is a test Route created'
    requirements:
        _permission: 'access content'

route_callbacks:
    - '\Drupal\lndynamicroutes\Routing\LearnDynamicRoutes::routes'

Here at the bottom of routing.yml file you can see route_callbacks which is routing where route callbacks are defined. We need to create a class LearnDynamicRoutes under src/Routing folder. It will have routes() class which returns an array of Symfony\Component\Routing\Route objects. Symfony\Component\Routing\Route has all the information of routes that need to be created dynamically.

namespace Drupal\lndynamicroutes\Routing;

use Symfony\Component\Routing\Route;

class LearnDynamicRoutes {

    public function routes() {

        $routes = [];

        $routes['lndynamic.another_test'] = new Route(
                '/lndynamicroutes/another-test', array(
            '_controller' => '\Drupal\lndynamicroutes\Controller\LearnDynamicRoutesController::testroute',
            '_title' => 'Route created Dynamically',
                ), array(
            '_permission' => 'access content',
                )
        );

        for ($i = 1; $i < 10; $i++) {
            $machine_name = 'lndynamicroutes.myroute_' . $i;
            $routes[$machine_name] = new Route(
                    '/lndynamicroutes/myroute_' . $i, [
                '_controller' => '\Drupal\lndynamicroutes\Controller\LearnDynamicRoutesController::myroute',
                '_title' => 'My Route is ' . $i,
                    ], [
                '_access' => 'TRUE',
                    ]
            );
        }
        
        for ($i = 1; $i < 10; $i++) {
            $machine_name = 'lndynamicroutes.newroute_' . $i;
            $routes[$machine_name] = new Route(
                    '/lndynamicroutes/newroute/' . $i, [
                '_controller' => '\Drupal\lndynamicroutes\Controller\LearnDynamicRoutesController::newroute',
                '_title' => 'New Route is ' . $i,
                        'id' => 2,
                    ], [
                '_access' => 'TRUE',
                    ]
            );
        }

        return $routes;
    }

}

 

More information on routing is found at Routing API in Drupal

Leave a Reply