Dynamics CRM: cómo obtener la etiqueta del campo de tipo OptionSet / TwoOption

1. Obtenga el valor de OptionSet

      En Dynamics CRM, generalmente obtenemos el valor del campo OptionSet de las siguientes maneras: ya sea en C # o JS, el resultado que obtenemos es un valor Int (correspondiente al valor de cada Opción).

// C # get optionset Valor 
si (entity.new_field =! Nula ) 
{ 
    int oValue = entity.new_field.Value; 
} 

// JS obtiene el valor OptionSet 
var oValue = Xrm.Page.getAttribute ( " new_field " ) .getValue ();

 

2.C # Plugin Obtener etiqueta del conjunto de opciones (no aplicable al campo Dos opciones)

1  cadena pública  GetOptionSetLabel <T> ( este servicio IOrganizationService, string fieldName, int Value, int ? Lang = 1033 ) donde T: clase 2 {
 3 intente 4     {
 5 var type = typeof (T);
6 var attReq = new RetrieveAttributeRequest ();
7          attReq.EntityLogicalName = type.Name.ToLower ();
8          attReq.LogicalName = fieldName.ToLower ();
9 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          retorno x;
15      }
 16      catch (Excepción ex)
 17      {
 18          return  null ;
19      }
20 }

      Nota: aquí se utilizan genéricos, por lo que el campo OptionSet es común a todas las tablas de entidades. El uso específico es el siguiente:

1  // Suponga que hay un campo OptionSet en 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 Obtener etiqueta del campo de dos opciones (también aplicable al campo Conjunto de opciones)

1  cadena pública  GetTwoOptionLabel (servicio IOrganizationService, cadena de entidad nombre, cadena de campo nombre , bool inputValue)
 2 {
 3 cadena _value = null ;
4      Entidad entidad = nueva Entidad (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      cadenas objetTypeCode = ent.ObjectTypeCode.ToString ();
11      string fetchXML = " <fetch version = '1.0' output-format = 'xml-platform' mapping = 'logical' distinct = 'false'> " 
12                             + " <entity name = 'stringmap'> " 
13                             + " <atributo nombre = 'valor' /> " 
14                             + "
15                             + " <filter type = 'y'> " 
16                             + $ " <condition attribute = 'objecttypecode' operator = 'eq' value = '{objetTypeCode}' /> " 
17                             + $ " <condition attribute = 'attributename' operator = 'eq' value = '{fieldName}' /> " 
18                             + " </filter> " 
19                             + " </entity> " 
20                             + "</fetch> " ;
 21     EntityCollection entidades = service.RetrieveMultiple ( nuevo FetchExpression (fetchXML));
22      if (entidades.Entities.Count> 0 )
 23      {
 24          foreach ( entidad var en entity.Entities )
 25          {
 26              string value = Convert.ToBoolean (Convert.ToInt32 (entity.Attributes [ " attributevalue " ] .ToString ()) ).Encadenar();
27              if (value == inputValue.ToString ())
 28              {
 29                  _value = entity.Attributes [ "valor " ] .ToString ();
 30              }
 31          }
 32      }
 33      return _value;
 34 }

      Nota: Fetch Xml se usa aquí para consultar la tabla StringMap (también son posibles otros métodos de escritura, como Expresión de consulta), donde <attributename> almacena el nombre del campo y <objecttypecode> almacena el Código de tipo de objeto de la entidad donde se encuentra el campo (sí un valor único), los dos campos como una consulta, se puede obtener <AttributeValue> - valor optionset / campo TwoOption y <valor> - Label campo optionset / TwoOption.

      Además, siempre que se cambie el código del bucle foreach:

      1. Adquiera la etiqueta OptionSet según el valor;

      2. Adquiera el valor de OptionSet de acuerdo con la etiqueta (se puede usar para verificar).

 

4. Obtenga la etiqueta del campo OptionSet / TwoOption en JS (ambos tipos de campo son aplicables)

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' y objecttypecode eq 'sEntityName '", cierto );
3 req.setRequestHeader ("OData-MaxVersion", "4.0" );
4 req.setRequestHeader ("OData-Version", "4.0" );
5 req.setRequestHeader ("Aceptar", "aplicación / json" );
6 req.setRequestHeader ("Content-Type", "application / json; charset = utf-8" );
7 req. setRequestHeader ("Preferir", "odata.include-annotations = \" * \ "" );
8req.onreadystatechange = function () {
 9      if ( this .readyState === 4 ) {
 10          req.onreadystatechange = null ;
11          if ( this .status === 200 ) {
 12              resultados var = JSON.parse ( this .response);
13              para ( var i = 0; i <results.value.length; i ++ ) { 
14 var attributevalue = results.value [i] ["attributevalue"];
15 valor var = resultados.valor [i] ["valor"]; // Obtener OptionSet / TwoOption Label 16 } 17 } más { 18 Xrm.Utility.alertDialog ( this .statusText); 19 } 20 } 21 }; 22 req.send ();

      Nota: El nombre del campo y el nombre de la tabla de entidad se requieren de la misma manera. Luego, compare el <attributevalue> con el valor real del campo ( Xrm.Page.getAttribute ("sFieldName"). GetValue () ) en el bucle for, y finalmente obtenga la etiqueta del campo.

5. Postdata (Tucao un poco)

      Cada vez que se escribe un blog trabajador, los reptiles y otros lo transfieren en menos de una hora, una palabra del mismo tipo, y finalmente agrega una oración "reimpreso / dirección original: xxxxx", por favor levante la mano, Puede publicar un enlace como referencia, el contenido es bueno o malo, y mi publicación en el blog no es necesariamente correcta. Algunos artículos han sido actualizados durante algún tiempo después de que los escribí. Lo más divertido es usar un motor de búsqueda para buscar en mi blog. El artículo (título) en realidad no está en frente ==, solo puedo decir que eres tú. Dicho esto, finalmente vamos a dar algunas sugerencias prácticas. Si encuentra algunas dificultades en el desarrollo de CRM, puede usar la versión internacional de Bing para encontrarlo. Después de todo, los propios productos de Microsoft, además, los futuros blogs probablemente estén en caracteres tradicionales. Lo escribí, hábitos personales, el propósito original era recordar lo que usaba, reptiles o algo así, arrastrarme hacia el maestro (susurrando bb).

Supongo que te gusta

Origin www.cnblogs.com/Sunny20181123/p/12007226.html
Recomendado
Clasificación