Vladimir Cvetic
Vladimir Cvetic

Reputation: 842

Symfony 2 optional route url parts (wildcard?)

In Symfony 2.2.1 Is it possible to create route like:

/search/category_ids/1,2,3,4/subcategory_ids/32,23,9/language_ids/10,23,5 ...

where every url part is optional, for example user could visit url

/search/category_ids/1,2,3,4/language_ids/10,23,5 ...

or even

/search/subcategory_ids/2,23 

I would like to get away from traditional get parameters in favor of this, mainly for aesthetic appeal.

Upvotes: 0

Views: 2815

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

While some frameworks discourage the use of query strings, symfony doesn't, and you should just pass the parameters in a query string:

/search?category_ids=1,2,3,4&subcategory_ids=...

These parameters can be accessed through the request object:

public function searchAction(Request $request) {
    $category_ids = $request->query->get('category_ids');
}

If you really really need to pass the parameters in the path, you can achieve the same result with a "match all" parameter at the end of your route:

@Route("/search/{params}", requirements={"params"=".*"}, defaults={"params"=""})
public function searchAction($params) {

}

You can just parse $params like this:

$parts = explode('/', $params);
$map = array();
for ($i = 0; $i < count($parts); $i+=2) {
    $map[$parts[$i]] = $parts[$i+1];
}

Upvotes: 2

Related Questions