Retrieve Option Set Label from Entity with JavaScript in CRM

Hello everyone,

In this article I am going to share a javascript code snippet to let you retrieve option set label (text) or value of any Optionset field from any entity in Microsoft Dynamics CRM.

First of all you need to refer a js resource file named Sdk.Metadata.js in your form.

You can find this resource at sdk\samplecode\js\soapforjscript\soapforjscript\scripts 

After adding this resource to your CRM Form you just need to use below function:

// This function Gets optionset values and text via given entityname and optionset attribute
// To use this function Sdk.Metada.js must be added to form.
// This javascript (Sdk.Metada.js) file source can be found at the location : "sdk\samplecode\js\soapforjscript\soapforjscript\scripts"
function GetOptionSetLabel(EntityLogicalName, AttributeLogicalName) {
    SDK.Metadata.RetrieveAttribute(EntityLogicalName, AttributeLogicalName, "00000000-0000-0000-0000-000000000000", true,
        function(result) {

            for (var i = 0; i < result.OptionSet.Options.length; i++) {

                var text = result.OptionSet.Options[i].Label.LocalizedLabels[0].Label;

                var value = result.OptionSet.Options[i].Value;

              	// Here you can use text or value of the OptionSet to do whatever you want
            }
        },
        function(error) {}
    );
} 

Let’s take a look at the parameters we’ve just used;

EntityLogicalName: It can be any entity in your CRM. i.e: Contact, Account or any custom entity.

AttributeLogicalName: This refers to attribute name of the OptionSet that you want to get label or value of.

 

I hope you’ve enjoyed this tutorial 🙂

Leave a Reply

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