Update Rollup Field at onload Event in Dynamics 365 using JavaScript
1 min readMay 17, 2022
I have created a dynamic function for the ease of use. You just have to pass the function parameters.
Let me explain it with an example
We have a field “pin_numberofproducts” in “opportunities” entity which is rollup field and we want to update its value on load of form.
I have divided function in two separate functions for better understanding.
function onLoadEvent (executionContext)
{
var entityName = 'opportunities'; // Name of Entity
var rollup_fieldName = 'pin_numberofproducts'; // Rollup Field
var entityId = formContext.data.entity.getId().replace('{', '').replace('}', ''); // GUID of current record
refreshRoleupField(executionContext,entityName , entityId, rollup_fieldName ); // Function Call to update value
}
All the changes will be done in this onLoadEvent function.
Next function will remain same
Note: I am using 9.1 API if you are using different please change accordingly
function refreshRoleupField (executionContext, entityName, entityId, rollup_fieldName)
{
var formContext = executionContext.getFormContext();
var clientUrl = formContext.context.getClientUrl();// Method Calling and defining parameter
var rollupAPIMethod = "/api/data/v9.1/CalculateRollupField(Target=@tid,FieldName=@fn)";// Passing Parameter Values
rollupAPIMethod += "?@@odata.id">tid={'@odata.id':'" + entityName + "(" + entityId + ")'}&@fn='" + rollup_fieldName + "'";var req = new XMLHttpRequest();
req.open("GET", clientUrl + rollupAPIMethod, false);
req.onreadystatechange = function ()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
console.log("Field Recalculated successfully");
}
}
};req.send();
formContext.data.entity.save();
}
At the end call the onLoadEvent() function on the onload event.