Magento – Get Translation for Each Store Using Event Observer

event-observerlocalisation

I am trying to get the translation of a string for each store in my magento admin. I have five stores with different languages, the translations are given in .csv files for each store.

What I try to achieve is to get a collection of all stores and to print out the translation of a predefined string for each store from an observer class. I was able to get the store collection and I have the country codes but I was not able to get the translations. What is the best way to achieve this or is it possible at all?

Thanks in advance!

Best Answer

You can load a different translation for $newLocaleCode like this:

Mage::getSingleton('core/translate')
    ->setLocale($newLocaleCode)
    ->init(Mage_Core_Model_App_Area::AREA_FRONTEND, true);

To also take other locale settings like number and currency formatting into account:

Mage::app()->getLocale()->setLocaleCode($newLocaleCode);

But it's a good idea to do this within an emulated store, with the core/app_emulation model, that Magento uses for example to send transactional emails from backend/cron with the right design and configuration for their associated store. This way it gets set back afterwards.

Example

protected $_helper;

public function translateInStore($storeId, $string)
{
    $newLocaleCode = Mage::getStoreConfig(
        Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeId
    );
    $initialEnvironmentInfo = Mage::getSingleton('core/app_emulation')
        ->startEnvironmentEmulation($storeId);
    Mage::app()->getLocale()->setLocaleCode($newLocaleCode);
    Mage::getSingleton('core/translate')->setLocale($newLocaleCode)->init(Mage_Core_Model_App_Area::AREA_FRONTEND, true);

    $translatedString = $this->_helper->__($string);

    Mage::getSingleton('core/app_emulation')
        ->stopEnvironmentEmulation($initialEnvironmentInfo);

    return $translatedString;
}
Related Topic