How to delete record/field value using the Web API in Dynamics CRM

By | April 15, 2016

Introduction:

As we all know, the Web API has been introduced in Microsoft Dynamics CRM 2016. It offers a great development experience across many devices, programming languages and platforms.

In our earlier blog, we have seen how to create and retrieve records using the Web API. Now, let’s take a look of how to delete a Lookup field value in CRM.

Clear Entity Reference [Lookup] Field Value:

We are trying to Clear the lookup field value or set the value of the lookup field as null using the Patch action but it does not work as expected. So there is an alternate way to clear the lookup field value by using the DELETE action.

If we need to clear the lookup field value using DELETE action then we need to pass the Record GUID with the logical name of lookup field along with the ‘$ref’ keyword.

Here’s is the code snippet.

//Function to delete the entity refrence field value 
function DeleteEntityRefField() {

    var functionName = "DeleteEntityRefField";
    try {
        
        //get Server url
        var serverURL = Xrm.Page.context.getClientUrl();

        //create XML request object 
        var xhr= new XMLHttpRequest();

        //below line is used to delete the entity ref field (lookup) from the account record
        xhr.open("DELETE", serverURL + "/api/data/v8.0/accounts(1DD18913-11CB-E511-80D2-C4346BDC11C1)/primarycontactid/$ref", true);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xhr.setRequestHeader("OData-MaxVersion", "4.0");
        xhr.setRequestHeader("OData-Version", "4.0");
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                xhr.onreadystatechange = null;
                if (this.status == 204) {

                    //show alert message 
                    alert('Field Value Deleted');
                }
                else {
                    var error = JSON.parse(this.response).error;

                    //show error message
                    alert(error.message);
                }
            }
        };
        xhr.send();
    } catch (e) {
        alert(functionName + (e.message || e.description));
    }
}

Later, the above code is used to clear/delete the entity reference (lookup) field value. To specify the field is lookup field, we need to use entity reference ‘/$ref’ after the field name.

Delete String/Date/OptionSet/Currency Field Value:

We can also clear the single entity attribute value of type string/Date/Option Set/Currency using the DELETE action. To perform this action we need to pass the field’s logical name and the record GUID in the Web API URL section. Here’s is the code which will help you understand what we are trying to say.

//Function to delete the entity reference field value 
function DeleteFieldValue() {

    var functionName = "DeleteEntityRecord";
    try {
        
        //get Server url
        var serverURL = Xrm.Page.context.getClientUrl();

        //create XML request object 
        var xhr = new XMLHttpRequest();

        //below line ios used to delete the particular field value 
        xhr.open("DELETE", serverURL + "/api/data/v8.0/accounts(1DD18913-11CB-E511-80D2-C4346BDC11C1)/telephone1", true);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xhr.setRequestHeader("OData-MaxVersion", "4.0");
        xhr.setRequestHeader("OData-Version", "4.0");
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                xhr.onreadystatechange = null;
                if (this.status == 204) {

                    //show alert message 
                    alert('Field Value Deleted');
                }
                else {
                    var error = JSON.parse(this.response).error;

                    //show error message
                    alert(error.message);
                }
            }
        };
        xhr.send();
    } catch (e) {
        alert(functionName + (e.message || e.description));
    }
}

From the above code the ‘Phone (telephone1)’ field value from the account record will be cleared.

Deleting an Entity Record:

Let’s consider ‘Accounts’ as the entity for which the record needs to be deleted. You have to pass the record GUID as a parameter in the WEB API URL in order to delete the entity record.

Check out the code as written below.

//Function to delete the entity refrence field value 
function DeleteEntityRecord() {

    var functionName = "DeleteEntityRecord";
    try {
        
        //get Server url
        var serverURL = Xrm.Page.context.getClientUrl();

        //create Xml request object 
        var xhr = new XMLHttpRequest();

        //below line is used to delete the entity record  
        xhr.open("DELETE", serverURL + "/api/data/v8.0/accounts(1DD18913-11CB-E511-80D2-C4346BDC11C1)", true);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xhr.setRequestHeader("OData-MaxVersion", "4.0");
        xhr.setRequestHeader("OData-Version", "4.0");
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                xhr.onreadystatechange = null;
                if (this.status == 204) {

                    //show alert message 
                    alert('Field Value Deleted');
                }
                else {
                    var error = JSON.parse(this.response).error;

                    //show error message
                    alert(error.message);
                }
            }
        };
        xhr.send();
    } catch (e) {
        alert(functionName + (e.message || e.description));
    }
}

Conclusion:

On a concluding note, it is actually simple to delete an entity record using Web API. You should ensure that the right record GUID and the field’s logical name are passed as parameters.

Free 70% of storage space in CRM with Attachment Management Apps!

Attach2Dynamics – Store and manage documents/attachments in cloud storage of your choice – SharePoint, Dropbox or Azure Blob Storage from within Dynamics 365 CRM.
SharePoint Security Sync – Robust and secure solution to integrate Dynamics 365 CRM and SharePoint Security Sync thereby ensuring secure access to confidential documents stored in SharePoint.

2 thoughts on “How to delete record/field value using the Web API in Dynamics CRM

  1. Jeff Dodds

    You can also do this via a request matching the followign format that allows you to use execute or executeMultiple from the WebApi. Under the Hood it does the same thing as what you are doing.

    {
    getMetadata: function () {
    var ODataMetadata = {
    boundParameter: null,
    parameterTypes: {},
    operationName: “Disassociate”,
    operationType: 2
    };
    return ODataMetadata
    },
    target: {
    id: selectedId,
    entityType: “Entity-with-lookup-LOGICALNAME”
    },
    relationship: “LookupSchemaName”
    }

    1. Inogic

      The blog which you are referring to covers all other fields and is not limited for lookup fields only.

      Now, you don’t have to use ‘DELETE’ request explicitly as you can simply use Xrm.WebApi.UpdateRecord for updating all types of fields including lookup fields. So no need to use separate request for that.

      Also, whenever you make disassociate requests to CRM, in the background CRM treats it as a DELETE request.

      Hope this helps.

      Thanks!

Comments are closed.