Doctrine extensions (Gedmo) Translatable - how display translated entity based on current locale

1.1k Views Asked by At

I have the gedmo translatable extension working in my zend framework application. I mean that the following code creates the ext_translations table and inserts the translated articles in the table.

$article = new \App\Entity\Article;
$article->setTitle('my title in en');
$article->setContent('my content in en');
$this->_em->persist($article);
$this->_em->flush();

//// first load the article
$article = $this->_em->find('App\Entity\Article', 1 /*article id*/);
$article->setTitle('my title in de');
$article->setContent('my content in de');
$article->setTranslatableLocale('de_de'); // change locale
$this->_em->persist($article);
$this->_em->flush();

// first load the article
$article = $this->_em->find('App\Entity\Article', 1 /*article id*/);
$article->setTitle('my title in es');
$article->setContent('my content in es');
$article->setTranslatableLocale('es_es'); // change locale
$this->_em->persist($article);
$this->_em->flush();

$article = $this->_em->getRepository('App\Entity\Article')->find(1/* id of article */);
echo $article->getTitle();
// prints: "my title in en"
echo $article->getContent();
// prints: "my content in en"

The above works and prints what I have included in the comments. However, if I change my application locale to es_ES it gives the same output and doesn't seem to notice the change in locale.

In my bootstrap, it is set up as follow :

public function _initLocale() {
        $session = new Zend_Session_Namespace('myswaplocalesession');
        if ($session->locale) {
            $locale = new Zend_Locale($session->locale);
        }

        $config = $this->getOptions();

        if (!isset($locale) || $locale === null) {
            try {
                $locale = new Zend_Locale(Zend_Locale::BROWSER);
            } catch (Zend_Locale_Exception $e) {
                $locale = new Zend_Locale($config['resources']['locale']['default']);
            }

        }
        Zend_Registry::set('Zend_Locale', $locale);

        echo $locale;

        $translator = new Zend_Translate('gettext', APPLICATION_PATH . '/../data/lang/',
                        null, array('scan' => Zend_Translate::LOCALE_FILENAME, 'disableNotices' => 1));


        Zend_Registry::set('Zend_Translate', $translator);
        Zend_Form::setDefaultTranslator($translator);
    }

What am I missing here?

1

There are 1 best solutions below

2
On

You must tell to Gedmo what locale, by default, must use.

You can add these lines when you know what locale to use:

$listener = $this->getDoctrine()->getEventManager()->getListener(
    'Gedmo\Translatable\TranslatableListener'
);

$listener->setTranslatableLocale($locale);