DYNAMICS 365 HOW TO RETRIEVE AND EXECUTE PREDEFINED QUERIES
As you know, System views are available to all users, while, the Personal views are available to only the users who created them
and the users these views are shared with. Both of these are called Predefined queries and can be retrieved and executed using WebAPI.
- System views are the system defined views and are contained in the entity named SavedQuery
- Personal views are the personal views and are contained in the entity named UserQuery
You can use the following WebAPI calls to execute the predefined queries:
- System views: https://<OrgUrl>/api/data/v9.0/account?savedQuery=<SystemViewId>
- Personal views: https://<OrgUrl>/api/data/v9.0/account?userQuery=<PersonalViewId>
To get the Query Id, you can use the Xrm.WebAPI and get it based on the name of the view (same way can de done for both savedQuery and userQuery):
function getViewIdByName(context, viewName) {
Xrm.WebApi.retrieveMultipleRecords("savedquery", "?$select=name,savedqueryid&$filter=name eq '" + viewName + "'&$top=1").then(
function success(results) {
for (var i = 0; i < results.entities.length; i++) { //length=1 because of top=1 in query
var name = results.entities[i]["name"];
var savedqueryid = results.entities[i]["savedqueryid"];
}
},
function (error) { }
);
}
Once you get the savedqueryid value, you can do the call that will execute the view and get the records returned by the query
function getPredefinedQuery(context, entityName, queryType, viewId) {
var formContext = context.getFormContext();
var urlRequest = formContext.context.getClientUrl() + "/api/data/v9.0/" + entityName + "?" + queryType + "=" + viewId;
var req = new XMLHttpRequest();
req.open("GET", urlRequest, true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var data = JSON.parse(req.response);
var recordsFromView = data.value;
}
}
};
req.send();
}
- entityName = entity plural name of the entity
- queryType = savedQuery or userQuery
- viewId = guid of the view you want to execute
Hope This Helps!
Comments
Post a Comment