Wednesday, 20 May 2015

Create record using OData and JQuery in CRM 2011/2013/2015

Hi,

Here is the code for creating a record using OData and Jquery in CRM 2011/2013/2015.

Let us take the example of creating Account record.

  • Create a JS and add it in Account entity.
  • Copy and Paste the below code. I have covered the basic attributes which you can change according to your requirement.

function createAccount() {
    //Create an object to represent an Account record and set properties
    var account = new Object();
    // Set Single Line of Text field
    account.Name = "Testing Odata";
    // Set Lookup field (Contact should exists in the system)
    var primaryContact = new Object();
    primaryContact.ContactId = "B5A0F1C2-7CF5-E411-80D5-C4346BAC59E8";
    primaryContact.FullName = "Rene Valdes (sample)";
    if (primaryContact != null) {
        account.PrimaryContactId = { Id: primaryContact.ContactId, LogicalName: "contact", Name: primaryContact.FullName };
    }
    //Set a picklist value
    account.PreferredContactMethodCode = { Value: 2 };
    // Set a money value (i.e., Annual Revenue)
    account.Revenue = { Value: "2000000.00" };
    // Set a Decimal field (Here ‘new_DecimalField’ is my custom Account field)
    account.new_DecimalField = 200.00.toString();
    // Set a Boolean value
    account.DoNotPhone = true;
    // Set Date field (Here ‘new_DateField’ is my custom Account field)
    //var myDate = new Date();
    //myDate.setFullYear(1980, 12, 29);
    //account.new_Date = myDate;
    // Call create method by passing
    //(i) Entity Object (i.e.,account in this case)
    //(ii) Entity Set
    //(iii)SuccessCallback function
    //(iv) Error callback function
    createRecord(account, "AccountSet", createAccountCompleted, null);
}

// callback method which will get executed on successfull account creation
function createAccountCompleted(data, textStatus, XmlHttpRequest) {
    var account = data;
    alert("Account created; Id: " + account.AccountId.toString());
}
 
// This function creates record by making OData call
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(entityObject);
    // Get Server URL
    var url = "";
    if (Xrm.Page.context.getClientUrl) {
        //Post UR 12
        url = Xrm.Page.context.getClientUrl();
    }
    else {
        //Pre UR 12
        url = Xrm.Page.context.getServerUrl();
    }
    //The OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: url + ODATA_ENDPOINT + "/" + odataSetName,
        data: jsonEntity,
        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) {
            if (successCallback) {
                successCallback(data.d, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback) {
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            }
            else {
                alert("An error has occured while creating the record; Error – " + errorThrown);
            }
        }
    });
}
  • Call createAccount function on the Load of Account.
  • Create JQuery and JSON files as web resources and them on Account Form.
  • Save and Publish.

Hope this helps

--
Happy CRM'ing
Gopinath.

1 comment:

  1. Hii, could you tell if i want to call this function from a custom button ?

    ReplyDelete