Development, Howto

How to get Object Type Code of entity using WebApi

If you need to get Object Type Code of entity based on Logical Name of entity you can use following code:

var entityLogicalName = "account";

var requestUrl = "/api/data/v8.2/EntityDefinitions?$filter=LogicalName eq '" + entityLogicalName + "'&$select=ObjectTypeCode";

var context;

if (typeof GetGlobalContext === "function") {
    context = GetGlobalContext();
} else {
    context = Xrm.Page.context;
}
var req = new XMLHttpRequest();
req.open("GET", context.getClientUrl() + requestUrl, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function () {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            var result = JSON.parse(this.response);
            var objectTypeCode = result.value[0].ObjectTypeCode;
            //use retrieved objectTypeCode
        } else {
            var errorText = this.responseText;
            //handle error here
        }
    }
};
req.send();

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.