Getting Local Option Set Metadata with WebAPI and JavaScript

Leave a comment

In this post, we will use the WebAPI with JavaScript to get the metadata for a local option set.

Let’s say we have a local option set called Customer Priority, with 3 options:

  • A
  • B
  • C

The option set is part of the Contact entity. We can see the local option set on the form below:

And its name is new_contactpriority:

Using the WebAPI, we can get these values through JavaScript. We can access the Option Set metadata by using EntityDefinitions, and selecting our attribute by filtering on the logical name.  We will also expand the OptionSet:

https://yourcrm.crm.dynamics.com/api/data/v8.2/EntityDefinitions(LogicalName=’contact’)/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$filter=LogicalName eq ‘new_contactpriority’&$expand=OptionSet

We can see the labels of the option set:

We can access this through JavaScript with the following code:

 

            var req = new XMLHttpRequest();
            req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/EntityDefinitions(LogicalName='contact')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$filter=LogicalName eq 'new_contactpriority'&$expand=OptionSet", true);
            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 () {
                if (this.readyState === 4) {
                    req.onreadystatechange = null;
                    if (this.status === 200) {
                        var results = JSON.parse(this.response);
                        for (var i = 0; i < results.value[0].OptionSet.Options.length; i++) {
                            var Label = results.value[0].OptionSet.Options[i].Label.UserLocalizedLabel.Label;
                            alert(Label);
                        }
                    } else {
                        Xrm.Utility.alertDialog(this.statusText);
                    }
                }
            };
            req.send();

This produces below (and B and C):

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, BI, Web, Cloud and Data Science.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *