Microsoft Dynamics CRM 2011

Microsoft Dynamics CRM 2011

Tuesday, April 16, 2019

Dynamics 365 - How to Update Entity attributes using Web API and Javascript in 5 minutes

In this article we describe Step by step How to Update Entity attributes using Web API and Javascript in 5 minutes.
In this example, we send an HTTP PATCH request to the Dynamics 365 Web Api, in order to update several attributes, and also a MANY-TO-ONE relationship reference between Phonecall and Contact.
We use the HTTP PATCH verb since we are updating more than ONE attribute. Elsewhere, we should use the HTTP PUT OData REST method.


How to Update Entity attributes using Web API and Javascript in 5 minutes  



The following code sends an HTTP PATCH request to the Dynamics 365 Web Api, in order to update several attributes, and also a MANY-TO-ONE relationship reference between Phonecall and Contact:



 var fnPATCHEntity = (newEntityId) => {
            //debugger;
            var entity = {};
            entity.phonenumber = document.getElementById("Phone").value;            
            entity.description = document.getElementById("Description").value;
            entity["regardingobjectid_contact@odata.bind"] = "/contacts(" + newEntityId + ")";
            let id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');


            $.ajax({
                type: "PATCH",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/phonecalls(" + id + ")",
                data: JSON.stringify(entity),
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                    XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                async: true,
                success: function (data, textStatus, xhr) {
                    Xrm.Utility.alertDialog('Phonecall Updated with MANY-TO-ONE relationship!!');
                },
                error: function (xhr, textStatus, errorThrown) {
                    Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
                }
            });

        }




That's all...
In this article we've seen Step by step How to Update Entity attributes using Web API and Javascript in 5 minutes.
Enjoy Microsoft Dynamics 365 CRM!

by Carmel Schvartzman

כתב: כרמל שוורצמן

No comments:

Post a Comment