zoukankan      html  css  js  c++  java
  • Dynamics CRM

    1.獲取 OptionSet 的值

          在 Dynamics CRM 中,我們通常通過以下方式來獲取 OptionSet 字段的值,無論在 C# 還是 JS 中,我們獲取的結果都是一個 Int 值(對應每個 Option Item 的 Value)。

    //C# get OptionSet Value
    if (entity.new_field != null)
    {
        int oValue = entity.new_field.Value;
    }
    
    //JS get OptionSet Value
    var oValue = Xrm.Page.getAttribute("new_field").getValue();

    2.C# Plugin 獲取 OptionSet 的 Label(不適用於Two Option字段)

     1 public string GetOptionSetLabel<T>(this IOrganizationService service, string fieldName, int Value, int? lang = 1033) where T : class
     2 {
     3     try
     4     {
     5         var type = typeof(T);
     6         var attReq = new RetrieveAttributeRequest();
     7         attReq.EntityLogicalName = type.Name.ToLower();
     8         attReq.LogicalName = fieldName.ToLower();
     9         attReq.RetrieveAsIfPublished = true;
    10         var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
    11         var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;
    12 
    13         var x = attMetadata.OptionSet.Options.FirstOrDefault(o => o.Value.Value == Value).Label.LocalizedLabels.Where(I => I.LanguageCode == lang).FirstOrDefault().Label;
    14         return x;
    15     }
    16     catch (Exception ex)
    17     {
    18         return null;
    19     }
    20 }

          説明:這裏采用了汎型,所以對於所有 Entity 表的 OptionSet 字段都通用,具體用法如下:

    1 //假设在 Entity Account 中存在一个 OptionSet 字段 <Month>
    2 if (entity.new_month != null)
    3 {
    4     string sMonth = GetOptionSetLabel<Account>(service, "new_month", entity.new_month.Value);
    5 }

    3.C# Plugin 獲取Two Option字段的 Label(同時適用於Option Set字段)

     1 public string GetTwoOptionLabel(IOrganizationService service, string entityName, string fieldName, bool inputValue)
     2 {
     3     string _value = null;
     4     Entity entity = new Entity(entityName);
     5     RetrieveEntityRequest EntityRequest = new RetrieveEntityRequest();
     6     EntityRequest.LogicalName = entity.LogicalName;
     7     EntityRequest.EntityFilters = EntityFilters.All;
     8     RetrieveEntityResponse responseent = (RetrieveEntityResponse)service.Execute(EntityRequest);
     9     EntityMetadata ent = (EntityMetadata)responseent.EntityMetadata;
    10     string objetTypeCode = ent.ObjectTypeCode.ToString();
    11     string fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"
    12                            + "<entity name='stringmap'>"
    13                            + "<attribute name='value'/>"
    14                            + "<attribute name='attributevalue'/>"
    15                            + "<filter type='and'>"
    16                            + $"<condition attribute='objecttypecode' operator='eq' value='{objetTypeCode}'/>"
    17                            + $"<condition attribute='attributename' operator='eq' value='{fieldName}'/>"
    18                            + "</filter>"
    19                            + "</entity>"
    20                            + "</fetch>";
    21     EntityCollection entities = service.RetrieveMultiple(new FetchExpression(fetchXML));
    22     if (entities.Entities.Count > 0)
    23     {
    24         foreach (var entity in entities.Entities)
    25         {
    26             string value = Convert.ToBoolean(Convert.ToInt32(entity.Attributes["attributevalue"].ToString())).ToString();
    27             if (value == inputValue.ToString())
    28             {
    29                 _value = entity.Attributes["value"].ToString();
    30             }
    31         }
    32     }
    33     return _value;
    34 }

          説明:這裏使用了 Fetch Xml 去查詢 StringMap 表(使用其他寫法也可以,比如Query Expression),其中,<attributename> 存的是字段名,<objecttypecode>存的是該字段所在 Entity 的 Object Type Code (是一個唯一值),將這兩個字段作爲查詢條件,可以得到 <attributevalue> - OptionSet/TwoOption 字段的 value 以及 <value> - OptionSet/TwoOption 字段的 Label。

          另外,只要改變下 foreach 循環的代碼就能實現:

          1.根據 Value 獲取 OptionSet Label;

          2.根據 Label 獲取 OptionSet 的 Value(可以用來做checking)。

    4.JS 中獲取 OptionSet/TwoOption 字段的 Label(兩種字段類型都適用)

     1 var req = new XMLHttpRequest();
     2 req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/stringmaps?$select=attributevalue,value&$filter=attributename eq 'sFieldName' and  objecttypecode eq 'sEntityName'", true);
     3 req.setRequestHeader("OData-MaxVersion", "4.0");
     4 req.setRequestHeader("OData-Version", "4.0");
     5 req.setRequestHeader("Accept", "application/json");
     6 req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
     7 req.setRequestHeader("Prefer", "odata.include-annotations="*"");
     8 req.onreadystatechange = function() {
     9     if (this.readyState === 4) {
    10         req.onreadystatechange = null;
    11         if (this.status === 200) {
    12             var results = JSON.parse(this.response);
    13             for (var i = 0; i < results.value.length; i++) {
    14 var attributevalue = results.value[i]["attributevalue"];
    15 var value = results.value[i]["value"]; //Get OptionSet/TwoOption Label 16 } 17 } else { 18 Xrm.Utility.alertDialog(this.statusText); 19 } 20 } 21 }; 22 req.send();

          説明:同理需要字段名和 Entity 表名,之後在 for 循環裏對比 <attributevalue> 與字段的實際值(Xrm.Page.getAttribute("sFieldName").getValue()),最後得到該字段的 Label。

    5.後記(吐槽一下)

          每次辛辛苦苦寫出來的博客,不到一個鐘就被爬蟲和別人轉走了,一個字不差的那種,最後加上一句 “轉載/原文地址:xxxxx”,拜托各位高擡貴手吧,你貼個鏈接參考可以,内容好歹自己寫吧,我的博文又不一定是完全正確的,有的文章寫完一段時間後我又更新了一些錯誤,更搞笑的是用某搜索引擎搜自己博客文章(標題),排在前面的居然還不是自己 = =,我也只能説不愧是你了。説了這麽多,最後還是給點實用的建議吧,如果在 CRM 開發上碰到一些難題,可以用必應國際版去找找,畢竟微軟自家產品,另外,以後的博客大概都是繁體字來寫了,個人習慣,原本的目的就是記自己用到的東西,爬蟲什麽的,給爺爬(小聲bb)。

  • 相关阅读:
    预备作业03
    预备作业02
    寒假作业01
    1179 最大的最大公约数(水题)
    HttpWebRequest
    python模拟银行家算法
    Lock锁与Condition监视器(生产者与消费者)。
    synchronized(){}同步代码块笔记(新手笔记,欢迎纠正)
    详解~实现Runnable方法创建线程之为什么要将Runnable接口的子类对象传递给Thread的构造函数
    语义web基础知识学习
  • 原文地址:https://www.cnblogs.com/Sunny20181123/p/12007226.html
Copyright © 2011-2022 走看看