Tuesday, August 23, 2016

CRM 2016 Web API Retrieve Attribute Names By Entity Name

GetEntityMetaData function will retrieve the list of attributes from he Account entity.

 function GetEntityMetaData() {  
   var entityType = "Account";  
   var metaDataId = getMetaDataIdByName(entityType);  
   var schemaNames = getAttributeList(metaDataId);  
 }  
 function getAttributeList(metaDataId) {  
   var attributesList;  
   $.ajax({  
     type: "GET",  
     contentType: "application/json; charset=utf-8",  
     datatype: "json",  
     url: Xrm.Page.context.getClientUrl() + "/api/data/v8.1/EntityDefinitions(" + metaDataId + ")?$select=LogicalName&$expand=Attributes($select=LogicalName)",  
     beforeSend: function (XMLHttpRequest) {  
       XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");  
       XMLHttpRequest.setRequestHeader("OData-Version", "4.0");  
       XMLHttpRequest.setRequestHeader("Accept", "application/json");  
       XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");  
     },  
     async: false,  
     success: function (data, textStatus, xhr) {  
       attributesList = data.Attributes;  
     },  
     error: function (xhr, textStatus, errorThrown) {  
       alert(textStatus + " " + errorThrown);  
     }  
   });  
   return attributesList;  
 }  
 function getMetaDataIdByName(entityType) {  
   var MetadataId;  
   $.ajax({  
     type: "GET",  
     contentType: "application/json; charset=utf-8",  
     datatype: "json",  
     url: Xrm.Page.context.getClientUrl() + "/api/data/v8.1/EntityDefinitions?$select=DisplayName,IsKnowledgeManagementEnabled,EntitySetName&$filter=SchemaName eq '" + entityType + "'",  
     beforeSend: function (XMLHttpRequest) {  
       XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");  
       XMLHttpRequest.setRequestHeader("OData-Version", "4.0");  
       XMLHttpRequest.setRequestHeader("Accept", "application/json");  
       XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");  
     },  
     async: false,  
     success: function (data, textStatus, xhr) {  
       var result = data.value[0];  
       MetadataId = result.MetadataId;  
     },  
     error: function (xhr, textStatus, errorThrown) {  
       alert(textStatus + " " + errorThrown);  
     }  
   });  
   return MetadataId;  
 }  

No comments:

Post a Comment