How to update related entity records in Dynamics CRM using javascript

In this blog, I am going to show how we can update a related entity record through JScript in DYnamics CRM either REST or OData way.

First of all I'll show update data using REST Query in Method 1 and then using OData query in method 2.

function btnUpdateOnClick() {
    try {
        var selectedRows = Xrm.Page.getControl("SubGridName").getGrid().getSelectedRows();

        selectedRows.forEach(function (selectedRow, i) {
            var s = selectedRow.getData().getEntity().getEntityReference();
            var selectedRowGuid = s.id;
            var selectedRowName = s.name;
            var selectedRowEntityName = s.entityType;

            UpdateAccount(selectedRowGuid, selectedRowName, selectedRowEntityName);
        });


    }
    catch (e) {
        ShowCatchMessage("new_accountservice_ribbonscript.js", "btnUpdateInventoryOnClick", "A1", e.message);
    }
}

Method 1:

function UpdateAccount(selectedRowGuid, selectedRowName, selectedRowEntityName) {
    var accountId = Xrm.Page.data.entity.getId();
    var objAccount = new Object();

    // Get the name of Account
    var RecordName = Xrm.Page.data.entity.attributes.get("new_name").getValue();

    // set the Account Servcice lookup field.
    objAccount.new_accountserviceid = { Id: accountId, LogicalName: selectedRowEntityName, Name: RecordName };

    // set the Status optionset field as "Not Available"
    objAccount.new_statuscode = { Value: 2 };

    /*USING REST*/
    XrmServiceToolkit.Rest.Update(selectedRowGuid, objAccount, "new_entityNameSet",
     function () {
         alert("Record Updated: " + RecordName);
     },
      function (error) {
          alert("Failed to Update Record");
      },
      false);

    RefreshSubGrid("SubGridName");
}

function RefreshSubGrid(subGridName) {
    gridControl = Xrm.Page.ui.controls.get(subGridName);
    gridControl.refresh()
}


Method 2:

function UpdateAccount(selectedRowGuid, selectedRowName, selectedRowEntityName) {
    var accountId = Xrm.Page.data.entity.getId();
    var objAccount = new Object();

    // set the name of Account
    var RecordName = GetTextFieldValue("new_name");

    // set the Account Servcice lookup field.
    objAccount.new_accountserviceid = { Id: accountId, LogicalName: selectedRowEntityName, Name: RecordName };

    // set the Status optionset field as "Not Available"
    objAccount.new_statuscode = { Value: 2 };

     /*USING ODATA*/
    // Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(objAccount);

    var serverUrl = Xrm.Page.context.getClientUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var odataSetName = "new_entityNameSet";
    var ODataPath = serverUrl + ODATA_ENDPOINT;

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + selectedRowGuid + "')",
        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);
            }
        }
    });
}

Comments

Popular posts from this blog

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

How to import CSV files into DataTable in C#

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

go to top image