Looking for PowerObjects? Don’t worry, you’re in the right place! We’ve been part of HCL for several years, and we’ve now taken the final step in our acquisition journey: moving our website to the HCL domain. Nothing else is changing – we are still fanatically focused on Microsoft Business Applications!

PowerObjects Blog 

for Microsoft Business Applications


Use Javascript to Update Price Per Unit When Selecting a Product in Dynamics CRM 2011

Post Author: Joe D365 |

If you enter a lot of products in Dynamics CRM, this JavaScript tip will save you time. We'll review the JavaScript you can use to allow the user to see the 'Price' from the Price List for a selected Product. This can be used/modified for Quote Product, Order Product, or Invoice Product. The example below is for Opportunity Product. (In our next blog, we'll cover another example where user has already selected the Product, but upon changing the Unit, the appropriate 'priceperunit' value is populated.)

Once a user has selected the Product and Unit, now we have enough information to target the Price from the parent Price List. The JavaScript I have provided below will pull the Price from the associated 'Price List Item' (using the ProductId guid, Unit guid, and Price List guid) and populate the 'Price per Unit' field, all before saving! This will save time, allowing user to verify the price before they create an Opportunity Product record.

Use Javascript to Update price per unit

Notice! – Before JavaScript will work, make sure to add the SDK.REST library, JQuery, and JSON2 library. These libraries are found in the SDK, available for download. The files must be added as web resources and added to the Form Library for Opportunity Product. Also, this JavaScript must be added as web resource and to trigger upon the OnChange event for Product. See below.

So let's go through this step by step. (Some of the images may appear small. For a bigger view, right click and select View Image. JavaScript is also posted at the bottom of the blog post.) We started by checking to make sure the Product has been selected on the form, and store that GUID in 'productFieldId'. We check to make sure not null, then continue.

Once we have the productField Guid, we can build our oData query for Ajax. Here we are grabbing the page context, the server Url, adding the DataPath (notice this is for CRM 2011 On-premise). As for oDataSelect, we add our predefined oData Query that we generated using the OData Query Designer. Notice I inserted our productFieldId into the query to have it return the DefaultUoMId (default unit for the product).

NOTICE! – You will want to double check your own value for oDataPath as it may be different for your On-Premise or Online Dynamics CRM.

Now we can conduct our Ajax call. The Ajax call itself won't return the GUID to our main method, but will call a separate function upon success. This success function will implicitly return two values, data and status. If we want to pass along more parameters, I must call another method that will allow me to pass more than just data and status. Since I will need oDataPath and productFieldId in our next Ajax call, I will pass these along to my custom function – NowHaveDefaultUnitGuid()

Once in the custom function, we will store the returned Unit GUID in defaultUnitGUID. We will also need to grab the parent Opportunity GUID to include in our next query. We will check to make sure not null and continue.

Here we have used the passed in oDataPath parameter to include in our next query. Notice that the Opportunity GUID is inserted into the query string to return PriceLevelId – or also known as the Price List Guid. Upon success, we will call the custom function NowWeHaveEverything.

This will be our last Ajax call to return us the Price List Item field value for Amount (this is what will populate price per unit). Here we take the passed parameter data and sotre the PriceLevelId guid into PriceLevelId. Notice we use all three GUID's in our Odata query.

Here upon success, we call our custom function havePrice and pass data and the defaultUnitGUID we passed along from earlier.

Here we check to make sure the passed in defaultUnitGUID is not null, then proceed to store the Amount value in priceListItemAmount. Our last step is to update these values on the form, and also set the Unit using the defaultUnitGUID.

Voila! That's it!

JavaScript Below:

[sourcecode language="JavaScript"]

