Friday, March 4, 2011

CRM 2011 Set Default Transaction Currency in JavaScript

The following function uses JSON and OData to select the first Currency entity that is configured on your system and then sets the transactioncurrencyid lookup to be that currency.

This particular feature is just as relevant for CRM 2011 as it was for CRM 4.0, but it is easier to implement now.

The OData selection for this consists of the following:
/TransactionCurrencySet?$select=TransactionCurrencyId,CurrencyName

If you have multiple currencies, you can always add a filter to OData select to grab the specific currency that you need. This function uses the first currency returned.

function SetDefaultCurrency() { var context = Xrm.Page.context; var serverUrl = context.getServerUrl(); var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc"; var odataSelect = ODataPath + "/TransactionCurrencySet?$select=TransactionCurrencyId,CurrencyName"; $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", datatype: "json", url: odataSelect, beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); }, success: function (data, textStatus, XmlHttpRequest) { var myCurrency = data.d.results[0]; var idValue = eval('myCurrency.TransactionCurrencyId'); var textValue = eval('myCurrency.CurrencyName'); var thisEntityType = 'transactioncurrency'; Xrm.Page.getAttribute("transactioncurrencyid").setValue([{ id: idValue, name: textValue, entityType: thisEntityType }]); }, error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); } }); }

In order to use this. You need to make sure that you include jquery1.4.1.min.js and json2.js as libraries first since this script relies on them. Create another library with the above function. If you just call the SetDefaultCurrency function in the OnLoad event of your form, the currency will be set as the form opens and will be be ready for you to set any currency values that rely on this.

image

The jquery1.4.1.min.js and json.js files can be found in the most recent MS CRM SDK. sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts

2 comments:

Unknown said...

I have the routine to use this instead of getServerUrl()..:
function getODataEndPoint() { return Xrm.Page.context.prependOrgName("/xrmservices/2011/OrganizationData.svc"); };
I think this works better if suddenly users have a VPN or something like that

Unknown said...

Great post ,thanks for sharing ,looking for more postings like this.





Dynamics CRM Developers