0

I'm using PHP Symfony and i have a multilanguage website, in order to test some things i want to set website language from code not matter what user choose on the frontend, i did this:

    $request->setLocale('en');
    $request->getSession()->set('_locale', 'en');
    var_dump($request->getLocale());die;

I receive en but this still does not change my language of the whole website. I tried to switch language as a user and that works, but i want to be always english as i set in the code, any advice?

1 Answers1

0

First, have you correctly define languages in your config ? For example here's my configuration :

config/services.yaml: (for default values)

parameters:
    locale: 'en'
    app_locales: en|fr #|de|es|pt|

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true
        autoconfigure: true
        bind:
            $locale: "@=service('request_stack').getCurrentRequest().getLocale()"
            $defaultLocale: "%locale%"
            $listLocales: '%app_locales%'

config/packages/translation.yaml :

framework:
    default_locale: '%locale%'
    translator:
        default_path: '%kernel.project_dir%/translations'
        fallbacks:
            - '%locale%'

config/packages/translation.yaml

framework:
    default_locale: '%locale%'
    translator:
        default_path: '%kernel.project_dir%/translations'
        fallbacks:
            - '%locale%'

Maybe it's useless for you, but since Symfony 4, you can force locale in route like this following https://symfony.com/doc/current/routing.html#localized-routes-i18n :

controllers:
    resource: ../../src/Controller/
    type: annotation
    prefix:
        en: /
        fr: /{_locale}
        de: /{_locale}
        es: /{_locale}
        pt: /{_locale}
    requirements:
        _locale: '%app_locales%'
    defaults:
        _locale: '%locale%'

If you want to force in english, you can create an EventSubscriber who force in english : services.yaml :

    App\EventListerner\LocaleSubscriber:
        arguments: ['%kernel.default_locale%']
        tags: [kernel.event_subscriber]

App\EventListerner

<?php

namespace App\EventListerner;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Set locale into session
 * Class LocaleSubscriber
 * @package App\EventSubscriber
 */
class LocaleSubscriber implements EventSubscriberInterface
{

    private string $defaultLocale;

    /**
     * LocaleSubscriber constructor.
     * @param string $defaultLocale
     */
    public function __construct(string $defaultLocale = 'en')
    {
        $this->defaultLocale = $defaultLocale;
    }

    /**
     * @param RequestEvent $event
     */
    public function onKernelRequest(RequestEvent $event): void
    {
        /** @var Request $request */
        $request = $event->getRequest();

        if (!$request->hasPreviousSession()) {
            return;
        }

        // Change here to force in english
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => [
                ['onKernelRequest', 20]
            ]
        ];
    }
}

Astro-Otter
  • 736
  • 1
  • 10
  • 22
  • how to call this onKernelRequest function from other script and request and language parameters? –  Nov 15 '21 at 06:43