I'm trying to figure out why my locale is different in one of my controllers and when I get the request from the request stack.
Here's an example of one of my routes: 'website.com/nl'
/**
* Main page of the website
* @Route("/{_locale}",
* name="home",
* defaults={"_locale": "nl"},
* requirements={
* "_locale": "nl|en|fr"
* },
* )
* @param Request $request
* @param $_locale
* @return \Symfony\Component\HttpFoundation\Response
*/
public function home(
Request $request,
$_locale
) {
// $_locale === "nl"
// $request->getLocale() === "nl"
}
As expected based on the url, the locale is NL
Now when I need the locale in one of my services or event listeners, I need to use RequestStack->getCurrentRequest()->getLocale()
. However, this locale is always set to locale: "en"
Service mapping:
app.doctrine.locale_listener:
class: App\EventListener\LocaleListener
public: false
arguments: ["@request_stack"]
lazy: true
tags:
- { name: "doctrine.orm.entity_listener", entity: App\Entity\Translation\Translatable, event: postLoad }
Entity listener:
namespace App\EventListener;
use App\Entity\Translation\Translatable;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\HttpFoundation\RequestStack;
class LocaleListener
{
private $currentLocale;
public function __construct(RequestStack $rs)
{
$this->currentLocale = $rs->getCurrentRequest()->getLocale();
// $this->currentLocale === "en"
}
public function postLoad(Translatable $translatable, LifecycleEventArgs $args)
{
$translatable->setLocale($this->currentLocale);
// e.g. url: mywebsite.be/nl
// Why is $this->currentLocale === "en"?
}
}
What am I doing wrong?