Question

I am trying to convert currency in Magento 1.5 using the following code in a separate file to check currency conversion. I have two stores with respective currency settings in the admin.

set_time_limit(0);
error_reporting(1);
ini_set('display_errors', 1);
define('D_S', DIRECTORY_SEPARATOR);
require_once 'app/Mage.php';
umask(0);
Mage::app();

$_fromCurr = 'USD';
if( Mage::app()->getStore()->getCurrentCurrencyCode() == 'CAD') {
    $_locale = 'en_CA';
    $_toCurr = 'CAD';
} else {
    $_locale = 'en_US';
    $_toCurr = 'USD';
}
$currency = new Zend_Currency($_locale); 
$amount = 150;
echo $_price = $currency->toCurrency(round( Mage::helper('directory')->currencyConvert( $amount, $_fromCurr, $_toCurr ), 2 ));

I am getting following error,

Fatal error: Call to a member function getCode() on a non-object in /var/www/vhosts/www.test.com/httpdocs/app/code/core/Mage/Directory/Model/Currency.php on line 171

I tried following this http://www.magentocommerce.com/boards/v/viewthread/118631/P15/#t381027, but it does not work. What is wrong here?

Was it helpful?

Solution

The PHP fatal error is stemming from a bug in the convert method where it assumes that $toCurrency is an object. The error, however, is being caused when it's trying to throw an exception:

throw new Exception(Mage::helper('directory')->__('Undefined rate from "%s-%s".', $this->getCode(), $toCurrency->getCode()));

The meaning of this error is that the convert method cannot find a rate. I tested your code, and it works fine, as long as the rates exist for the currencies you are converting to/from.

What you'll need to do is navigate to System -> Configuration -> Currency Setup and make sure the currencies you are using are selected in the Allowed Currencies setting.

After you have selected the Allowed Currencies, you'll need to set the rates. You can do this by going to System -> Manage Currency Rates. From there you can either input your own conversion ratios into the grid or import them by clicking the Import button, then click Save Currency Rates.

Once you have the currency rates for the conversion setup, it should work without a hitch.

OTHER TIPS

Try below code it will worked

$_Baseprice = $_product->getPrice(); 
    $_Currentcurrencycode =Mage::app()->getStore()->getCurrentCurrencyCode();
    //This will return USD, EUR e.t.c
    //echo $_Currentcurrencycode;
    if ($_Currentcurrencycode == 'USD') {$_convertedCurrency = Mage::helper('directory')->currencyConvert($cprice, 'SAR', 'USD');}
    else {$_convertedCurrency = Mage::helper('directory')->currencyConvert($cprice, 'SAR', 'SAR');}
    //_convertedCurrency will return price without symbol
    //echo $_convertedCurrency ;
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top