Dynamics 365获取选项集字段显示文本的N种方法

我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面的微软最有价值专家(Microsoft MVP),欢迎关注我的微信公众号 MSFTDynamics365erLuoYong ,回复407或者20200505可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!

 如果是通过Web API来查询的话,不加点料,选项集(Optionset)字段返回的是该字段的值(整数),不会返回显示名称。如果要返回显示名称的话,参考我的博文:使用Dynamics 365 CE Web API查询数据加点料及选项集字段常用查询 ,也就是HTTP Request Header加点东西:Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"。

 

 

如果是在Power Automate中从触发器的的返回中取到这个显示文本可以参考我的博文:Power Automate实用常见问题解答(FAQ) 。也就是使用类似  triggerOutputs()?['body/_fieldname_label'] 这种方式来获取。如果是查询数据,则和Web API的方法是一样的。

如果是表单上的选项集字段,获取其值也是获取到值,但是结合 formContext.getAttribute("ly_optionsetfield").getOptions() 获取到该字段所有的选项信息,包括选项值和显示值,这样用代码稍微处理下即可,示例如下,更多信息可以参考 getOptions (Client API reference) 和我的博文:Dynamics 365客户端编程示例:两个选项集字段的联动

var fieldValue = formContext.getAttribute("lvo_market").getValue();
var fieldOptions = formContext.getAttribute("ly_field").getOptions();
var fieldText = "";
        for (var i = 0; i < fieldOptions.length; i++) {
            if (fieldOptions[i].value === fieldValue) {
                fieldText = fieldOptions[i].text;
                break;
            }
        }

 

如果使用的是组织服务的话,查询时候也返回了选项集文本的值和显示值,可以直接获取到。

Get the label of an OptionSetValue 帖子中Goutam Das提供了两种方法,一种是通过 Entity.FormattedValues Property 的方法,示例代码:

string optionSetText= entity.FormattedValues["FieldName"];

 

另外一种是通过查询元数据获取的方法,示例代码如下:

        private string GetOptionsSetTextForValue(IOrganizationService service, string entityName, string attributeName, int selectedValue)
        {

            RetrieveAttributeRequest retrieveAttributeRequest = new
            RetrieveAttributeRequest
            {
                EntityLogicalName = entityName,
                LogicalName = attributeName,
                RetrieveAsIfPublished = true
            };
            // Execute the request.
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            // Access the retrieved attribute.
            Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)
            retrieveAttributeResponse.AttributeMetadata;// Get the current options list for the retrieved attribute.
            OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
            string selectedOptionLabel = null;
            foreach (OptionMetadata oMD in optionList)
            {
                if (oMD.Value == selectedValue)
                {
                    selectedOptionLabel = oMD.Label.LocalizedLabels[0].Label.ToString();
                    break;
                }
            }
            return selectedOptionLabel;
        }

 

posted @ 2020-05-05 08:56  微软MVP(15-18)罗勇  阅读(935)  评论(0编辑  收藏  举报