Tuesday, March 3, 2020

Generic way to Refresh Rollup field in Dynamic CRM

Opportunity Roll-up fields




Opportunity Products Grid




Roll-up fields Definition





Generic method to re-calculate and refresh the Rollup field.

refreshRoleupField: function (executionContext, entityName, entityId, rollup_fieldName)
{
 debugger;
 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 += "?@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();
}

Syntax for calling the method

onLoad: function (executionContext)
{
    var entityId = formContext.data.entity.getId().replace('{''').replace('}''');
    opty.Functions.refreshRoleupField(executionContext, 'opportunities', entityId, 'new_totalunitcost');
    opty.Functions.refreshRoleupField(executionContext, 'opportunities', entityId, 'new_sumextendedcost');

}

I hope you find this useful.

Thanks.

3 comments:

krombipils said...

Could you please elaborate a little more about how to use this code? I have a parent-child relationship and I would like to immediately update a rollup field on the parent whenever a child is created/updated/deleted. How should I call your code?
And there is a hardcoded totalamount attribute in your code. Does this make sense?
Thank you!

GoodGirlGa said...

Thanks for sharing an idea, but for me refreshing by "Save" doesn't work because of 'Don't have dirty changes to save' error. I use refresh instead but it triggers reloading table and endless loop. I break it with global boolean variable, but this way seems ugly and furthermore - do not stable.

Jebz said...

Thanks Vipin