0

I'm trying to add a feature of multi language to my application using API Plateform and ReactJS. I've installed StofDoctrineExtensionsBundle, I want to use the extension Translatable. I send the local("EN" or "FR" etc) then I want to send response swtich the local.

use Gedmo\Translatable\Translatable;

/**
 * @ApiResource()
 * @ORM\Entity(repositoryClass=CountryRepository::class)
 */
class Country implements Translatable
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @Gedmo\Translatable
     * @ORM\Column(type="string", length=255)
     */
    private $name;

services.yml

App\EventSubscriber\LocaleSubscriber:
    arguments: ['%kernel.default_locale%']

LocaleSubscriber.php

<?php
namespace App\EventSubscriber;

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

class LocaleSubscriber implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct(string $defaultLocale = 'en')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        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));
        }
    }

    public static function getSubscribedEvents()
    {
        return [
            // must be registered before (i.e. with a higher priority than) the default Locale listener
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
        ];
    }
}

In the response of the webservice which allows me to get the list of countries there is no name field.

How can I get the names of the countries switch the language ? Thanks.

1 Answer 1

0

AFAIK it is not very RESTfull to use the session, your api will no longer be stateless.

You can use the accept-language request header. Most browsers automatically send it with each request. Here is an event subscriber that puts it in symfonies request obect:

<?php
// src/EventSubscriber/LocaleSubscriber.php

namespace App\EventSubscriber;

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

class LocaleSubscriber implements EventSubscriberInterface
{

    public function onKernelRequest(RequestEvent $event)
    {
        $request = $event->getRequest();
        $accept_language = $request->headers->get("accept-language");
        if (empty($accept_language)) {
            return;
        }
        $arr = HeaderUtils::split($accept_language, ',;');
        if (empty($arr[0][0])) {
            return;
        }

        // Symfony expects underscore instead of dash in locale
        $locale = str_replace('-', '_', $arr[0][0]);

        $request->setLocale($locale);
    }

    public static function getSubscribedEvents()
    {
        return [
            // must be registered before (i.e. with a higher priority than) the default Locale listener
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
        ];
    }
}

If you want the user to be able to choose the locale dynamically i suppose adding the accept-language request header from your own code with each request will override the default of the browser.

I made this EventSubscriber for my tutorial. Chapter 3 is about Localization and Internationalization. The api side was easy in comparision to the react client side.

Sign up to request clarification or add additional context in comments.

1 Comment

BTW, don't you need to add some configuration to activate the Doctrine EventSubscriber that implements the functionality of Translatable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.