Wednesday, June 17, 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, entityIdSchemaName, entityId, rollup_fieldName)
{
debugger;
var formContext = executionContext.getFormContext();
var clientUrl = formContext.context.getClientUrl();


var Sdk = window.Sdk || {};

Sdk.CalculateRollupFieldRequest = function (entityName, rollup_fieldName) {
    this.Target = entityName;
    this.FieldName = rollup_fieldName;
};

Sdk.CalculateRollupFieldRequest.prototype.getMetadata = function () {
    return {
        boundParameter: null,
        parameterTypes: {
            "Target": {
                "typeName": "mscrm.crmbaseentity",
                "structuralProperty": 5
            },
            "FieldName": {
                "typeName": "Edm.String",
                "structuralProperty": 1
            }
        },
        operationType: 1, // This is a function. Use '0' for actions and '2' for CRUD
        operationName: "CalculateRollupField"
    };
};

// Create variables to point to a quote record and to a specific field

var projectId = {};

projectId["@odata.type"] = "Microsoft.Dynamics.CRM." + entityName

projectId[entityIdSchemaName] = entityId;



// Create variable calculateRollupFieldRequest and pass those variables created above
var calculateRollupFieldRequest = new Sdk.CalculateRollupFieldRequest(projectId, rollup_fieldName);

// Use the request object to execute the function
Xrm.WebApi.online.execute(calculateRollupFieldRequest).then(
    function (response) {
        if (response.ok) { // If a response was received.
            console.log("Status: %s %s", response.status, response.statusText);

            // Use response.json() to access the content of the response body.
            response.json().then(
                function (responseBody) { //Do something with the response
                    console.log("The response is: %s", responseBody);
                });
        }
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    });        
       
}

Syntax for calling the method

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

}

I hope you find this useful.

Thanks.
Vipin



---------------------Refer other blog post here---------------------

Most common JavaScript methods for Dynamic 365 CRM