Search code examples
odatadynamics-crmdynamics-crm-2016dynamics-crm-webapi

Is there a way to apply a filter when using a savedQuery in Dynamics CRM Web API?


Is there a way to apply a filter when using a savedQuery? For example, if a saved/pre-defined view returns multiple accounts, like with the following URL ".../api/data/v9.0/accounts?savedQuery=9e3ddee9-9e74-e811-a95d-000d3a34afa9", is there a way to return the results of the same saved view for a single account?


Solution

  • You can send a fetch XML to Web API. Simply download the fetch XML of the view through the Advanced Find. Here's an exemple in javascript:

    var accountFetchXML = ['< fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
                '< entity name="account">' +
                '< attribute name="name" />' +
                '< filter type="and">' +
                   '< condition attribute="industrycode" operator="not-null" />' +
                '</ filter>' +
                '< link-entity name="contact" from="contactid" to="primarycontactid" visible="false" link-type="outer" alias="prmContact">' +
                   '< attribute name="telephone3" />' +
                   '< attribute name="description" />' +
                 '</ link-entity>' +
               '</ entity>' +
             '</ fetch>'].join('');
    
    var encodedFetchXML = encodeURIComponent(accountFetchXML);
    
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts?fetchXml=" + encodedFetchXML, true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i++) {
                    var accountDetails = results.value[i];
    
                    //Single Line Text
                    var nameValue = accountDetails['name'];
                }
            }
            else {
                alert(this.statusText);
            }
        }
    };
    req.send();