Exemplo: Criar OptionSets dependentes (listas de seleção)

 

Publicado: novembro de 2016

Aplicável a: Dynamics CRM 2015

Um requisito comum é que os valores em um campo de conjunto de opções precisam ser filtrado por um valor escolhido para outro campo de conjunto de opções. Este tópico descreve uma abordagem para fazer isso com uma biblioteca reutilizável do JScript, eventos de formulário e um recurso da Web XML.

Para observar e verificar a funcionalidade desse exemplo, é possível instalar a solução gerenciada DependentOptionSetsSample_1_0_0_2_managed.zip pelo seguinte local no download do SDK: SDK\SampleCode\JS\FormScripts

Baixe o pacote do SDK do Microsoft Dynamics CRM.

Metas para essa solução

Esta solução foi projetada para cumprir os seguintes requisitos:

  • Ela fornece uma biblioteca genérica e reutilizável JScript que pode ser usada para qualquer par de campos de conjunto de opções.

  • Ela permite uma cadeia de campos de conjunto de opções dependentes. Como as opções de cada campo de conjunto de opções dependentes são filtradas com base no valor de outro campo, opções adicionais de campos de conjunto de opções podem ser filtradas pela opção escolhida no primeiro campo do conjunto de opções dependentes. Isso permite a possibilidade de um conjunto de campos de conjunto de opções hierarquicamente dependentes.

  • A filtragem de opções dependentes é definida em um recurso da Web XML. Isso permite alterar os mapeamentos de opção sem alterar o código. Editar um recurso da Web XML é mais fácil para um não desenvolvedor configurar opções com menos oportunidade de interromper o código.

  • A solução suporta vários idiomas. A filtragem é baseada exclusivamente no valor dos dados das opções, não em qualquer texto nas opções.

  • A filtragem funciona para qualquer número de instâncias de um controle do atributo no formulário.

Exemplo

Esta seção descreve uma aplicação dessa abordagem e o procedimento para aplicar a biblioteca de exemplos.

O formulário da entidade Tíquete (sample_ticket) tem três campos de conjunto de opções e opções que permitem a categorização de produtos. A tabela abaixo mostra a filtragem desejada do conjunto de opções.

Categoria

(sample_category)

Subcategoria

(sample_subcategory)

Tipo

(sample_type)

Valor:727000000 Rótulo: Software

Valor:727000000 Rótulo: Produtividade pessoal

Valor:727000000 Rótulo: Processador de texto

Valor:727000001 Rótulo: Planilha

Valor:727000002 Rótulo: Navegador da Internet

Valor:727000003 Rótulo: E-mail

Valor:727000001 Rótulo: Aplicativos de negócio

Valor:727000004 Rótulo: Gerenciamento de Relacionamento com o Cliente

Valor:727000005 Rótulo: Gerenciamento de Recursos Empresariais

Valor:727000006 Rótulo: Gerenciamento de Recursos Humanos

Valor:727000002 Rótulo: Sistemas operacionais

Valor:727000007 Rótulo: Windows Vista

Valor:727000008 Rótulo: Windows 7

Valor:727000009 Rótulo: Windows Server 2003

Valor:727000010 Rótulo: Windows Server 2008

Valor:727000001 Rótulo: Hardware

Valor:727000003 Rótulo: Computador Desktop

Valor:727000011 Rótulo: Estação de Trabalho x1000

Valor:727000012 Rótulo: Estação de Trabalho x2000

Valor:727000013 Rótulo: Estação de Trabalho x3000

Valor:727000014 Rótulo: Estação de Trabalho x4000

Valor:727000004 Rótulo: Computador Laptop

Valor:727000015 Rótulo: Laptop Série 1000

Valor:727000016 Rótulo: Laptop Série 2000

Valor:727000017 Rótulo: Laptop Série 3000

Valor:727000018 Rótulo: Laptop Série 4000

Valor:727000005 Rótulo: Monitor

Valor:727000019 Rótulo: CRT-XYZ 17 pol.

Valor:727000020 Rótulo: LCD-XYZ 17 pol.

