Dynamics CRM-How to get Label of OptionSet / TwoOption type field

1. Get the value of OptionSet

      In Dynamics CRM, we usually get the value of the OptionSet field in the following ways. Whether in C # or JS, the result we get is an Int value (corresponding to the value of each Option Item).

//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 Get Label of OptionSet (not applicable to Two Option field)

 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 }

      Note: Generics are used here, so the OptionSet field is common to all Entity tables. The specific usage is as follows:

1  // Assume that there is an OptionSet field in Entity Account <Month> 
2  if (entity.new_month! = Null )
 3  {
 4      string sMonth = GetOptionSetLabel <Account> (service, " new_month " , entity.new_month.Value);
 5 }

 

3.C # Plugin Get Label of Two Option field (also applicable to Option Set field)

 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 }

      Note: Fetch Xml is used here to query the StringMap table (other writing methods are also possible, such as Query Expression), where <attributename> stores the field name, and <objecttypecode> stores the Object Type Code of the Entity where the field is located (yes a unique value), the two fields as a query, can be obtained <attributevalue> - value OptionSet / TwoOption field and <value> - Label OptionSet / TwoOption field.

      In addition, as long as the code of the foreach loop is changed:

      1. Acquire OptionSet Label according to Value;

      2. Acquire the value of OptionSet according to Label (can be used for checking).

 

4. Get the Label of the OptionSet / TwoOption field in JS (both field types are applicable)

 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();

      Note: The field name and the Entity table name are required in the same way. Then, compare the <attributevalue> with the actual value of the field ( Xrm.Page.getAttribute ("sFieldName"). GetValue () ) in the for loop, and finally get the Label of the field.

5. Postscript (Tucao a bit)

      Every time a hard-working blog is written, it is transferred away by reptiles and others in less than an hour, a word of the same kind, and finally add a sentence "reprinted / original address: xxxxx" You can post a link for reference, the content is good or bad, and my blog post is not necessarily correct. Some articles have been updated for some time after I wrote them. The more funny thing is to use a search engine to search my blog. The article (title) is actually not in front ==, I can only say that it is you. Having said so much, let ’s finally give some practical suggestions. If you encounter some difficulties in CRM development, you can use the Bing international version to find it. After all, Microsoft ’s own products, in addition, the future blogs are probably traditional characters I wrote it, personal habits, the original purpose was to remember what I used, reptiles or something, to crawl for the master (whispering bb).

Guess you like

Origin www.cnblogs.com/Sunny20181123/p/12007226.html