Basic Create, Update, Fetch and Delete operations using Odata in Dynamics CRM

1. Create:
New records, or entries, are created by executing an HTTP POST request against the URI of the collection where the entry is to be created. The POST request includes the new entry in its body using either ATOM or JSON formats.

The server assigns default values to any properties not specified in the request and returns the result with a ‘Location’ header that contains the URL for the record that was created. The entry title element reflects the primary attribute of the entity. For example, for the account entity the name attribute is the primary attribute. HTTP status code 201 indicates that the record was successfully created.

// Function to create an account

function createAcc()
{
    var accInfo = new Object();
    accInfo.Name = "ABC";
    var jsonAccount = JSON.stringify(accInfo);
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
  url:           Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/      AccountSet",
        data: jsonAccount,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) { },
        error: function (XMLHttpRequest, textStatus, errorThrown) { }
    });

}


2. Update:

Two ways are possible to update a record in CRM.

2.1 Using Put:
Updating records using PUT replaces the existing record with the data provided. All property values in the record either take the values provided in the request or are set to their default values if they are not included in the request. Links are not replaced. It is used to update individual properties.

function updateRecord(id, entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
//Asynchronous AJAX function to Update a CRM record using OData
$.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
data: jsonEntity,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “(guid'” + id + “‘)/Name”,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
//Specify the HTTP method MERGE to update just the changes you are submitting.
XMLHttpRequest.setRequestHeader(“X-HTTP-Method”, “PUT”);
},
success: function (data, textStatus, XmlHttpRequest) {
alert(“Updated successfully”);
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (XmlHttpRequest && XmlHttpRequest.responseText) {
alert(“Error while updating ” + odataSetName+ ” ; Error – ” + XmlHttpRequest.responseText);
}
}
});
}

// Entity Object
var account = new Object();
account.Name = “Updated”;

2.2 Using Merge:
It is used to update all the properties of records

function updateRecord(id, entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
//Asynchronous AJAX function to Update a CRM record using OData

$.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
data: jsonEntity,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “(guid'” + id + “‘)”,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
//Specify the HTTP method MERGE to update just the changes you are submitting.
XMLHttpRequest.setRequestHeader(“X-HTTP-Method”, “MERGE”);
},
success: function (data, textStatus, XmlHttpRequest) {
alert(“Updated successfully”);
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (XmlHttpRequest && XmlHttpRequest.responseText) {
alert(“Error while updating ” + odataSetName+ ” ; Error – ” + XmlHttpRequest.responseText);
}
}
});
}

// Enity Object

var account = new Object();
account.Name = “Updated”;
account.Telephone1 = “1234567890”;
account.AccountNumber = “Updated-123”;
account.EmailAddress1 = abc@gmail.com;


3. Fetch:
HTTP GET is used when you are retrieving records. When a unique identifier for a specific record is provided, only that record will be retrieved. Otherwise, any system query options that are defined will be applied and up to 50 records will be retrieved that match any system query option filters.

// Example to fetch Account Id where name is ABC

function getAccId() {
    var id = [];
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        async: false,
 url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/AccountSet?$select=AccountId &$filter=Name eq 'ABC'",

        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");

        },
        success: function (data, textStatus, XmlHttpRequest) {
            for (var i = 0; i < data.d.results.length; i++) {
                id.push(data.d.results[i].AccountId);
                alert("Id is " + id[i]);
            }
           },
        error: function (XMLHttpRequest, textStatus, errorThrown) { }
    });
}
  

4. Delete:
Use a POST request with the X-HTTP-METHOD header set to DELETE with a URI reference to the record to be deleted.

function deleteAccount() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
url:
Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationDatasvc/AccountSet(guid'" + id + "')",
            async: false,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
                XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
            },
            success: function (data, textStatus, XmlHttpRequest) {
alert("Deletion Successfull"); },
error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Deletion Failed"); }
        });       
}

Comments

Popular posts from this blog

Creating a Grid dynamically using HTML in Dynamics CRM to show, update and delete associated records in an entity