2

I am having an issue with a route in Symfony, I have a route setup that needs to match the below:

/my-test-route-holidays/

The above "my-test-route" is the placeholder variable.

The route in symfony is as follows:

overview:
  path: /{var}-holidays/
  defaults: { _controller: AppBundle:Overview:index }

Symfony cannot find the route, a route like below does work without dashes/hyphens in the variable:

/test-holidays/

So my question is, how can I allow hyphens inside a route placeholder?

Thanks

Ben Osborne
  • 218
  • 4
  • 15

2 Answers2

1

I have managed to solve this myself, it was a quick skim of the documentation that led me to the wrong answer.

I come across this page on Symfonys website a few times whilst trying to research the answer: Symfony Docs Current Slash in Parameter

In their example:

share:
    path:     /share/{token}
    defaults: { _controller: AppBundle:Default:share }
    requirements:
        token: .+

You can see that they have added "requirements" and underneath that "token", I just assumed that "token" was something to do with regex but actually it relates to the placeholder you have in your "path" and they should match.

Below is what I had:

overview:
  path: /{var}-holidays/
  defaults: { _controller: AppBundle:Overview:index }
  requirements:
      token: .+

But what I actually needed was to replace the "token" under "requirements" with "var".

overview:
  path: /{var}-holidays/
  defaults: { _controller: AppBundle:Overview:index }
  requirements:
      var: .+

And what do you know, it works!

I hope somebody else finds this useful.

Ben Osborne
  • 218
  • 4
  • 15
1

Be careful with .+ as it will match "any" character including / slash characters, used to separate routes.
eg: /@nY-th1nG/can/../~/go$foo-holidays

Since the requirements parameter accepts a regular expression, for matching the hyphens I recommend using [-\w]+ instead. Which matches -a-zA-Z0-9_ 1 or more times.

overview:
  path: /{var}-holidays/
  defaults: { _controller: AppBundle:Overview:index }
  requirements:
      var: [-\w]+

Example https://3v4l.org/c712H

Allowing

/01234578247-AbC-19082-Zx-holidays 

Excluding paths like /$-holidays or /test/12-holidays


If you're expecting only digit dates, you could use [-\d]+ or for a more strict requirement on the accepted date formats \d{1,4}(-\d{1,2})?. 0-9999 followed by optional dash and 0-99

overview:
  path: /{var}-holidays/
  defaults: { _controller: AppBundle:Overview:index }
  requirements:
      var: [-\d]+ #or \d{1,4}(-\d{1,2})?

Which will allow

/190-holidays
/190-02-holidays

Excluding paths like /2019-a-holidays and /a-2019-holidays

If you need a specific format let me know and I will update the requirement pattern used to one that is more appropriate.

Will B.
  • 17,883
  • 4
  • 67
  • 69