Quantcast
Channel: Sam's Activities
Viewing all articles
Browse latest Browse all 3363

Set Values of all Data Types using Web API in Dynamics CRM

$
0
0

In CRM 2016, Microsoft Introduced a new concept called “Web API” (OData v4) to perform CRUD operations as well as other special messages supported in Dynamics CRM. Stepping towards the new enhancement OData v2 is deprecated from the CRM 2016.

Though WEB API too requires the object to be sent in JSON form, it differs a little in the way the values for fields that support complex data type are set. The aim of this blog was to take up most of the common data types used and provide a sample code around how the values need to be set of each of these

Sample code to create an Account Entity Record with all Data Types

///----------- Create with all Data Type (Account) --------
function createAccountWithAllDT() {
    try {
        //declare variables
        var uri = null;
        var stringJSONAcc = null;
        var entityIdWithLink = null;
        var getEntityId = null;

        //create JSON object 
        var JSONAcc = {};

        //set fields using JSON object
        //Single line of text
        JSONAcc.name = "CompanyName Pvt. Ltd."; //Account Name
        //Option Set
        JSONAcc.accountcategorycode = "2" //Category : 1--> Preferred Customer, 2--> Standard

        //Two Options
        JSONAcc.donotsendmm = false;//Marketing Materials : 0-->False/Send, 1-->True/Do Not Send
        //Whole Number
        JSONAcc.numberofemployees = 151; //Number of Employees

        //Decimal Number
        JSONAcc.new_decimalnumber = 345.12; //Decimal Number (Custom Field) 

        //Lookup
        JSONAcc["transactioncurrencyid@odata.bind"] = "/transactioncurrencies(4e950855-9eb3-e511-80de-6c3be5a8ad10)"; //Currency

        JSONAcc["primarycontactid@odata.bind"] = "/contacts(DFE54660-37CD-E511-80DE-6C3BE5A831DC)" //Primary Contact

        //Currency
        JSONAcc.creditlimit = 15000; //Currency Limit

        //Date 
        JSONAcc.new_dateonly = new Date();//Date Only (Custom Field)

        //convert JSON object to string
        stringJSONAcc = JSON.stringify(JSONAcc);

        //url for ajax request to create account
        uri = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts";

        //ajax request to create account
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: uri,
            data: stringJSONAcc,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
                XMLHttpRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=*");
            },
            //Success Callback Function
            success: function (data, textStatus, XMLHttpRequest) {
                //get Response from Created Record
                entityIdWithLink = XMLHttpRequest.getResponseHeader("OData-EntityId");

                //get EntityId from ResponseHeader of Created Record  
                getEntityId = entityIdWithLink.split(/[()]/);
                getEntityId = getEntityId[1];

                //Display Enttity ID of Created Record
                Xrm.Utility.alertDialog("Entity ID : " + getEntityId);
            },
            //Error Callback Function
            error: function () {
                Xrm.Utility.alertDialog("Something Wrong in Script POST...:(");
            }
        });
    } catch (e) {
        Xrm.Utility.alertDialog(e.message + "\n" + e.description);
    }
}

Sample code to create an Activity & set Activity Party

///------------ Create Phone Call Activity ----------

function createPhoneCall() {
    try {
        //declare variables
        var phonecallId = null;
        var stringJSONPhone = null;
        var urlPhone = null;

        //create activity party collection
        var parties = [];

        //create JSON object 
        var JSONPhone = {};

        //set fields using JSON object
        //Single line of text
        JSONPhone["subject"] = "Test Phone Call"; //Subject

        //Single line of text & format of phone 
        JSONPhone["phonenumber"] = "9876543210"; //Phone Number

        //Multiple Line of Text
        JSONPhone["description"] = "Phone Call Activity for Testing Purpose only...!"; //Description

        //Date and Time
        JSONPhone["scheduledend"] = new Date(); //Due

        //Lookup
        JSONPhone["regardingobjectid_account@odata.bind"] = "/accounts(B386D403-F7AD-E511-80DC-A45D36FC4F90)"; //Regarding is an account

        //ActivityParty (From)
        var sender = {};
        sender["partyid_systemuser@odata.bind"] = "/systemusers(D949B11D-9240-4037-8379-F31C7A36680E)";
        sender["participationtypemask"] = 1; //From

        //ActivityParty (To)
        var receiver1 = {};
        receiver1["partyid_account@odata.bind"] = "/accounts(B386D403-F7AD-E511-80DC-A45D36FC4F90)";
        receiver1["participationtypemask"] = 2; //To
        //receiver["addressused"] = "roohi@dyn20161.onmicrosoft.com";

        var receiver2 = {};
        receiver2["partyid_contact@odata.bind"] = "/contacts(DFE54660-37CD-E511-80DE-6C3BE5A831DC)";
        receiver2["participationtypemask"] = 2; //To

        var receiver3 = {};
        receiver3["partyid_lead@odata.bind"] = "/leads(ED81F0D9-37CD-E511-80DE-6C3BE5A831DC)";
        receiver3["participationtypemask"] = 2; //To

        //add this to collection
        parties.push(sender);
        parties.push(receiver1);
        parties.push(receiver2);
        parties.push(receiver3);

        //pass parties[] to phonecall_activity_parties
        JSONPhone["phonecall_activity_parties"] = parties;

        //Whole Number
        JSONPhone["actualdurationminutes"] = 25; //Duration

        //Two Options
        JSONPhone["directioncode"] = true;//Direction : 0-->False/Incomming, 1-->True/Outgoing

        //convert JSON object to string
        stringJSONPhone = JSON.stringify(JSONPhone);

        //url for ajax request to create phonecall activity
        urlPhone = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/phonecalls";

        //ajax request to create phonecall activity
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: urlPhone,
            data: stringJSONPhone,
            beforeSend: function (CreatePhoneCallActivityRequest) {
                CreatePhoneCallActivityRequest.setRequestHeader("Accept", "application/json");
                CreatePhoneCallActivityRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                CreatePhoneCallActivityRequest.setRequestHeader("Prefer", "odata.include-annotations=*");
                CreatePhoneCallActivityRequest.setRequestHeader("OData-MaxVersion", "4.0");
                CreatePhoneCallActivityRequest.setRequestHeader("OData-Version", "4.0");
            },
            //Success Callback Function
            success: function (data, taxtStatus, getPhoneCallActivityResponse) {
                //get Response from Created Record
                phonecallId = getPhoneCallActivityResponse.getResponseHeader("OData-EntityId");

                //get EntityId from ResponseHeader of Created Record 
                phonecallId = phonecallId.split(/[()]/);
                phonecallId = phonecallId[1];

                //Display Enttity ID of Created Record
                Xrm.Utility.alertDialog("Entity ID : " + phonecallId);

            },
            //Error Callback Function
            error: function (CreatePhoneCallActivityRequest, textStatus, errorThrown) {
                Xrm.Utility.alertDialog("Something Wrong in Script...:(");
            }
        });
    } catch (e) {
        Xrm.Utility.alertDialog(e.message + "\n" + e.description);
    }
}

Conclusion:

Lookup, Regarding and Activity parties being special complex field need to be set by providing a reference to the entity type that you intend to set. The field name also includes a reference to the entity as can be seen in the sample code above. This differs from the way it used to be done earlier where entity type used to be provided as a property of the Lookup object instead of in the field name itself.

Accounting inside your Dynamics CRM..try today. Dynamics CRM and QuickBooks Integration.


Viewing all articles
Browse latest Browse all 3363

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>