Search code examples
symfonylocalefosuserbundlesymfony-routing

How to manually set router locale in Symfony 2.8


I am running a Symfony 2.8 based web app which uses FOSUserBundle to handle users.

The FOSUserBundle routes are imported using the current locale as prefix:

// app/config/routing.yml
...
# fos_userbundle
user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"
    prefix: "/{_locale}/user"

This works fine. If the users creates a new account using the web browser, the e-mail confirmation link is created the current locale, e.g. https://example.com/XX/user/register/confirm/TOKEN

Now I have added a REST API which allows to create new users from within the mobile Apps (iOS and Android). This is done by simple POSTing the necessary data (username, password, etc.) including the locale to controller which than handles the user creation.

The problem: Users created using the REST API always receive confirmation links using the default locale, which is en.

While setting the locale manually works fine to generate the confirmation mail in the correct language, it has no effect on the confirmation link:

public function registerAction(Request $request) { 
    $username = getDataFromRequest(...);
    $userLocale = getDateFromRequest(...);
    ...

    // Set locale manually
    $translator->setLocale(userLocale);
    $sessionLocale = $request->getSession()->set('_locale', userLocale);
    $request->setLocale(userLocale);
    ...

    $mailer = $this->get('fos_user.mailer');
    $tokenGenerator = $this->get('fos_user.util.token_generator');

    if (null === $user->getConfirmationToken()) 
        $user->setConfirmationToken($tokenGenerator->generateToken());

    $mailer->sendConfirmationEmailMessage($user);

    ...
}

I have checked the code of sendConfirmationEmailMessage(...) and it uses the default router to generate the confirmation link:

$url = $this->router->generate('fos_user_registration_confirm', array('token' => $user->getConfirmationToken()), UrlGeneratorInterface::ABSOLUTE_URL);

Question: How to tell the router to use the correct locale?


Solution

  • After digging through half the Symfony code I found out from where the router gets the locale and found a solution that works for me. Maybe it is useful for others as well.

    Simply update the router locale using the following code:

    $router->getContext()->setParameter('_locale', $locale);