Dynamics CRM - Accessing Custom Product Option Value

前端 未结 2 967
一个人的身影
一个人的身影 2020-12-12 01:38

Is there a way to programmatically access the Label & Value fields that has been created as a custom Field in MS CRM Dynamics please?

I have added a custom field

2条回答
  •  天涯浪人
    2020-12-12 01:54

    Yes, that data is all stored in the metadata for an attribute (SDK article). You have to retrieve the entity metadata for the entity and then find the attribute in the list. Then cast that attribute to a PicklistAttributeMetadata object and it will contain a list of options. I would mention that typically retrieving Metadata from CRM is an expensive operation, so think about caching.

    private static OptionSetMetadata RetrieveOptionSet(IOrganizationService orgService,
        string entityName, string attributeName)
    {
        var entityResponse = (RetrieveEntityResponse)orgService.Execute(
            new RetrieveEntityRequest 
                { LogicalName = entityName, EntityFilters = EntityFilters.Attributes });
    
        var entityMetadata = entityResponse.EntityMetadata;
    
        for (int i = 0; i < entityMetadata.Attributes.Length; i++)
        {
            if (attributeName.Equals(entityMetadata.Attributes[i].LogicalName))
            {
                if (entityMetadata.Attributes[i].AttributeType.Value == 
                        AttributeTypeCode.Picklist)
                {
                    var attributeMD = (PicklistAttributeMetadata)
                        entityMetadata.Attributes[i];
    
                    return attributeMD.OptionSet;
                }
            }
        }
    
        return null;
    }
    

    Here is how to write the options to the console using the above call.

    var optionSetMD = RetrieveOptionSet(orgService, "account", "accountcategorycode");
    var options = optionSetMD.Options;
    
    for (int i = 0; i < options.Count; i++)
    {
        Console.WriteLine("Local Label: {0}.  Value: {1}",
            options[i].Label.UserLocalizedLabel.Label,
            options[i].Value.HasValue ? options[i].Value.Value.ToString() : "null");
    }
    

    I believe this works for global option set attributes as well, but if you know it is a global option set there is a different message for it that would probably a bit more efficient (SDK article).

提交回复
热议问题