Valor:727000021 Rótulo: LCD-XYZ 21 pol.

Valor:727000022 Rótulo: LCD-XYZ 24 pol.

Valor:727000006 Rótulo: Impressora

Valor:727000023 Rótulo:Impressora Série 1000 - Privativa

Valor:727000024 Rótulo: Impressora Colorida Série 2000 - Privativa

Valor:727000025 Rótulo: Impressora Série 9000 - Compartilhada

Valor:727000026 Rótulo: Impressora Colorida Série 9000 - Compartilhada

Valor:727000007 Rótulo: Telefone

Valor:727000027 Rótulo: Telefone PSTN

Valor:727000028 Rótulo: Telefone IP

Valor:727000029 Rótulo: Telefone Celular

Habilitar a filtragem

  1. Converter a filtragem desejada das opções no seguinte documento do XML e depois carregue-o como um recurso da Web do XML intitulado sample_TicketDependentOptionSetConfig.xml. Os valores do rótulo estão incluídos para tornar o documento mais fácil de editar, mas não são usados no script que filtra as opções.

    
    <DependentOptionSetConfig entity="sample_ticket" >
     <ParentField id="sample_category"
                  label="Category">
      <DependentField id="sample_subcategory"
                      label="Sub Category" />
      <Option value="727000000"
              label="Software">
       <ShowOption value="727000000"
                   label="Personal Productivity" />
       <ShowOption value="727000001"
                   label="Business Applications" />
       <ShowOption value="727000002"
                   label="Operating Systems" />
      </Option>
      <Option value="727000001"
              label="Hardware">
       <ShowOption value="727000003"
                   label="Desktop Computer" />
       <ShowOption value="727000004"
                   label="Laptop Computer" />
       <ShowOption value="727000005"
                   label="Monitor" />
       <ShowOption value="727000006"
                   label="Printer" />
       <ShowOption value="727000007"
                   label="Telephone" />
      </Option>
     </ParentField>
     <ParentField id="sample_subcategory"
                  label="Sub Category">
      <DependentField id="sample_type"
                      label="Type" />
      <Option value="727000000"
              label="Personal Productivity">
       <ShowOption value="727000000"
                   label="Word Processor" />
       <ShowOption value="727000001"
                   label="Spreadsheet" />
       <ShowOption value="727000002"
                   label="Internet Browser" />
       <ShowOption value="727000003"
                   label="E-mail" />
      </Option>
      <Option value="727000001"
              label="Business Applications">
       <ShowOption value="727000004"
                   label="Customer Relationship Management" />
       <ShowOption value="727000005"
                   label="Enterprise Resource Management" />
       <ShowOption value="727000006"
                   label="Human Resource Managment" />
      </Option>
      <Option value="727000002"
              label="Operating Systems">
       <ShowOption value="727000007"
                   label="Windows Vista" />
       <ShowOption value="727000008"
                   label="Windows 7" />
       <ShowOption value="727000009"
                   label="Windows Server 2003" />
       <ShowOption value="727000010"
                   label="Windows Server 2008" />
      </Option>
      <Option value="727000003"
              label="Desktop Computer">
       <ShowOption value="727000011"
                   label="Workstation x1000" />
       <ShowOption value="727000012"
                   label="Workstation x2000" />
       <ShowOption value="727000013"
                   label="Workstation x3000" />
       <ShowOption value="727000014"
                   label="Workstation x4000" />
      </Option>
      <Option value="727000004"
              label="Laptop Computer">
       <ShowOption value="727000015"
                   label="Laptop 1000 series" />
       <ShowOption value="727000016"
                   label="Laptop 2000 series" />
       <ShowOption value="727000017"
                   label="Laptop 3000 series" />
       <ShowOption value="727000018"
                   label="Laptop 4000 series" />
      </Option>
      <Option value="727000005"
              label="Monitor">
       <ShowOption value="727000019"
                   label="CRT-XYZ 17 inch" />
       <ShowOption value="727000020"
                   label="LCD-XYZ 17 inch" />
       <ShowOption value="727000021"
                   label="LCD-XYZ 21 inch" />
       <ShowOption value="727000022"
                   label="LCD-XYZ 24 inch" />
      </Option>
      <Option value="727000006"
              label="Printer">
       <ShowOption value="727000023"
                   label="Series 1000 Printer - Private" />
       <ShowOption value="727000024"
                   label="Series 2000 Color Printer - Private" />
       <ShowOption value="727000025"
                   label="Series 9000 Printer - Shared" />
       <ShowOption value="727000026"
                   label="Series 9000 Color Printer - Shared" />
      </Option>
      <Option value="727000007"
              label="Telephone">
       <ShowOption value="727000027"
                   label="PSTN Phone" />
       <ShowOption value="727000028"
                   label="IP Phone" />
       <ShowOption value="727000029"
                   label="Mobile Phone" />
      </Option>
     </ParentField>
    </DependentOptionSetConfig>
    
  2. Crie um recurso da Web chamado sample_SDK.DependentOptionSetSample.jsJScript usando o seguinte código.

    
    
    //If the SDK namespace object is not defined, create it.
    if (typeof (SDK) == "undefined")
    { SDK = {}; }
    // Create Namespace container for functions in this library;
    SDK.DependentOptionSet = {};
    SDK.DependentOptionSet.init = function (webResourceName) {
     //Retrieve the XML Web Resource specified by the parameter passed
     var clientURL = Xrm.Page.context.getClientUrl();
    
     var pathToWR = clientURL + "/WebResources/" + webResourceName;
     var xhr = new XMLHttpRequest();
     xhr.open("GET", pathToWR, true);
     xhr.setRequestHeader("Content-Type", "text/xml");
     xhr.onreadystatechange = function () { SDK.DependentOptionSet.completeInitialization(xhr); };
     xhr.send();
    };
    SDK.DependentOptionSet.completeInitialization = function (xhr) {
     if (xhr.readyState == 4 /* complete */) {
         if (xhr.status == 200) {
             xhr.onreadystatechange = null; //avoids memory leaks
       var JSConfig = [];
       var ParentFields = xhr.responseXML.documentElement.getElementsByTagName("ParentField");
       for (var i = 0; i < ParentFields.length; i++) {
        var ParentField = ParentFields[i];
        var mapping = {};
        mapping.parent = ParentField.getAttribute("id");
        mapping.dependent = SDK.Util.selectSingleNode(ParentField, "DependentField").getAttribute("id");
        mapping.options = [];
        var options = SDK.Util.selectNodes(ParentField, "Option");
        for (var a = 0; a < options.length; a++) {
         var option = {};
         option.value = options[a].getAttribute("value");
         option.showOptions = [];
         var optionsToShow = SDK.Util.selectNodes(options[a], "ShowOption");
         for (var b = 0; b < optionsToShow.length; b++) {
          var optionToShow = {};
          optionToShow.value = optionsToShow[b].getAttribute("value");
          optionToShow.text = optionsToShow[b].getAttribute("label");
          option.showOptions.push(optionToShow);
         }
         mapping.options.push(option);
        }
        JSConfig.push(mapping);
       }
       //Attach the configuration object to DependentOptionSet
       //so it will be available for the OnChange events 
       SDK.DependentOptionSet.config = JSConfig;
       //Fire the onchange event for the mapped optionset fields
       // so that the dependent fields are filtered for the current values.
       for (var depOptionSet in SDK.DependentOptionSet.config) {
        var parent = SDK.DependentOptionSet.config[depOptionSet].parent;
        Xrm.Page.data.entity.attributes.get(parent).fireOnChange();
       }
      }
     }
    };
     // This is the function set on the onchange event for 
     // parent fields
    SDK.DependentOptionSet.filterDependentField = function (parentField, childField) {
     for (var depOptionSet in SDK.DependentOptionSet.config) {
      var DependentOptionSet = SDK.DependentOptionSet.config[depOptionSet];
      /* Match the parameters to the correct dependent optionset mapping*/
      if ((DependentOptionSet.parent == parentField) &amp;&amp; (DependentOptionSet.dependent == childField)) {
       /* Get references to the related fields*/
       var ParentField = Xrm.Page.data.entity.attributes.get(parentField);
       var ChildField = Xrm.Page.data.entity.attributes.get(childField);
       /* Capture the current value of the child field*/
       var CurrentChildFieldValue = ChildField.getValue();
       /* If the parent field is null the Child field can be set to null */
       if (ParentField.getValue() == null) {
        ChildField.setValue(null);
        ChildField.setSubmitMode("always");
        ChildField.fireOnChange();
    
        // Any attribute may have any number of controls
        // So disable each instance
        var controls = ChildField.controls.get()
    
        for (var ctrl in controls) {
         controls[ctrl].setDisabled(true);
        }
        return;
       }
    
       for (var os in DependentOptionSet.options) {
        var Options = DependentOptionSet.options[os];
        var optionsToShow = Options.showOptions;
        /* Find the Options that corresponds to the value of the parent field. */
        if (ParentField.getValue() == Options.value) {
         var controls = ChildField.controls.get();
         /*Enable the field and set the options*/
         for (var ctrl in controls) {
          controls[ctrl].setDisabled(false);
          controls[ctrl].clearOptions();
    
          for (var option in optionsToShow) {
           controls[ctrl].addOption(optionsToShow[option]);
          }
    
         }
         /*Check whether the current value is valid*/
         var bCurrentValueIsValid = false;
         var ChildFieldOptions = optionsToShow;
    
         for (var validOptionIndex in ChildFieldOptions) {
          var OptionDataValue = ChildFieldOptions[validOptionIndex].value;
    
          if (CurrentChildFieldValue == OptionDataValue) {
           bCurrentValueIsValid = true;
           break;
          }
         }
         /*
         If the value is valid, set it.
         If not, set the child field to null
         */
         if (bCurrentValueIsValid) {
          ChildField.setValue(CurrentChildFieldValue);
         }
         else {
          ChildField.setValue(null);
         }
         ChildField.setSubmitMode("always");
         ChildField.fireOnChange();
         break;
        }
       }
      }
     }
    };
    
    SDK.Util = {};
    //Helper methods to merge differences between browsers for this sample
     SDK.Util.selectSingleNode = function (node, elementName) {
      if (typeof (node.selectSingleNode) != "undefined") {
       return node.selectSingleNode(elementName);
      }
      else {
       return node.getElementsByTagName(elementName)[0];
      }
     };
     SDK.Util.selectNodes = function (node, elementName) {
      if (typeof (node.selectNodes) != "undefined") {
       return node.selectNodes(elementName);
      }
      else {
       return node.getElementsByTagName(elementName);
      }
     };
    
  3. Adicione o recurso de script da Web sample_SDK.DependentOptionSetSample.js às bibliotecas JScript disponíveis para o formulário.

  4. No evento Onload para o formulário, configure o manipulador de eventos para chamar a função SDK.DependentOptionSet.init e passe no nome do recurso da Web XML como um parâmetro. Use o campo na caixa de diálogo Propriedades do manipulador para inserir: "sample_TicketDependentOptionSetConfig.xml" no campo Lista separada por vírgulas de parâmetros que serão passados para a função.

  5. No evento OnChange para o campo Categoria, defina a Função como SDK.DependentOptionSet.filterDependentField.

    Na caixa de texto Lista separada por vírgulas de parâmetros que serão passados para a função insira: "sample_category", "sample_subcategory".

  6. No evento OnChange para o campo Subcategoria, defina a Função como SDK.DependentOptionSet.filterDependentField.

    Na caixa de texto Lista separada por vírgulas de parâmetros que serão passados para a função insira: "sample_subcategory ", "sample_type".

  7. Salve e publique todas as personalizações.

Confira Também

Use o modelo de objeto Xrm.Page
Criar códigos para os formulários do Microsoft Dynamics CRM 2015
Usar o Javascript com o Microsoft Dynamics CRM 2015
Personalizar formulários de entidade
Atributo Xrm.Page.data.entity (referência do cliente)
Controle Xrm.Page.ui (referência do cliente)

© 2017 Microsoft. Todos os direitos reservados. Direitos autorais