Use Field Aliasing for ConvertCurrency

This post is more of a cautionary tale so you won’t be a bonehead like me. I recently wrote some code that queried OpportunityLineItem and used the ConvertCurrency function to get the TotalPrice in the user’s currency. The problem was that later in the code, I did an update to that same record. Since I had converted the currency using the formula, the update replaced the value with the converted value, but left the record currency in the foreign value.

My solution was to use a new feature in Spring 16 that lets you alias ConvertCurrency fields. With the field aliased, updates no longer change the monetary value, and problem solved!

OpportunityLineItem oli = [Select Id, convertcurrency(TotalPrice) usdprice from OpportunityLineItem where Id = '00k4B000003ESxW'];
// Use get to access the value
System.debug(oli.get('usdprice'));
// Safely update without overwriting the value
update oli;

Leave a Reply