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

Get optionset text from OData query in CRM web api


https://example.com/crm/api/data/v8.2/accounts?$select=custom_optionset

The above query selects all values in an optionset field in CRM. The return data looks something like this:

{
    {
        "@odata.etag":"W/\"112607639\"","custom_optionset":285960000,"accountid":"a08f0bd1-e2c4-e111-8c9a-00155d0aa573"
    },
    {
        "@odata.etag":"W/\"112615384\"","custom_optionset":285960010,"accountid":"a18f0bd1-e2c4-e111-8c9a-00155d0aa573"
    }
}

I don't want the value of the optionset. I want the associated text label. How do I get this?


Solution

  • To get optionset text using webapi, use below snippet in request header.

    req.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
    

    This will return the picklist text similar to lookup FormattedValue.

    enter image description here

    Entire code example:

    function retrieveEntity(entityName, Id, columnSet) {
        var serverURL = Xrm.Page.context.getClientUrl();
        var Query = entityName + "(" + Id + ")" + columnSet;
        var req = new XMLHttpRequest();
        req.open("GET", serverURL + "/api/data/v8.2/" + Query, 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=OData.Community.Display.V1.FormattedValue");
        req.onreadystatechange = function() {
            if (this.readyState == 4 /* complete */ ) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    var data = JSON.parse(this.response);
                    if (data != null {
                            alert(data["_primarycontactid_value@OData.Community.Display.V1.FormattedValue"]); //for lookup text
                            alert(data["[email protected]"]); //for optionset text
                        }
                    } else {
                        var error = JSON.parse(this.response).error;
                        alert(error.message);
                    }
                }
            };
            req.send();
        }
    

    Reference.