Calculate RollupField using Javascript WebApi

As we know that rollup field recalculate values every hour but in some cases if we need to recalculate value to represent the value on another entity, then we can do it using JavaScript Web API.

Suppose, Rollup field is mapped with another entity and we need latest value of rollup on create of related entity record then below code is useful to achieve your requirements :

The CalculateRollupField function inside the web request requires few parameter to know which rollup field you want to to calculate:

  • The EntitySetName of the target record.
  • The GUID of the target record.
  • The schema name of the target field.

function calculateRollupField(TargetEntitySetName, TargetRecordId, TargetRollupFieldName)
   TargetRecordId= TargetRecordId.replace("{", "").replace("}", "");
    var req = new XMLHttpRequest();, this.url, true); // Need this to initiate the request
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("OData-MaxVersion", "4.0");"GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" +
        "CalculateRollupField(Target=@p1,FieldName=@p2)?" +
        "@p1={'':'" + TargetEntitySetName+ "(" + TargetRecordId+ ")'}&" +
        "@p2='" + TargetRollupFieldName+ "'", true);
    req.onreadystatechange = function ()
        if (this.readyState === 4)
            req.onreadystatechange = null;
            if (this.status === 200)
                var results = JSON.parse(this.response);
                //Use XRM commands to perform operation..

We can retrieve the updated value via JavaScript API call and use XRM commands to replace the updated value in the form.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s