Problem/Motivation
I'm trying to add something like /ajax_get_jobs/en/{langCode}/{searchTerm}/{jobTypes}/{units}/{page}
in a custom route. However, if I leave one of the parameters in the middle (searchTerm for example) empty (for example /ajax_get_jobs/en//Full-time/Central
it no longer works even though there are defaults defined for all of the parameters.
Seems that using vanilla Symphony adding ! in front of each of the parameter definitions should work per Symphony documentation, but the exclamation mark doesn't seem to work in Drupal at all.
The Drupal routing documentation isn't too specific on this. It does specify that ”the first item of the path cannot be an argument, and must be a string. You can also define optional parameters at the end of your path (See 'Optional Parameters' on this page).”, which could mean that all empty optional parameters must be in the end of the path, but could also mean just that the optional parameters must be defined in the end of the route.
It also specificies that ”unlike generic Symfony routes, Drupal requires that a slug occupies a complete path part”, but that also doesn't mean that a path part can't be empty (ie. nothing between the slashes).
Steps to reproduce
Create a custom module with a routing definition like
example_module.job_data:
path: '/ajax_get_jobs/{langCode}/{searchTerm}/{jobTypes}/{units}/{page}'
defaults:
_controller: '\Drupal\example_module\Controller\JobController::getJobs'
searchTerm: NULL
jobTypes: NULL
units: NULL
page: 0
requirements:
_permission: 'access content'
Try accessing /fi/ajax_get_jobs/fi//Full-time/Central. The request doesn't match the route, unlike if you have a searchTerm that's not empty.
Proposed resolution
Either allow an empty optional parameter in the middle of the route or clearly document that it isn't possible.
Comments
Comment #2
zeip CreditAttribution: zeip at Ardcoras oy for Druid commentedComment #3
darktek CreditAttribution: darktek as a volunteer commentedI don't think it can be accomplish unless you change how Drupal behaves when you add a "//".
As you can see that's an event subscriber in the core that changes double "//" into one symbol (/).
Maybe your best option here is to leave the searchTerms parameter at the end of your endpoint.
Comment #4
anybodyI think the request makes sense, but might be complicated or even impossible to accomplish. Changing to latest core version anyway.
Comment #5
spookyisland CreditAttribution: spookyisland as a volunteer commentedYou can already do it adding a question mark to the parameter name, as explained in the green box here: https://symfony.com/doc/current/routing.html#optional-parameters