asolenzal
asolenzal

Reputation: 500

Symfony 2 issue with routing and _locale parameter

I have the following issue with symfony 2. The thing is that I have several route definitions with a _locale parameter on the beginning for example:

 /**
 * @Route("/{_locale}")
 * @Route("/{_locale}/community")
 * @Route("/{_locale}/events")
 */

Now, the _locale parameter has a default value of en-US, so it is not displayed on the url once the site locale is en-US.

I have another route that will change the locale on the app,

 /**
 * @Route("/change-locale/{locale}", name="change_locale")
 */

And I need to get the referer route name in order to redirect the request to the referer route name with the locale parameter set as the new locale. I do that using the router service match() method to get the route name of the referer url.

Now for example.

If the referer url is /en-US/community

then the dumped route obtained using the match method is:

  '_locale' = 'en-US'
  '_route' = 'app_frontend_main_default_index_1' 

Which is correct, but if the locale is the default locale (eg. es-ES) then the dumped route is as follows:

  '_locale' = '/community'
  '_route' = 'app_frontend_main_default_index' 

Which is wrong, because the url is matched to another route, and the locale(which is the default) gets the value of the first part of the route.

What I need is to get the correct route name, taking account in the default locale parameter.

Thanks in advance.

Upvotes: 2

Views: 416

Answers (1)

chapay
chapay

Reputation: 1315

You are to add extra routes:

/**
 * @Route("/", defaults={"_locale" = "en-US"})
 * @Route("/community", defaults={"_locale" = "en-US"})
 * @Route("/events", defaults={"_locale" = "en-US"})
 */

and then to add requirements to existing:

/**
 * @Route("/{_locale}", requirements={"_locale": "en-US|en|fr"})
 * @Route("/{_locale}/community", requirements={"_locale": "en-US|en|fr"})
 * @Route("/{_locale}/events", requirements={"_locale": "en-US|en|fr"})
 */

In this case you will be able to handle both /community and /en-US/community routes.

Upvotes: 1

Related Questions