Pimcore Translator has a wrong locale in static routes when country context is missing in language attribute.
Eg. Document locale: de_CH, static route: www.project.ch/de/my-static-route/object-xy
Fix in project:
<?php
namespace App\EventListener;
use I18nBundle\Helper\RequestValidatorHelper;
use I18nBundle\Resolver\PimcoreDocumentResolverInterface;
use Pimcore\Model\Document;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class StaticRouteLocaleListener implements EventSubscriberInterface
{
protected PimcoreDocumentResolverInterface $pimcoreDocumentResolver;
protected RequestValidatorHelper $requestValidatorHelper;
public function __construct(
PimcoreDocumentResolverInterface $pimcoreDocumentResolver,
RequestValidatorHelper $requestValidatorHelper)
{
$this->pimcoreDocumentResolver = $pimcoreDocumentResolver;
$this->requestValidatorHelper = $requestValidatorHelper;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onKernelRequestLocale', 17], // before symfony LocaleListener
]
];
}
public function onKernelRequestLocale(RequestEvent $event)
{
if ($event->isMainRequest() === false) {
return;
}
$request = $event->getRequest();
$document = $this->pimcoreDocumentResolver->getDocument($request);
if (!$document instanceof Document) {
return;
}
if (!$this->requestValidatorHelper->isValidForRedirect($request)) {
return;
}
$documentLocale = $document->getProperty('language');
$requestSource = $request->attributes->get('pimcore_request_source');
if ($requestSource === 'staticroute' && !empty($documentLocale) && $request->attributes->get('_locale') !== $documentLocale) {
$request->attributes->set('_locale', $documentLocale);
}
}
}
Pimcore Translator has a wrong locale in static routes when country context is missing in language attribute. Eg. Document locale: de_CH, static route: www.project.ch/de/my-static-route/object-xy
Fix in project: