Calling a Dynamics 365 Action from JavaScript using Xrm.WebApi.online.execute

8 Comments

In this post, we will continue with our example of calling a Dynamics 365 action from JavaScript, this time using the Xrm.WebApi.

In the previous example, on saving a case, we would call an action to send an email to a developer if the title of the case contained the word “bug”. The action would accept 2 inputs, a “to” user and a “from” user to send the email to and from.

Our action looks like this, with 2 input parameters of type EntityReference User:

We will need to get the metadata for this action. To do this, browse to https://yourorg.crm.dynamics.com/api/data/v9.1/$metadata and find your action, in this case new_RouteBugtoDeveloper. You will see the parameters and the types:

Now, we can build the request to send to the xrm.webapi endpoint. The details of the request can be found here: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-webapi/online/execute

The request object contains the following parameters:

  • boundParameter – we can see from the metadata that IsBound = true. This means it is bound to an entity, not global. If it is bound, we set boundParameter to the word “entity”.
  • operationName – this is the name of the action, in our case, new_RouteBugtoDeveloper
  • operationType – 0 for actions
  • parameterTypes – this are the parameters we will pass to the action. This includes:
    • enumProperties – the metadata for enum types
    • structuralProperty – 0 = Unknown, 1 = Primitive, 2 = ComplexType, 3 = EnumerationType, 4 = Collection, 5 = EntityType

Now the code. We are creating an object for the target, which we will run our code on. We are also creating an object for the FromUser and the ToUser. We will pass all of these as parameters to our action:


function RunAction() {

    var Id = Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');

    var target = {};
    target.entityType = "incident";
    target.id = Id;

    var fromUser = {};
    fromUser.entityType = "systemuser";
    fromUser.id = "9C9CA531-E021-E911-A9BC-000D3A1B913D";

    var toUser = {};
    toUser.entityType = "systemuser";
    toUser.id = "6E8B062B-E021-E911-A9BC-000D3A1B913D";

    var req = {};
    req.FromEmail = fromUser;
    req.ToEmail = toUser;
    req.entity = target; 
    req.getMetadata = function () {
        return {
            boundParameter: "entity",
            parameterTypes: {
                "entity": { 
                    typeName: "mscrm.incident", 
                    structuralProperty: 5 
                },
                "FromEmail": {
                    "typeName": "mscrm.systemuser",
                    "structuralProperty": 5
                },
                "ToEmail": {
                    "typeName": "mscrm.systemuser",
                    "structuralProperty": 5
                }
            },
            operationType: 0,
            operationName: "new_RouteBugtoDeveloper"
        };
    };

    Xrm.WebApi.online.execute(req).then( 
        function (data) { 
            var e = data; 
            debugger; 
        }, 
        function (error) { 
            debugger; 
            var errMsg = error.message; 
        }
    );
}

Now, we will run this on saving a case. We can see the URL as: https://xxxxx.crm.dynamics.com/api/data/v9.0/incidents(5CACFC14-2050-E911-A986-000D3A18BAB7)/Microsoft.Dynamics.CRM.new_RouteBugtoDeveloper

The action has run successfully.

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

8 Responses to Calling a Dynamics 365 Action from JavaScript using Xrm.WebApi.online.execute

  1. hello,
    thanks for this great article but can you show how to pass a date time parameter to action in same way,
    i’ve tried but no success
    var date = new Date(‘2019-11-5’).toISOString();
    var request = {
    StartDate: date,
    getMetadata: function () {
    return {
    boundParameter: null,
    operationType: 0,
    operationName: “gzt_CustomReportsCPUTicketAging”,
    parameterTypes: {
    “StartDate”: {
    structuralProperty: 1,
    typeName: “Edm.DateTimeOffset”
    }
    }
    }
    }
    };

    Xrm.WebApi.online.execute(request).then(
    function success(result) {
    if (result.ok) {
    // perform operations as required
    console.log(result);

    debugger;

    }
    },
    function (error) {
    console.log(error.message);
    debugger;
    // handle error conditions
    }
    );

    • Hi, your code should work, although you need to stringify your date variable, like this:

      StartDate: JSON.stringify(date)

      Also, if you have a workflow assembly in your action which expects a Date parameter with exactly the same name as your Input Parameter of your Action, oddly enough the action call crashes… so try renaming your action input parameter. Hope this helps

  2. Hi Carl,
    thank you for the blog entry, this is really useful.

    do you have an example with processing Action output parameters in JavaScript?

  3. Hi Carl,

    I’m using fetch api aginst Dynamics 365 online like this:

    const requestBody = JSON.stringify({“IssueSend”: ‘true’});
    const url = `…/api/data/v9.2/emails(GUID)/Microsoft.Dynamics.CRM.SendEmail`;
    const fetchResult = await fetch(url,
    {
    method: ‘POST’,
    headers: { ‘Content-Type’: ‘application/json’, ‘Prefer’: return=representation’ },
    body: requestBody
    });

    Is it possible to do the same using Xrm.WebApi.online.execute(req) ?
    I get “Resource not found for the segment ‘Microsoft.Dynamics.CRM.SendEmail'” with the code below.

    const target = {
    entityType: ’email’,
    id: activityId
    };

    const req = {};
    req.entity = target;
    req.IssueSend = true;

    req.getMetadata = function () {
    return {
    boundParameter: null,
    parameterTypes: {
    “entity”: {
    “typeName”: “email”,
    “structuralProperty”: 5

    },
    “IssueSend”: {
    “typeName”: ‘Edm.Boolean’,
    “structuralProperty”: 1
    }
    },
    operationType: 0,
    operationName: ‘Microsoft.Dynamics.CRM.SendEmail’
    };
    };

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *