如何在Power Automate Flow中获取Choice类型属性的Label名称(含多选)
获取Choice类型字段的Label名称(含单选/多选)
单选Choice字段
对于单选Choice字段,你已经知道可以通过字段名加_label后缀的方式获取Label,比如_new_currency_label。这个方式适用于查询记录、Post操作插件或者Web API查询场景,能直接拿到对应的显示名称。
多选Choice字段
多选Choice字段无法直接通过_label后缀获取,需要通过字段元数据来匹配每个选中的值对应的Label,以下是不同场景的实现方式:
1. C#插件场景
在插件中,你可以通过RetrieveAttributeRequest获取字段的元数据,然后遍历选中的OptionSetValueCollection来匹配Label:
// 假设多选字段是new_multiselectchoices string entityName = "account"; string attributeName = "new_multiselectchoices"; // 获取字段元数据 RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); MultiSelectPicklistAttributeMetadata multiSelectMetadata = (MultiSelectPicklistAttributeMetadata)attributeResponse.AttributeMetadata; // 获取当前记录选中的Value集合(以Post操作为例) OptionSetValueCollection selectedValues = (OptionSetValueCollection)context.PostEntityImage["new_multiselectchoices"]; // 匹配对应的Label List<string> selectedLabels = new List<string>(); foreach (var value in selectedValues) { var option = multiSelectMetadata.OptionSet.Options.FirstOrDefault(o => o.Value == value.Value); if (option != null) { selectedLabels.Add(option.Label.UserLocalizedLabel.Label); } } // selectedLabels就是所有选中项的Label集合
2. 客户端Web API场景
在前端脚本中,你可以先获取字段的元数据,再匹配选中的Value:
// 获取多选字段元数据 async function getMultiSelectLabels(entityName, attributeName, selectedValues) { const metadataResponse = await Xrm.WebApi.retrieveMultipleRecords("attributemetadata", `?$filter=LogicalName eq '${attributeName}' and EntityLogicalName eq '${entityName}'&$select=OptionSet`); const optionSet = metadataResponse.entities[0].OptionSet; const labels = []; selectedValues.forEach(value => { const option = optionSet.Options.find(opt => opt.Value === value); if (option) { labels.push(option.Label.UserLocalizedLabel.Label); } }); return labels; } // 使用示例:创建Account后获取选中的多选Label Xrm.WebApi.createRecord("account", { "name": "Test Account", "new_multiselectchoices": [100000001, 100000003] // 选中的Value }).then(response => { return Xrm.WebApi.retrieveRecord("account", response.id, "?$select=new_multiselectchoices"); }).then(account => { return getMultiSelectLabels("account", "new_multiselectchoices", account.new_multiselectchoices); }).then(labels => { console.log("选中的Label:", labels); });
3. Power Automate场景
在Power Automate中,可以通过以下步骤获取多选Choice的Label:
- 添加"获取元数据"动作,选择对应实体和多选字段,获取所有选项
- 使用"应用到每一个"遍历记录中选中的多选Value
- 在循环内,使用"筛选数组"动作,从元数据选项中筛选出Value等于当前项的记录
- 提取筛选结果中的Label,收集到数组中
注意事项
- 如果是在Pre操作插件中,此时记录尚未保存,但可以提前获取元数据,结合
Context.InputParameters中的Value集合来匹配Label - 多语言场景下,注意获取对应语言的
LocalizedLabel,而不是只取UserLocalizedLabel
内容的提问来源于stack exchange,提问作者Aiden Martin
相关产品推荐
相关产品推荐

