3

How does Drupal 8 decide which route to use, if there are two routes defined in Drupal 8 via routing.yml that lead to the same path?

Of course this sounds like a stupid idea or like a mistake in code to have two routes with same path. But I think about having one route with a parameter and a second route without parameter but with a path that the first route might deliver.

So for example there is node.add route in node.routing.yml

node.add:
  path: '/node/add/{node_type}'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE
    parameters:
      node_type:
        with_config_overrides: TRUE

Now I am defining a route myexamle.nodeadd in myexample.routing.yml like this

myexample.nodeadd:
  path: '/node/add/examplecontenttype'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
    node_type: 'examplecontenttype'
  requirements:
    _node_add_access: 'node:examplecontenttype'
    _permission: 'access administration pages'
  options:
    _node_operation_route: TRUE
    parameters:
      node_type:
        with_config_overrides: TRUE

I added an additional _requirement in the second route. This is working for me like this, but I actually did not get how Drupal decides which of the two routes to actually use.

  • Seems first the more specific route, then the one with the wildcard, no? – leymannx Nov 30 '18 at 14:46
  • Yes, that sounds good and would be the way I prefer it to be :-). But I could not find some evidence about that, so wanted to be sure to understand this properly. – Stefan Korn Nov 30 '18 at 14:51
  • Yeah, could be module weight as well. – leymannx Nov 30 '18 at 14:52
  • 2
    Yes, the more specific route wins because it has a higher fit value, evidence RouteCompiler::getFit – 4k4 Nov 30 '18 at 15:16
  • Ah, yes there it is. If you like to put it as an answer I will accept it. Or if you not like, I can do and accept the answer. Kudos to @4k4!! – Stefan Korn Nov 30 '18 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.