Advertising sustains the DA. Ads are hidden for members. Join today

Computed Field

Converting currency

Last updated on
30 April 2025

I used this snippet with the currency api and the Money CCK modules.

In this code, I have an initial amount of money ($total_amount), may be in euros or in other currency ($currency field), that is the money expended by one of our distributor (both fields are provided by money cck module.). We have to evaluated the project of our distributor and check if we return the 50%, 25% or 0%, depending of several factors. This is the $result field.

In the step 2, I calculated the import to return according to our evaluation.

And finally, in the 3rd step , we write the $node_field[0]['value'] with the import to return, but first we check if the currency if in euros and if not, we convert in order to present this amount in €, all this with the help of the currency_api_convert function.

The $currency field stores the currency ISO, the same that uses the currency api to convert the money.

<?php
// Step 1
$total_amount = $node->field_coop_total[0]['amount'];
$result = $node->field_coop_result[0]['value'];
$currency = $node->field_coop_total[0]['currency'];

// Step 2
$total_result = number_format($total_amount*$result/100 ,2);

// Step 3

if ($currency == 'EUR') {

  $node_field[0]['value'] = $total_result.' '.$currency;

}else{

  $from = $currency;
   $to   = 'EUR';
   $amt  = $total_result;
  if (module_exists('currency') && function_exists('currency_api_convert')) { 
   $ret = currency_api_convert($from, $to, $amt);
  $node_field[0]['value'] = $ret['value'].' €';
  }else{
    $node_field[0]['value'] = $total_result;
  }
}
?>

Help improve this page

Page status: Not set

You can: