Samia Ruponti
Samia Ruponti

Reputation: 4038

Symfony2 getLocal() in post load lifecycle event

I am developing a application with symfony2. Im facing a problem with localization. I want to set the in the postLoad event in doctrine lifecycle, but can find a way to do that. I am using the route method to set my local for example:

http://example.com/en/content

here is my listener:

namespace MyApiBundle\Listener;

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

use Doctrine\ORM\Event\LifecycleEventArgs;



class LocaleListener
{
private $local;

public function __construct($local) {

    $this->local = $local;
}


public function postLoad(LifecycleEventArgs $args)
{


    $local= 'en'; // I need to get the local from here

    $entity = $args->getEntity();
    if(method_exists($entity, 'setLocale')) {
        $entity->setLocale($local);
    }
}

}

Is there any quick way get the local from here? Cant use the new Request() as it always returning the en I also have 3 other language. Thanks for help

Upvotes: 2

Views: 318

Answers (2)

Samia Ruponti
Samia Ruponti

Reputation: 4038

Thanks @Igor Pantovic

here I got it work, here is my local listner:

#/src/MyApiBUndle/Listner/LocalListner.php

namespace MyApiBundle\Listener;

use Symfony\Component\HttpFoundation\RequestStack;
use Doctrine\ORM\Event\LifecycleEventArgs;



class LocaleListener {

   
   private $requestStack;

/**
 * @param RequestStack $requestStack
 */
public function __construct(RequestStack $requestStack) {

    
    $this->requestStack = $requestStack;
}


/**
 * @param LifecycleEventArgs $args
 */
public function postLoad(LifecycleEventArgs $args)
{

    $local= $this->requestStack->getCurrentRequest()->getLocale();

    $entity = $args->getEntity();
    if(method_exists($entity, 'setLocale')) {
        $entity->setLocale($local);
    }
}

}

and my service

services:
my_api.listener.locale_listener:
        class:  MyApiBundle\Listener\LocaleListener
        tags:
            - { name: doctrine.event_listener, event: postLoad }
        # @request_stack must be quoted "":
        arguments: ["@request_stack"]

hope this will help other too

Upvotes: 2

Igor Pantović
Igor Pantović

Reputation: 9246

Yes, you can. You can inject @request_stack service into your listener, get request from it and read locale.

There is, however, a Doctrine extension that probably does what you want: Translatable

Upvotes: 3

Related Questions