Retrieve Entity Primary Key Schema Name using JavaScript in MSCRM using Web API


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();
};


Example:
On a form we have two fields called 1. Entity Schema Name 2. Primary Key. Entity Schema Name, in which we are passing Entity Schema Name and in Primary Key field we are getting that Entity's Primary Key schema name. 

Example

No comments:

Post a Comment