Onema
Onema

Reputation: 7582

Symfony2 routing optional parameter and format path/pattern

I would like to construct the following URI's using a single route pattern

1 hello/first.format
2 hello/first
3 hello/first/last.format
4 hello/first/last

where first is required and last and format are optional.

this is what I have tried:

hello-route:
  pattern:  /hello/{fist_name}/{last_name}.{_format}
  defaults: { _controller: AcmeHelloBundle:Default:index, last_name:Default, _format:html}
requirements:
  _format: html|rss|json
  first_name: \w+
  last_name: \w+

But is not correct as it matches 2, 3, and 4 but not 1. 1 will not fail, but it will match {first_name} as "first.format" despite the requirement.

How can I do this using basic routing?

Upvotes: 0

Views: 3447

Answers (1)

james_t
james_t

Reputation: 2733

Define two routes to accomplish this

hello-route-first:
  pattern:  /hello/{fist_name}.{_format}
  defaults: { _controller: AcmeHelloBundle:Default:index, _format:html}
requirements:
  _format: html|rss|json
  first_name: \w+

hello-route-last:
  pattern:  /hello/{fist_name}/{last_name}.{_format}
  defaults: { _controller: AcmeHelloBundle:Default:index, _format:html}
requirements:
  _format: html|rss|json
  first_name: \w+
  last_name: \w+

Then make the $last_name argument optional in your controller

function indexAction($first_name, $last_name = "")
   {

Upvotes: 1

Related Questions