function updateProductPrice(){

//Developed by PowerObjects 11/9/2012

//This jscript is intended to fire off on the OnChange event of the Product lookup on Opportunity Products

//Once user inputs a product, the default unit for the product will set, and price per unit, from the Price List Item, will populate below

//This javascript assumes there are price lists.

var productField = Xrm.Page.getAttribute('productid').getValue();

var productFieldId = productField[0].id;

if (productFieldId != null){

//build the query to get the default unit

var pagecontext = Xrm.Page.context;

var serverUrl = pagecontext.getServerUrl();

var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc/";

var oDataSelect = oDataPath + "ProductSet?$select=DefaultUoMId&$filter=ProductId eq guid'" + productFieldId + "'";

//Start AJAX call to get default unit guid from product

$.ajax({

type: "GET",

contentType: "application/json; charset=utf-8",

datatype: "json",

url: oDataSelect,

beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },

success: function (data,status) { NowHaveDefaultUnitGuid(data,status,productFieldId,oDataPath);},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert('OData Select Failed: ' + errorThrown + ". There is no default unit associated with product");

}

});

}

}

function NowHaveDefaultUnitGuid(data, status, productFieldId, oDataPath) {

//we are passing the oDataPath and productFieldId since we will still need these variables

var defaultUnitGUID = data.d.results[0].DefaultUoMId;//retrieved defaultUnit guid

var opportunityId = Xrm.Page.getAttribute('opportunityid').getValue();

if (opportunityId != null)

{

var oDataSelect = oDataPath + "OpportunitySet?$select=PriceLevelId&$filter=OpportunityId eq guid'" + opportunityId + "'";

//start AJAX call for the parent price list guid

$.ajax({

type: "GET",

contentType: "application/json; charset=utf-8",

datatype: "json",

url: oDataSelect,

beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },

success: function (data,status) { NowWeHaveEverything(data,status,productFieldId,defaultUnitGUID,oDataPath);},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert('OData Select Failed: ' + errorThrown + ". There is no parent price list");

}

});

}

}

function NowWeHaveEverything(data, status, productFieldId,defaultUnitGUID, oDataPath) {

//now that we have the pricelist guid, default unit guid, we can lookup the price list item to pull the amount value

var priceLevelId = data.d.results[0].PriceLevelId.Id; //retrieved pricelevel

//start AJAX clal for Price List Item entities = Price List GUID and Product Guid and Unit Guid and return the Amount on that price list item. This will return one results.

var oDataSelect2 = oDataPath + "ProductPriceLevelSet?$select=Amount&$filter=(PriceLevelId/Id eq guid'" + priceLevelId + "' and ProductId/Id eq guid'"+ productFieldId +

"' and UoMId/Id eq guid'" + defaultUnitGUID.Id + "')";

$.ajax({

type: "GET",

contentType: "application/json; charset=utf-8",

datatype: "json",

url: oDataSelect2,

beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },

success: function (data,status){ havePrice(data, defaultUnitGUID);},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert('OData Select Failed: '+ errorThrown + ". There is no price list item for this product");

}

});

}

function havePrice(data, defaultUnitGUID){

if(defaultUnitGUID != null){

//set the price per unit

var priceListItemAmount = data.d.results[0].Amount.Value ;

Xrm.Page.getAttribute("priceperunit").setValue(parseFloat(eval(priceListItemAmount)));

Xrm.Page.getAttribute("priceperunit").setSubmitModeAlways;

//set the unit on Opportunity below.

var id = defaultUnitGUID.id;

var name = defaultUnitGUID.Name.toString();

var entityType = defaultUnitGUID.LogicalName.toString();

Xrm.Page.getAttribute("uomid").setValue( [{id: id, name: name, entityType: entityType}]);

}

}
[/sourcecode]

Want more Dynamics CRM JavaScript tidbits? Here are some options for further reading:

Happy CRM'ing!

Joe CRM
By Joe D365
Joe D365 is a Microsoft Dynamics 365 superhero who runs on pure Dynamics adrenaline. As the face of PowerObjects, Joe D365’s mission is to reveal innovative ways to use Dynamics 365 and bring the application to more businesses and organizations around the world.

One comment on “Use Javascript to Update Price Per Unit When Selecting a Product in Dynamics CRM 2011”

  1. Thanks for the script, I found a slight problem with my installation

    var id = defaultUnitGUID.id;
    var name = defaultUnitGUID.Name.toString();
    var entityType = defaultUnitGUID.LogicalName.toString();

    should be

    var id = defaultUnitGUID.Id; <---------------------------------------
    var name = defaultUnitGUID.Name.toString();
    var entityType = defaultUnitGUID.LogicalName.toString();

PowerObjects Recommends