Trigger Workflow Using JavaScript

 In Microsoft Dynamics 365, we can trigger the workflow based on OOB condition(eg. record is created or on change of field, etc).

If we want to trigger the workflow on specific condition which is not present as a OOB then we can use JavaScript to trigger the workflow.

You can follow following code for executing workflow using JavaScript:

ExecuteWorkflowUsingJS: function(executionContext) {
    var formContext = executionContext.getFormContext();
    var ExecuteCustomWorkflowRequest = function(entityID, WorkflowID) {
        this.EntityId = {
            "guid": entityID
        };
        this.entity = {
            id: WorkflowID,
            entityType: "workflow"
        };
        this.getMetadata = function() {
            return {
                boundParameter: "entity",
                parameterTypes: {
                    "entity": {
                        "typeName": "Microsoft.Dynamics.CRM.workflow",
                        "structuralProperty": 5
                    },
                    "EntityId": {
                        "typeName": "Edm.Guid",
                        "structuralProperty": 1
                    }
                },
                operationType: 0,
                operationName: "ExecuteWorkflow",
            };
        };
    };
    var activeWorkflowId = null;
    Xrm.WebApi.online.retrieveMultipleRecords("workflow", "?$filter=name eq 'Workflow Name' and _activeworkflowid_value ne null").then(
        function success(results) {
            for (var i = 0; i < 1; i++) {
                var AccountID = Xrm.Page.data.entity.getId();
                activeWorkflowId = results.entities[i]["workflowid"];
            }
            if (activeWorkflowId != null) {
                var triggerCustomWorflowRequest = new ExecuteCustomWorkflowRequest(AccountID, activeWorkflowId);
                Xrm.WebApi.online.execute(triggerCustomWorflowRequest).then(function successCallBack(result) {
                        alert("Workflow Run Successfully");
                    },
                    function errorCallBack(err) {
                        var alertStrings = {
                            text: err.message,
                            title: "Error Occured"
                        };
                        var alertOptions = {
                            height: 120,
                            width: 260
                        };
                        Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);
                    });
            }

        },
        function(error) {
            Xrm.Utility.alertDialog(error.message);
        });
}

Comments

Popular posts from this blog

Accessing Fields on QuickView Form through javaScript

ADF - (Part 2) Integrate Data From CRM to External system

Power Apps Portals - Lock/Unlock User Account for Invalid Sign In Attempt