Magento 1.9 – How to Translate Within Observer

event-observerlocalisationmagento-1.9

I've written a module with an observer but when I try and use $this->__('something to translate') within the observer, I get the error Fatal error: Call to undefined method CompanyName_ModuleName_Model_Observer::__()

I assume this is failing because my observer class doesn't extend a Magento base class, so there is no code that would include my helper and hence the translation methods.

I've searched the Magento 1.9 codebase and can't find any examples of translations within an observer. I'm guessing this means that translating within an observer is not the Magento way, but I can't think of any other way of achieving what I want.

My Observer code is

<?php
class CompanyName_ModuleName_Model_Observer
{
    public function testfunction(Varien_Event_Observer $observer)
    {
        $test = $this->__('test translation');
    }
}

My config.xml look like this

<?xml version="1.0"?>
<config>
    <modules>
        <CompanyName_ModuleName>
            <version>0.1.0</version>
        </CompanyName_ModuleName>
    </modules>
    <global>
        <models>
            <modulename>
                <class>CompanyName_ModuleName_Model</class>
            </modulename>
        </models>
        <helpers>
            <modulename>
                <class>CompanyName_ModuleName_Helper</class>
            </modulename>
        </helpers>
        <events>
            <controller_action_predispatch_checkout_onepage_saveBilling>
                <observers>
                    <companyName_modulename>
                        <type>singleton</type>
                        <class>modulename/observer</class>
                        <method>signupPreference</method>
                    </companyName_modulename>
                </observers>
            </controller_action_predispatch_checkout_onepage_saveBilling>
        </events>
  </global>
</config>

And I have a Helper/Date.php which looks like

<?php
class CompanyName_ModuleName_Helper_Data
    extends Mage_Core_Helper_Abstract
{

}

Best Answer

Instead of using $this->__('something to translate'), use Mage::helper('modulename')->__('something to translate')

I searched the Magento codebase further and there are examples of this being used in core Magento modules, so I assume its the correct process.

Related Topic