2

I needed to create a route in which the path of the route would be completely dynamic and so I created a routing callback.

<?php

namespace Drupal\uber_affiliate\Routing;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * Class EntityOverview
 *
 * @package Drupal\uber_affiliate\Routing
 */
class AffiliateRoute {

  /**
   * Dynamically generate the routes for the entity details.
   *
   * @return \Symfony\Component\Routing\RouteCollection
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function routes() {

    $affiliate_menu_path = \Drupal::state()->get('affiliate_module_affiliate_menu_path', 'affiliate');
    $routes = [];
    $routes['affiliate'] = new Route(
      $affiliate_menu_path . '/' .   '{aff_id}' . '/' . '{dest_path}' . '/' . '{tracker_id}',
      [
        '_controller' => 'Drupal\uber_affiliate\Controller\UberAffiliate::affiliate_page',
      ],
      [
        '_permission'  => 'track affiliate clicks for this role',
      ],
      );


    return $routes;
  }
}


I need {dest_path} and {tracker_id} to be optional. How do I make them optional?

0

1 Answer 1

4

You can do so by providing a default value for those parameters.

path: '/foo/bar/{baz}'
defaults:
  ...
  baz: 'fallback-value'

With your example, it should be something like:

$routes['affiliate'] = new Route(
  "{$affiliate_menu_path}/{aff_id}/{dest_path}/{tracker_id}",
  [
    '_controller' => 'Drupal\uber_affiliate\Controller\UberAffiliate::affiliate_page',
    'dest_path' => 'fallback',
    'tracker_id' => 'fallback',
  ],
  [
    '_permission'  => 'track affiliate clicks for this role',
  ]
);

I assume there is a reason why you want them as route parameters and not as query string parameters (i.e. ?destination=foo&tracker-id=bar).

See Optional parameters for more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.