Here is a JavaScript method, with which we can fetch any entity's Primary Key Attribute using Web API. Parameters Used: Entity Schema Name
Below, we are fetching only Primary Id Attribute from metadata of an entity. Check the filter condition in the query for the same.
function getPrimaryKey() {
var Oldprimary = Xrm.Page.data.entity.attributes.get("new_primarykey").getValue();
var req = new XMLHttpRequest();
var entityName = Xrm.Page.data.entity.attributes.get("new_entityschemaname").getValue();
var url = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + "EntityDefinitions?$select=PrimaryIdAttribute&$filter=SchemaName eq '" + entityName + "'";
req.open("GET", url, false);
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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
Xrm.Page.data.entity.attributes.get("new_primarykey").setValue("");
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
var results = JSON.parse(this.response);
var primarykey = results.value[0].PrimaryIdAttribute;
Xrm.Page.data.entity.attributes.get("new_primarykey").setValue(primarykey);
}
else {
Xrm.Utility.alertDialog("Error");
}
}
}
req.send();
};
No comments:
Post a Comment