Skip to main content

Notifications

Announcements

No record found.

Dynamics 365 general forum

Run Workflow when form loads

Posted on by Microsoft Employee

Hello,

I am trying to run a specific workflow when a user loads a specific entity. I'm using a workflow to copy account balances from one entity to another, but I need the balances to update whenever a user loads the page where the data is copied to. Account balances change daily on the source entity.

I've copied code from other forums and input my one workflow and entity IDs, I get the confirm window to pop up, but the workflow doesn't run. Any suggestions on how I can get this to work?

function RunWorkflow() {
var _return = window.confirm('Do you want to update the data?');
if (_return) {
var url = Xrm.Page.context.getServerUrl();
var entityId = '8AF4749E-41AE-E911-9136-00505694692C';
var workflowid = '97BED1B8-5D32-40D7-9EB2-BE5996E35F0A';
var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
url = url + OrgServicePath;
var request;
request = "<s:Envelope xmlns:s=\""">schemas.xmlsoap.org/.../\">" +
"<s:Body>" +
"<Execute xmlns=\"">schemas.microsoft.com/.../Services\" xmlns:i=\""">www.w3.org/.../XMLSchema-instance\">" +
"<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"">schemas.microsoft.com/.../Contracts\" xmlns:b=\""">schemas.microsoft.com/.../Contracts\">" +
"<a:Parameters xmlns:c=\""">schemas.datacontract.org/.../System.Collections.Generic\">" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>EntityId</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\""">schemas.microsoft.com/.../\">" + entityId + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>workflowid</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\""">schemas.microsoft.com/.../\">" + workflowid + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"</a:Parameters>" +
"<a:RequestId i:nil=\"true\" />" +
"<a:RequestName>ExecuteWorkflow</a:RequestName>" +
"</request>" +
"</Execute>" +
"</s:Body>" +
"</s:Envelope>";

var req = new XMLHttpRequest();
req.open("POST", url, true)
// Responses will return XML. It isn't possible to return JSON.
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "">schemas.microsoft.com/.../Execute");
req.onreadystatechange = function () { assignResponse(req); };
req.send(request);
}
}

function assignResponse(req) {
if (req.readyState == 4) {
if (req.status == 200) {
alert('successfully executed the workflow');
}
}
}

Thank you!

  • Suggested answer
    LeoAlt Profile Picture
    LeoAlt 16,329 on at
    RE: Run Workflow when form loads

    Hi partner,

    Thank you for your recognition, as I know, "Execute workflow" action also supports V8.2, the web api of V9.0 only add three other actions.

    I found a sample code for you.

    https://www.inogic.com/blog/2016/11/execute-workflow-using-web-api-in-dynamics-365-2/

    Best Regards,

    Leo

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Run Workflow when form loads

    Hi Leo,

    That is helpful. I think my issue here is that I'm on D365 v8.2 and it's hosted so I don't have the ability to upgrade until next year. Sounds like the web API won't work on older versions. That may explain why this code didn't work for me.

    Thanks for your help, I appreciate your efforts.

    Mark

  • Suggested answer
    LeoAlt Profile Picture
    LeoAlt 16,329 on at
    RE: Run Workflow when form loads

    Hi mfanning,

    Now in D365 V9, we could use web api to call a workflow directly.

    Here are the sample code for you.

    var clientUrl = Xrm.Page.context.getClientUrl();
    var workflowId = "24dc5603-a117-4221-a7bb-5b6ed17a1810";
    var entityId = "B0A19CDD-88DF-E311-B8E5-6C3BE5A8B200";
    
    var requestUri = clientUrl + "/api/data/v9.0/workflows(" + workflowId + ")/Microsoft.Dynamics.CRM.ExecuteWorkflow";
    
    var xhr = new XMLHttpRequest();
    xhr.open("POST", requestUri, true);
    xhr.setRequestHeader("Accept", "application/json");
    xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xhr.setRequestHeader("OData-MaxVersion", "4.0");
    xhr.setRequestHeader("OData-Version", "4.0");
    xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
            xhr.onreadystatechange = null;
            if (this.status == 200) {
                var result = JSON.parse(this.response);
            } else {
                var error = JSON.parse(this.response).error;
            }
        }
    };
    xhr.send("{\"EntityId\":\"" + entityId + "\"}");

    You could also refer to the following blogs.

    https://www.ashishvishwakarma.com/executing-workflows-using-javascript-c-sharp-example-dynamics-365/

    https://www.inogic.com/blog/2019/05/execute-workflow-using-xrm-webapi-online-execute-method-via-javascript-in-dynamics-365-crm-v9/

    Hope it helps.

    Best Regards,

    Leo

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Run Workflow when form loads

    Justin,

    Thanks for your response. I did check again and the workflow is set to 'on-demand.' I copied your suggested code, but it didn't work for me. Based on your description above, I'm thinking this is beyond my capability. I was hoping to be able to copy and paste some code and add in the ID numbers, but there seems to be more to it than that.

  • Suggested answer
    Justin Burch Profile Picture
    Justin Burch 25 on at
    RE: Run Workflow when form loads

    Just to make sure, have you set this workflow to "Run on Demand"? This would be a requirement to run the workflow this way. An alternative, if you'd like to prevent users from manually running it on demand, would be to convert this work to an Action. Sample code can be found on calling Actions via Web API.

    That being said, it's not recommended to use SOAP messages going forward; you should use the Web API provided methods. Using the example located @ https://d365globalcommunity.com/execute-workflow-using-web-api-in-dynamics-365/, here is some expected code for you - note that in the past, I've had to not use JSON.parse with the API responses - you may run into that here, as I have not tested this:

    function RunWorkflow() {
    var recordId = Xrm.Page.data.entity.getId(); // "8AF4749E-41AE-E911-9136-00505694692C"
    var workflowId = "{97BED1B8-5D32-40D7-9EB2-BE5996E35F0A}";
    try {
    var query = "workflows(" + workflowId.replace("}", "").replace("{", "") + ")/Microsoft.Dynamics.CRM.ExecuteWorkflow";
    var data = {
    "EntityId": recordId
    };
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/" + query, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 200) {
    console.log("Success: " + JSON.parse(this.response));
    } else {
    console.error("Error: " + JSON.parse(this.response).error);
    }
    }
    };
    req.send(JSON.stringify(data));
    } catch (e) {
    alert('An error has occurred running workflow:' + e);
    }
    }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans