Conteúdo

ALV Tree / Hierárquico

ALV é o relatório mais comum da SAP, e possui vários tipos. Um deles é chamado de ALV TREE, onde é possível amarrar um item ao outro, e visualizar no formato de árvore, conforme abaixo.

---Exemplo---

REPORT ZSAPeiros.

************************************************************************************
* ICONES
************************************************************************************
INCLUDE <icon>.                                               " Ícones diversos


************************************************************************************
* TIPOS
************************************************************************************
TYPES:
* Tabela de saída
  BEGIN OF ty_relatorio,
    vbeln               TYPE lips-vbeln,
    posnr               TYPE lips-posnr,
    matnr               TYPE lips-matnr,
  END OF ty_relatorio,

* Tabela para localizar ítens na árvore
  BEGIN OF ty_indice,
    tabix               TYPE lvc_nkey,                  " Número da linha na tabela
    linha               TYPE lvc_nkey,                  " Número de linha na árvore
  END OF ty_indice.


************************************************************************************
* CONTAINERS
************************************************************************************
DATA:
  g_alv_tree            TYPE REF TO cl_gui_alv_tree,          " Objeto árvore ALV
  g_custom_container    TYPE REF TO cl_gui_custom_container.  " Objeto container


************************************************************************************
* TABELAS E SUAS ESTRUTURAS
************************************************************************************
DATA:
  t_lips                TYPE TABLE OF ty_relatorio,
  w_lips                TYPE          ty_relatorio,
  t_relatorio           TYPE TABLE OF ty_relatorio,
  t_relatorio_itens     TYPE TABLE OF ty_relatorio,
  w_relatorio           TYPE          ty_relatorio,
  ti_fieldcat           TYPE          lvc_t_fcat,
  wa_fieldcat           TYPE LINE OF  lvc_t_fcat,
  ti_relacao            TYPE TABLE OF ty_indice,
  wa_relacao            TYPE          ty_indice.


************************************************************************************
* CONSTANTES
************************************************************************************
CONSTANTS:  c_raiz  TYPE lvc_nkey VALUE ''.          " Diretório raiz.(árvore)


************************************************************************************
* TELA DE SELEÇÃO
************************************************************************************
SELECTION-SCREEN BEGIN OF BLOCK bl1.
SELECT-OPTIONS:
  p_vbeln FOR w_lips-vbeln OBLIGATORY.
SELECTION-SCREEN END OF BLOCK bl1.


************************************************************************************
* START-OF-SELECTION
************************************************************************************
START-OF-SELECTION.
* Seleção dos dados
  PERFORM f_seleciona_dados.

* Tela do ALV Hierarquico
  CALL SCREEN 0100. "Dê 2 cliques para criar a tela 0100 -> Foto 01
* Nesta tela, 0100, criar um Custon Control com o nome MAIN_CONTAINER -> Foto 02
* Após criar a tela e o container, vá para o código onde terá o PBO e PAI -> Foto 03


************************************************************************************
* FORMS
************************************************************************************
************************************************************************************
* SELEÇÃO DOS DADOS
************************************************************************************
FORM f_seleciona_dados.
  SELECT vbeln posnr matnr
    FROM lips
    INTO TABLE t_lips
   WHERE vbeln IN p_vbeln.

  LOOP AT t_lips INTO w_lips.
    w_relatorio-vbeln = w_lips-vbeln.
    w_relatorio-posnr = w_lips-posnr.
    w_relatorio-matnr = w_lips-matnr.
    APPEND w_relatorio TO t_relatorio.
    CLEAR w_relatorio.
  ENDLOOP.
ENDFORM.                    "f_seleciona_dados


************************************************************************************
* CAMPOS A SEREM VISUALIZADOS NO ALV
************************************************************************************
FORM build_fieldcatalog.
  wa_fieldcat-fieldname     = 'POSNR'.
  wa_fieldcat-coltext       = 'Item'.
  wa_fieldcat-ref_table     = 'LIPS'.
  wa_fieldcat-ref_field     = 'POSNR'.
  APPEND wa_fieldcat TO ti_fieldcat.
  CLEAR wa_fieldcat.
ENDFORM.                    "build_fieldcatalog


************************************************************************************
* DESCRIÇÃO CAMPO PRINCIPAL DO CABEÇALHO NA ÁRVORE DO ALV
************************************************************************************
FORM build_hierarchy_header CHANGING p_hierarchy_header TYPE treev_hhdr.
  p_hierarchy_header-heading = 'Fornecimento'.
  p_hierarchy_header-tooltip = 'Fornecimento / Material'.
ENDFORM.                    "build_hierarchy_header


************************************************************************************
* PBO OUTPUT
************************************************************************************
MODULE pbo OUTPUT.
* TELA DE BOTÕES
  SET PF-STATUS 'STATUS_1000'. 
* Dê 2 cliques no nome do pf-status para criar a tela 1000 -> Foto 04
* E onde você irá adicionar os botões EXIT BACK CANC -> Foto 05

* Verifica se já existe container criado então, evitando runtime error
  IF g_alv_tree IS INITIAL.
*   Cria container ALVTree
    PERFORM create_alvtree_container.
*   Cria objeto ALVTree dentro do container
    PERFORM create_object_in_container.
*   Cria controle ALVTree vazio
    PERFORM create_empty_alvtree_control.
*   Cria hierarquia do ALVTree
    PERFORM create_alvtree_hierarchy.
  ENDIF.

* Retorno de Erros possíveis
  CALL METHOD cl_gui_cfw=>flush.
ENDMODULE.                    "pbo OUTPUT


************************************************************************************
* PAI INPUT
************************************************************************************
MODULE pai INPUT.
  DATA: v_okcode TYPE sy-ucomm.
  CASE v_okcode.
    WHEN 'EXIT' OR 'BACK' OR 'CANC'.
*     Retorno de Erros possíveis e volta para tela inicial
      CALL METHOD cl_gui_cfw=>flush.
      LEAVE TO SCREEN 0.
    WHEN OTHERS.
*     Retorno de Erros possíveis e volta para tela inicial
      CALL METHOD cl_gui_cfw=>flush.
      LEAVE TO SCREEN 0.
  ENDCASE.
ENDMODULE.                    "pai INPUT


************************************************************************************
* CRIA O CUSTOM CONTAINER
************************************************************************************
FORM create_alvtree_container.
  CREATE OBJECT g_custom_container
    EXPORTING
      container_name              = 'MAIN_CONTAINER'
    EXCEPTIONS
      cntl_error                  = 1
      cntl_system_error           = 2
      create_error                = 3
      lifetime_error              = 4
      lifetime_dynpro_dynpro_link = 5.

  IF sy-subrc <> 0.
  ENDIF.
ENDFORM.                    "create_alvtree_container


************************************************************************************
* CRIA O ALVTREE CONTAINER
************************************************************************************
FORM create_object_in_container.
  CREATE OBJECT g_alv_tree
    EXPORTING
      parent                      = g_custom_container
      node_selection_mode         = cl_gui_column_tree=>node_sel_mode_single
      item_selection              = 'X'
      no_html_header              = 'X'
      no_toolbar                  = ''
    EXCEPTIONS
      cntl_error                  = 1
      cntl_system_error           = 2
      create_error                = 3
      lifetime_error              = 4
      illegal_node_selection_mode = 5
      failed                      = 6
      illegal_column_name         = 7.

  IF sy-subrc <> 0.
  ENDIF.
ENDFORM.                    "create_object_in_container


************************************************************************************
* CRIA O CONTROLE ALVTREE (VAZIO)
************************************************************************************
FORM create_empty_alvtree_control.
* Ajusta o cabeçalho da árvode do ALV
  DATA e_hierarchy_header TYPE treev_hhdr.
  PERFORM build_hierarchy_header CHANGING e_hierarchy_header.

* Monta os campos a serem visualizados
  PERFORM build_fieldcatalog.

* Ativa a árvore
  CALL METHOD g_alv_tree->set_table_for_first_display
    EXPORTING
      is_hierarchy_header = e_hierarchy_header
    CHANGING
      it_outtab           = t_relatorio_itens
      it_fieldcatalog     = ti_fieldcat.
ENDFORM.                    "create_empty_alvtree_control


************************************************************************************
* CRIA HIERARQUIA
************************************************************************************
FORM create_alvtree_hierarchy.
* Carrega os ítens na árvore
  PERFORM carrega_itens_na_arvore.

* Otimiza o tamanho das colunas
  CALL METHOD g_alv_tree->column_optimize
    EXCEPTIONS
      start_column_not_found = 1
      end_column_not_found   = 2
      OTHERS                 = 3.

* Envia os dados para o frontend
  CALL METHOD g_alv_tree->frontend_update.
ENDFORM.                    "create_alvtree_hierarchy


************************************************************************************
* MONTA CABEÇALHO
************************************************************************************
FORM monta_cabecalho CHANGING p_node_key TYPE lvc_nkey.
  DATA: ld_node_text   TYPE lvc_value,    " Valor apresentado no cabeçalho
        lt_item_layout TYPE lvc_t_layi,   " Carrega layout do item
        ls_item_layout TYPE lvc_s_layi,   " Carrega layout do item
        is_node_layout TYPE lvc_s_layn.   " Ícones de seleção "pastinha"

* Neste caso, a separação será pelo VBELN, conforme abaixo:
  ls_item_layout-fieldname = g_alv_tree->c_hierarchy_column_name.
  ls_item_layout-style     = cl_gui_column_tree=>style_default.
  ld_node_text             = w_relatorio-vbeln.
  APPEND ls_item_layout TO lt_item_layout.
  CLEAR  ls_item_layout.

* Substitui o ícone da "pastinha"
  is_node_layout-n_image   = icon_rating_positive. "Item Aberto
  is_node_layout-exp_image = icon_rating_minus.    "Item Fechado

* Adiciona a "pastinha"
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = c_raiz
      i_relationship   = cl_gui_column_tree=>relat_last_child
      is_node_layout   = is_node_layout
      it_item_layout   = lt_item_layout
      i_node_text      = ld_node_text
      is_outtab_line   = w_relatorio
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                    "monta_cabecalho


************************************************************************************
* MONTA ITENS
************************************************************************************
FORM add_item_line USING    p_relate_key TYPE lvc_nkey
                   CHANGING p_node_key   TYPE lvc_nkey.
  DATA: ld_node_text TYPE lvc_value,      " Valor apresentado no head
        lt_item_layout TYPE lvc_t_layi,   " Carrega layout do item
        ls_item_layout TYPE lvc_s_layi,   " Carrega layout do item
        is_node_layout TYPE lvc_s_layn.   " Ícones de seleção "pastinha"

* Neste caso, abaixo do VBELN, informado anteriormente ao montar o Cebeçalho,
* será apresentado os Materiais (MATNR)
  ls_item_layout-fieldname = g_alv_tree->c_hierarchy_column_name.
  ls_item_layout-style     = cl_gui_column_tree=>style_default.
  ld_node_text             = w_relatorio-matnr.
  APPEND ls_item_layout TO lt_item_layout.
  CLEAR ls_item_layout.

* Substitui o ícone da "folinha"
  is_node_layout-n_image   = icon_material. "Item Aberto
  is_node_layout-exp_image = icon_material. "Item Fechado

* Adiciona "folinha"
  CALL METHOD g_alv_tree->add_node
    EXPORTING
      i_relat_node_key = p_relate_key
      i_relationship   = cl_gui_column_tree=>relat_last_child
      is_node_layout   = is_node_layout
      it_item_layout   = lt_item_layout
      i_node_text      = ld_node_text
      is_outtab_line   = w_relatorio
    IMPORTING
      e_new_node_key   = p_node_key.
ENDFORM.                    "add_item_line


************************************************************************************
* CARREGA ITENAS NA ÁRVORE DO ALVTREE
************************************************************************************
FORM carrega_itens_na_arvore.
* Variáveis auxiliares para montagem das "pastinhas", neste caso, por MATNR
  DATA: v_item        TYPE lips-matnr,     " Material
        v_cabeca_key  TYPE lvc_nkey,       " Chave de posição de head
        v_item_key    TYPE lvc_nkey.       " Chave de posição de item

  LOOP AT t_relatorio INTO w_relatorio.

*   Controle da linha da árvore X linha da tabela
*   Serve para localizar a linha da tabela que se refere cada linha da árvore.
    wa_relacao-tabix = sy-tabix.

    ADD 1 TO wa_relacao-linha.

*   Neste caso, cria uma nova hierarquia para cada novo VBELN
    IF w_relatorio-vbeln <> v_item.
      v_item = w_relatorio-vbeln.
*     Adiciona uma "pastinha"
      PERFORM monta_cabecalho CHANGING v_cabeca_key.
      APPEND wa_relacao TO ti_relacao.
      ADD 1 TO wa_relacao-linha.
    ENDIF.

*   Neste caso, adiciona os itens referentes ao VBELN
    PERFORM add_item_line USING v_cabeca_key
                       CHANGING v_item_key.

    APPEND wa_relacao TO ti_relacao.

  ENDLOOP.
ENDFORM.                    "carrega_itens_na_arvore

Foto 01

Foto 02

Foto 03

Foto 04

Foto 05