Showing posts with label retrieve optionset text using javascript. Show all posts
Showing posts with label retrieve optionset text using javascript. Show all posts

Monday, July 11, 2011

Retrieving optionset Lable data using Metadata service in CRM 2011

Hi All, Using OData service we are not able to get the option set selected text of an entity. Its providing only value field, but not the text. so I have used Metadata service to retrieve Option set text for the selected value.
 Here I am retrieving State option set text from country entity and assigning that option text to text field.

function RetrieveOptionsetLabel()
{
     // Entity schema name 
     var entityLogicalName = "new_country";
     // option set schema name
     var RetrieveAttributeName = "new_state";
     // Target Field schema name to which optionset text needs to be assigned
     var AssignAttributeName = "new_state";

// Option set value for which label needs to be retrieved
        var stateValue = optionValue;
     
        // Calling Metadata service to get Optionset Label
        SDK.MetaData.RetrieveEntityAsync(SDK.MetaData.EntityFilters.Attributes, entityLogicalName, null, false, function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata, RetrieveAttributeName, stateValue, AssignAttributeName); }, errorDisplay);

}

// Called upon successful metadata retrieval of the entity
function successRetrieveEntity(logicalName, entityMetadata, RetrieveAttributeName, OptionValue, AssignAttributeName) {
    ///<summary>
    /// Retrieves attributes for the entity 
    ///</summary>

    var success = false;
    for (var i = 0; i < entityMetadata.Attributes.length; i++) {
        var AttributeMetadata = entityMetadata.Attributes[i];
        if (success) break;
        if (AttributeMetadata.SchemaName.toLowerCase() == RetrieveAttributeName.toLowerCase()) {
            for (var o = 0; o < AttributeMetadata.OptionSet.Options.length; o++) {
                var option = AttributeMetadata.OptionSet.Options[o];
                if (option.OptionMetadata.Value == OptionValue) {
                    Xrm.Page.getAttribute(AssignAttributeName).setValue(option.OptionMetadata.Label.UserLocalizedLabel.Label);
                    success = true;
                    break;
                }
            }
        }

    }


}


 function errorDisplay(XmlHttpRequest, textStatus, errorThrown) {

     alert(errorThrown);
 }

Note: Dont forget to add "sdk.metadata.js" resource to form before calling these methods. you can find this library in sdk "sdk\samplecode\js\soapforjscript\soapforjscript\scripts".