ALV Grid

De SAP ABAP en castellano
Saltar a: navegación, buscar

Mediante el objeto ALV Grid es posible implementar la funcionalidad de un listado y muchas opciones más dentro de un dynpro.

Puedes ver muchos ejemplos de su utilización dentro de la clase de desarrollo SLIS.

Contenido

EJEMPLO

Los pasos que debes seguir son:

  1. Crea un programa ejecutable desde la transacción SE38
  2. Crea un dynpro y coloca dentro de él un custom container llamado ALV_CONTAINER
  3. Crea un botón. Dale el texto Salir y el codigo de función EXIT
  REPORT sapmz_hf_alv_grid .
 
  TABLES: sflight.
 
  *--------------------------------------------------------------------
  * G L O B A L   I N T E R N  A L   T A B L E S
  *--------------------------------------------------------------------
  DATA: gi_sflight TYPE STANDARD TABLE OF sflight.
 
  *--------------------------------------------------------------------
  * G L O B A L   D A T A
  *--------------------------------------------------------------------
  DATA: ok_code LIKE sy-ucomm,
        g_wa_sflight LIKE sflight.
 
  * Declara las variables de referencia a los objetos ALV Grid y su contenedor
  DATA:
    go_grid             TYPE REF TO cl_gui_alv_grid,
    go_custom_container TYPE REF TO cl_gui_custom_container.

  *--------------------------------------------------------------------
  * S T A R T - O F - S E L E C T I O N.
  *--------------------------------------------------------------------
  START-OF-SELECTION.
    SET SCREEN '100'.

  *&---------------------------------------------------------------------*
  *&      Module  USER_COMMAND_0100  INPUT
  *&---------------------------------------------------------------------*
  MODULE user_command_0100 INPUT.
    CASE ok_code.
      WHEN 'EXIT'.
        LEAVE TO SCREEN 0.
    ENDCASE.
  ENDMODULE.                 " USER_COMMAND_0100  INPUT

  *&---------------------------------------------------------------------*
  *&      Module  STATUS_0100  OUTPUT
  *&---------------------------------------------------------------------*
  MODULE status_0100 OUTPUT.
  * Crea los objetos
    IF go_custom_container IS INITIAL.
      CREATE OBJECT go_custom_container
        EXPORTING container_name = 'ALV_CONTAINER'.

      CREATE OBJECT go_grid
        EXPORTING
          i_parent = go_custom_container.

      PERFORM load_data_into_grid.
    ENDIF.
  ENDMODULE.                 " STATUS_0100  OUTPUT
 
  *&---------------------------------------------------------------------*
  *&      Form  load_data_into_grid
  *&---------------------------------------------------------------------*
  FORM load_data_into_grid.
  * Read data from table SFLIGHT
    SELECT *
      FROM sflight
      INTO TABLE gi_sflight.

  * Carga los datos en el grid y los muestra por pantalla
    CALL METHOD go_grid->set_table_for_first_display
      EXPORTING i_structure_name = 'SFLIGHT'
      CHANGING  it_outtab        = gi_sflight.
 
  ENDFORM.                    " load_data_into_grid

Permitir al usuario grabar y reutilizar una variante de disposición

Un ejemplo de como hacer eso se puede ver en el programa BCALV_GRID_09.

Para permitir esta opción, debemos informar los parámetros IS_VARIANT y I_SAVE del método set_table_for_first_display.

El parámetro I_SAVE Opciones para grabación de disposiciones debe tener uno de los siguientes valores:

   * U Sólo se pueden grabar disposiciones específicas de usuario
   * X Sólo se permite grabar disposiciones globales
   * A Se permiten grabar disposiciones de usuario y globales 
   * Espacio No se pueden grabar disposiciones.

Añade el siguiente código al ejemplo anterior:

 FORM load_data_into_grid.
 DATA:
 *   Variable para el parámetro IS_VARIANT
     l_layout TYPE disvariant.
 * Read data from table SFLIGHT
   SELECT *
     FROM sflight
     INTO TABLE gi_sflight.

 * Carga los datos en el grid y los muestra por pantalla
   l_layout-report = sy-repid.
 
   CALL METHOD go_grid->set_table_for_first_display
     EXPORTING i_structure_name = 'SFLIGHT'
               is_variant       = l_layout
               i_save           = 'A'
     CHANGING  it_outtab        = gi_

Integrar funciones de usuarios en la barra de herramientas del grid

Posibilidades:

  • Reemplazar funciones existentes en la barra herramientas o de contexto con funciones definidas por el usuario.
  • Añadir nuevas funciones a la barra de herramientas o de contexto

Ten en cuenta que la barra de herramientas entera puede ser eliminada completamente fijando el parámetro IT_TOOLBAR_EXCLUDING del método set_table_for_first_display.

Puedes ver un ejemplo de esto en el programa estándar BCALV_GRID_05

1) Para tener acceso a los iconos, inserta la siguiente linea en el inicio del programa:

 TYPE-POOLS: icon.

2) Para permitir la declaración de la clase o_event_receiver before antes de que la clase lcl_event_receiver sea definida, declara como deferred al inicio del programa:

 CLASS lcl_event_receiver DEFINITION DEFERRED.

3) Declara una referencia a la clase manejadora del evento

 DATA: o_event_receiver TYPE REF TO lcl_event_receiver.

4) Clase para el receptor del evento. Esta clase añade el nuevo botón a la barra de herramientas y maneja este evento cuando se pulse el botón

 CLASS lcl_event_receiver DEFINITION.
   PUBLIC SECTION.
     METHODS:
      handle_toolbar FOR EVENT toolbar OF cl_gui_alv_grid
        IMPORTING
          e_object e_interactive,
 
      handle_user_command FOR EVENT user_command OF cl_gui_alv_grid
        IMPORTING e_ucomm.
 ENDCLASS.
 
 *---------------------------------------------------------------------*
 *       CLASS lcl_event_receiver IMPLEMENTATION
 *---------------------------------------------------------------------*
 CLASS lcl_event_receiver IMPLEMENTATION.
   METHOD handle_toolbar.
 *  Manejador del evento para el evento toolbar
 
     CONSTANTS:
 *  Constantes de botón
       c_button_normal           TYPE i VALUE 0,
       c_menu_and_default_button TYPE i VALUE 1,
       c_menu                    TYPE i VALUE 2,
       c_separator               TYPE i VALUE 3,
       c_radio_button            TYPE i VALUE 4,
       c_checkbox                TYPE i VALUE 5,
       c_menu_entry              TYPE i VALUE 6.
 
     DATA:
         ls_toolbar  TYPE stb_button.
 
 *   Añade un separador 
     CLEAR ls_toolbar.
     MOVE c_separator TO ls_toolbar-butn_type..
     APPEND ls_toolbar TO e_object->mt_toolbar.
 
 *   Append a new button that to the toolbar. Use E_OBJECT of
 *   event toolbar. E_OBJECT is of type CL_ALV_EVENT_TOOLBAR_SET.
 *   This class has one attribute MT_TOOLBAR which is of table type
 *   TTB_BUTTON. The structure is STB_BUTTON
     CLEAR ls_toolbar.
     MOVE 'CHANGE'        TO ls_toolbar-function.
     MOVE  icon_change    TO ls_toolbar-icon.
     MOVE 'Change flight' TO ls_toolbar-quickinfo.
     MOVE 'Change'        TO ls_toolbar-text.
     MOVE ' '             TO ls_toolbar-disabled.
     APPEND ls_toolbar    TO e_object->mt_toolbar.
   ENDMETHOD.
 
   METHOD handle_user_command.
 *   Handle own functions defined in the toolbar
     CASE e_ucomm.
       WHEN 'CHANGE'.
         LEAVE TO SCREEN 0.
     ENDCASE.
 
   ENDMETHOD.
 ENDCLASS.

5) En el PBO, crea el objeto para manejar eventos

   CREATE OBJECT o_event_receiver.
 
   SET HANDLER o_event_receiver->handle_user_command FOR go_grid.
   SET HANDLER o_event_receiver->handle_toolbar FOR go_grid.

6) En el PBO despues del CALL METHOD go_grid->set_table_for_first_display, dispara el evento toolbar para mostrar la barra de herramientas modificada.

   CALL METHOD go_grid->set_toolbar_interactive.

Posicionar el foco en el grid

Después de CALL METHOD go_grid->set_table_for_first_display inserta las siguientes líneas:

   CALL METHOD cl_gui_control=>set_focus EXPORTING control = go_grid.

Introduce el título del grid

Rellena el campo grid_title de la estructura lvc_s_layo.


  DATA:
  * ALV control: estructura de formato
  gs_layout TYPE lvc_s_layo.
  
  * Indica el título del grid
  gs_layout-grid_title = 'Flights'.
  
  CALL METHOD go_grid->set_table_for_first_display
           EXPORTING i_structure_name = 'SFLIGHT'
                     is_layout               = gs_layout
           CHANGING   it_outtab               = gi_sflight.


Color

Debes definir en la estructura un campo que indique qué quieres colorear. A whole list record can be colored individually using a color code in a column of the internal output table for the record. Assign the name of the field containing the color code to this parameter. The internal output table field must be of type CHAR(3). The code must have the following syntax:

 'Cxy':
 C = color (all codes must start with 'C')
 x = color number ('1'-'9')
 y = bold ('0' = off, '1' = on)
  • 1 Azul
  • 2 Blanco
  • 3 Amarillo
  • 4 Azul
  • 5 Verde
  • 6 Rojo
  • 7 Naranja

Note: the color of the key columns is not affected. Key columns can be colored at record or cell level using the complex coloring which is described in the next parameter COLTAB_FIELDNAME. To color columns, see the documentation of the field catalog parameter FIELDCAT-EMPHASIZE of the IMPORTING parameter IT_FIELDCAT.

 coltab_fieldname
value set: SPACE, internal output table field name

Cells can be colored individually using a color code which is contained in a column of the internal output table for the record containing the cell. Assign the name of the field to this parameter.

The internal output table field must be of type SLIS_T_SPECIALCOL_ALV. Principle: the color code field is entered for the record containing the cells to be colored. The field contains an internal table with the above structure, containing the field names of the cells to be colored and the color code. The cell coordinates are determined by the record position containing the color code and the column information in the color table. The record structure of the internal color table of type SLIS_T_SPECIALCOL_ALV is as follows:

Color table-FIELDNAME = field name of the cell to be colored
Color table-COLOR-COL = color number (1 - 9)
Color table-COLOR-INT = bold (0 = off, 1 = on)
Color table-COLOR-INV = inverse (0 = off, 1 = on)
Color table-NOKEYCOL  = ignore key coloring ('X' = yes, ' ' = no)

If the parameter color table-FIELDNAME is not filled, the coloring applies to all fields, so the entire record is colored.

Iconos

Incluir en tu tabla de datos un campo de tipo ICON_D, 
que almacenaría el código del icono a mostrar 
(Por ejemplo llamaremos al campo ICONS). 
En el fieldcatalog del ALV: Cuando se esté haciendo referencía 
al nuevo campo que has creado en tu tabla de datos 
(WA_FIELDCAT-FIELDNAME = 'ICONS') has de activar en esa entrada 
el campo ICON (WA_FIELDCAT-ICON = 'X'). 
Finalmente solo te quedaría incluir en tu tabla de datos los 
códigos de icono que vas a meter: Por ejemplo este -> '@0A@' 
(que correspondería a un semaforo en rojo)

Formato de celda

El formato de una celda se modifica mediante un campo del tipo LVC_T_STYL que hay que añadir a la definición de la tabla interna del ALV. Este campo hay que indicarlo en el layout del ALV en el campo STYLEFNAME. El tipo LVC_T_STYL contiene un campo FIELDNAME donde se le indica el nombre del campo al que se le quiere cambiar el estilo y el campo STYLE donde se le indica el estilo a aplicar al campo. Para modificar el color de una celda el proceso es similar pero con un campo del tipo LVC_T_SCOL. En este caso el campo se indicará en el layout del ALV en el campo CTAB_FNAME. Para más claridad ver los siguientes apartados.

Mostrar celda como botón

1. Añadir campo a la estructura

DATA BEGIN OF gt_list OCCURS 0 .
 INCLUDE STRUCTURE mara .
 DATA cellstyles TYPE lvc_t_styl .
 DATA END OF gt_list .

2. Añadir el campo al layout.

gs_layout-stylefname = 'CELLSTYLES'.

3. Modificar el campo añadido

DATA ls_style TYPE lvc_s_styl .
READ TABLE gt_list INDEX 7 .
 ls_style-fieldname = 'MATNR' .
 ls_style-style = cl_gui_alv_grid=>mc_style_button .
 APPEND ls_style TO gt_list-cellstyles .
 MODIFY gt_list INDEX 7 .

Cambiar el color de una celda

El tipo lvc_t_scol tiene como campos principales FNAME que indica el nombre del campo a modificar y COLOR que es una estructura con los valores del color a aplicar. Los pasos son los siguientes: 1. Añadir campo a la estructura

DATA BEGIN OF gt_list OCCURS 0 .
 INCLUDE STRUCTURE mara .
 DATA cellcolors TYPE lvc_t_scol .
 DATA END OF gt_list .

2. Añadir el campo al layout.

gs_layout-ctab_fname = 'CELLCOLORS'.

3. Modificar el campo añadido

DATA ls_color TYPE lvc_s_scol .
READ TABLE gt_list INDEX 7 .
 ls_color-fname = 'MATNR' .
 ls_color-color-col = ‘3’.
 Ls_color-color-int = ‘1’. 
 APPEND ls_color TO gt_list-cellcolors .
 MODIFY gt_list INDEX 7 .


Métodos más importantes

  • CHECK_CHANGED_DATA Comprueba los datos contenidos en el grid y refresca la tabla interna con estos datos.
  • REFRESH_TABLE_DISPLAY Refresca el grid con el contenido de la tabla interna

Eventos

Ejemplo implementación evento HOTSPOT_CLICK en ALV Grid

Listados de ejemplo suministrador por SAP

  • BCALV_EDIT_01 This report illustrates the simplest case of using an editable/noneditable ALV Grid Control.
  • BCALV_EDIT_02 This report illustrates how to set chosen cells of an ALV Grid Control editable.
  • BCALV_EDIT_03 In this example the user may change values of fields SEATSOCC (occupied seats) and/or PLANETYPE. The report checks the input value(s) semantically and provides protocol messages in case of error
  • BCALV_EDIT_04 This report illustrates how to add and remove lines to a table using the ALV Grid Control and how to

implement the saving of the new data.

  • BCALV_EDIT_05 This example shows how to use checkboxes within an ALV Grid Control. You learn:
  1. how to define a column for editable checkboxes for an attribute of your list
  2. how to evaluate the checked checkboxes
  3. how to switch between editable and non-editable checkboxes
  • BCALV_EDIT_06 This example shows how to define a dropdown listbox for all cells of one column in an editable ALV

Grid Control.

  • BCALV_EDIT_07 This example shows how to define dropdown listboxes for particular cells of your output table.
  • BCALV_EDIT_08 This report implements an ALV Grid Control with an application specific F4 help. The following aspects

are dealt with:

  1. how to replace the standard f4 help
  2. how to pass the selected value to the ALV Grid Control
  3. how to build an f4 help, whose value range depend on a value of another cell.

Ejemplo 2

Este ejemplo muestra el funcionamiento de campos editables, cómo capturar el evento de modificacion de estos campo, cómo chequear la modificación de estos campos, cómo capturar el evento de doble click sobre una línea y cómo hacer de un campo una lista desplegable

Debemos tener un dynpro 0100 con un CONTROL CUSTOM llamado CC_ALV
EL dynpro tendra la siguiente logica

PROCESS BEFORE OUTPUT.
  MODULE STATUS_0100.
  module display_alv.
PROCESS AFTER INPUT.
 module exit at exit-command.
 MODULE USER_COMMAND_0100.

ademas de un status
STATUS_ALV con botones con codigos de funcion asociados a
EXIT, BACK y CANC


 
*&---------------------------------------------------------------------*
*& Report  Z_ALV_GRID_OO                                               *
*&                                                                     *
*&---------------------------------------------------------------------*
*& Ejemplo ALV grid OO sobre tabla estandar Flight                     *
*&    ejemplo de columnas editables, captura de eventos de doble     *
*&    click y abandono de celda editable modificada entre otros      *
*& Autor: Ignacio Diez Esteban                                         *
*& Fecha: Diciembre 2005                                               *
*&                                                                     *
*&---------------------------------------------------------------------*

REPORT  Z_ALV_GRID_OO.

************************************************************************
* Tablas
************************************************************************
tables: sflight.
************************************************************************
* Declaracion inicial de clases
************************************************************************
*- Clase manejadora de los eventos del ALV grid
class lcl_event_handler definition deferred.
*----------------------------------------------------------------------*
*  Variables para ALV
*----------------------------------------------------------------------*
* nombre objeto alvgrid
data gr_alvgrid type ref to cl_gui_alv_grid.
* nombre del control de dynpro
* Debemos crear en una dynpro un contenedor generico(Control Custom)
* yo lo he llamado CC_ALV. En nuestro caso el dynpro es el 0100
data gc_cc_name type scrfname value 'CC_ALV'.
* instancia de la referencia al contenedor
data gr_ccontainer type ref to cl_gui_custom_container.
* catalogo de campos
data gt_fieldcat type lvc_t_fcat.
* Estructura de layout
data gs_layout type lvc_s_layo.
* tabla de ordenacion y subtotales
data gt_sort type lvc_t_sort.
* manejador de eventos
data gr_event_handler type ref to lcl_event_handler.

* CLASES Definicion
class lcl_event_handler definition.
  public section.
    methods:
*    doble click sobre registro alv
      handle_double_click for event double_click of cl_gui_alv_grid
                                 importing e_row e_column,
*     modificacion de celda
      handle_data_changed for event data_changed of cl_gui_alv_grid
                             importing er_data_changed.

endclass.
* Implementacion de las clases
class lcl_event_handler implementation.
  method handle_double_click.
    perform double_click using e_row e_column .
  endmethod.
  method handle_data_changed.
    perform handle_data_changed using er_data_changed.
  endmethod.

endclass.


************************************************************************
* Variables y Tablas internas
************************************************************************
data: begin of i_tab occurs 0.
   include structure sflight.
      end of i_tab.

************************************************************************
* Pantalla de selección
************************************************************************
selection-screen: begin of block b1 with frame title text-S01.
select-options s_carrid for sflight-carrid. "denominacion de compañia
selection-screen: end of block b1 .

************************************************************************
* Start-of-selection
************************************************************************
start-of-selection.
  perform get_data.
************************************************************************
* end-of-selection.
************************************************************************
end-of-selection.
  call screen 0100.
 

*&---------------------------------------------------------------------*
*&      Form  get_data
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
*  -->  p1        text
*  <--  p2        text
*----------------------------------------------------------------------*
FORM get_data.
  select * into table i_tab
    from sflight
   where carrid in s_carrid.
ENDFORM.                    " get_data

*&---------------------------------------------------------------------*
*&      Module  display_alv  OUTPUT
*&---------------------------------------------------------------------*

MODULE display_alv OUTPUT.
  perform display_alv.
ENDMODULE.                 " display_alv  OUTPUT
*&---------------------------------------------------------------------*
*&      Form  display_alv
*&---------------------------------------------------------------------*

FORM display_alv.
* en la primera visualizacion no tenemos ninguna instancia de alvgrid
* por lo que debemos crearla con sus caracteristicas
  if gr_alvgrid is initial.

*  creamos instancia del contenedor
    CREATE OBJECT gr_ccontainer
      EXPORTING
        CONTAINER_NAME              = gc_cc_name
      EXCEPTIONS
        CNTL_ERROR                  = 1
        CNTL_SYSTEM_ERROR           = 2
        CREATE_ERROR                = 3
        LIFETIME_ERROR              = 4
        LIFETIME_DYNPRO_DYNPRO_LINK = 5
        others                      = 6
        .
    IF SY-SUBRC <> 0.
      MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                 WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
*    creamos instancia del alv grid
    CREATE OBJECT gr_alvgrid
      EXPORTING
        I_PARENT          = gr_ccontainer
        .
* creamos el manejador de eventos y se los asignamos a gr_alvgrid
    create object gr_event_handler.
    set handler gr_event_handler->handle_double_click for gr_alvgrid.
    set handler gr_event_handler->handle_data_changed for gr_alvgrid.
* decimos que queremos controlar cada modificacion en el alv por
* separado, al salir de la celda
    CALL METHOD GR_ALVGRID->REGISTER_EDIT_EVENT
      EXPORTING
        I_EVENT_ID = cl_gui_alv_grid=>mc_evt_modified
      .

* cargamos el catalogo
    perform cargar_cat changing gt_fieldcat.
* cargamos caracteristicas del layout
    perform cargar_lyt changing gs_layout.
* cargamos las caracteristicas de ordenacion
    perform cargar_sort changing gt_sort.
* cargamos valores de los desplegables, hay un campo editable con una
* lista de desplegables
    perform cargar_desplegables.
* ajustamos el diseño, ¡NO TENGO MUY CLARO QUE HACE ESTO!
    call method gr_alvgrid->set_adjust_design
      exporting
        ADJUST_DESIGN = 1.
* Y mostramos nuestro ALV grid por primera vez
    CALL METHOD GR_ALVGRID->SET_TABLE_FOR_FIRST_DISPLAY
      EXPORTING
        IS_LAYOUT                     = gs_layout
      CHANGING
        IT_OUTTAB                     = i_tab[]
        IT_FIELDCATALOG               = gt_fieldcat
        IT_SORT                       = gt_sort
   .
  else.
* ya tenemos todo generado e instanciado, solo tenemos que recargar el
* ALV grid 
    CALL METHOD GR_ALVGRID->REFRESH_TABLE_DISPLAY.
  endif.
ENDFORM.                    " display_alv
*&---------------------------------------------------------------------*
*&      Form  cargar_cat
*&---------------------------------------------------------------------*

FORM cargar_cat CHANGING pt_fieldcat type lvc_t_fcat.
  data ls_fcat type lvc_s_fcat.
* tengo la mania de generarme el catalogo manualmente y para ahorrarme
* lineas utilizo la siguiente subrutina o variaciones de la misma segun
* necesidad 
  perform c_alv using 'SFLIGHT' "referencia de la tabla de diccionario
              'CARRID'  "referencia del campo de la tabla de dic
                      'CARRID'  "Nombre del campo de mi tabla interna
                      'Compañia'  "Texto de la cabecera
                      '' '' ''  "distintos flags (editar,sumar,desplegable)
                CHANGING pt_fieldcat.
 
  perform c_alv using 'SFLIGHT'
              'CONNID'
              'CONNID'
              'Vuelo'
              '' '' ''
             CHANGING pt_fieldcat.
  perform c_alv using 'SFLIGHT'
              'FLDATE'
              'FLDATE'
              'Fecha'
              '' '' ''
             CHANGING pt_fieldcat.            
  perform c_alv using 'SFLIGHT'
              'PRICE'
              'PRICE'
              'Precio'
              '' 'X' ''  "Subtotalizaremos este campo
             CHANGING pt_fieldcat.            
   perform c_alv using 'SFLIGHT'
              'PLANETYPE'
              'PLANETYPE'
              'Tipo Avion'
              'X' '' 'X' "editable y lista desplegable
             CHANGING pt_fieldcat.     
   perform c_alv using 'SFLIGHT'
              'SEATSMAX'
              'SEATMAX'
              'Ocupacion Max'
              '' '' ''
             CHANGING pt_fieldcat.              
   perform c_alv using 'SFLIGHT'
              'SEATSOCC'
              'SEATSOCC'
              'Plazas ocupadas'
              'X' '' '' "editable
             CHANGING pt_fieldcat.            
                
             
ENDFORM.                    " cargar_cat
*&---------------------------------------------------------------------*
*&      Form  cargar_lyt
*&---------------------------------------------------------------------*

FORM cargar_lyt CHANGING ps_layout type lvc_s_layo.
  ps_layout-zebra = 'X'.
  ps_layout-grid_title = 'Vuelos'.
  ps_layout-cwidth_opt = 'X'.
  ps_layout-no_toolbar = 'X'. "sin barra de botones
ENDFORM.                    " cargar_lyt
*&---------------------------------------------------------------------*
*&      Form  cargar_sort
*&---------------------------------------------------------------------*

FORM cargar_sort CHANGING pt_sort type lvc_t_sort.
  "ordenaremos por compañia y fecha y solo totalizaremos por compañia
  data ls_sort type lvc_s_sort.

  ls_sort-spos = '1'. "nivel de ordenacion
  ls_sort-fieldname = 'CARRID'. "ordenamos por compañias
  ls_sort-up = 'X'. "hacia arriaba
  ls_sort-down = space.
  ls_sort-subtot = 'X'. "y queremos subtotales
  append ls_sort to pt_sort. clear ls_sort.
 
  ls_sort-spos = '2'. "nivel de ordenacion
  ls_sort-fieldname = 'FLDATE'. "subordenamos por fecha
  ls_sort-up = 'X'. "hacia arriba
  ls_sort-down = space.
  ls_sort-subtot = ''. "y no queremos subtotales
  append ls_sort to pt_sort. clear ls_sort.
ENDFORM.                    " cargar_sort
*&---------------------------------------------------------------------*
*&      Form  c_alv
*&---------------------------------------------------------------------*

FORM c_alv USING    ref_tab ref_field field texto edit sum drop
           CHANGING PT_FIELDCAT type lvc_t_fcat.
* caracteristicas de columna           
  data ls_fieldcat type lvc_s_fcat.
  ls_fieldcat-ref_table = ref_tab.
  ls_fieldcat-ref_field = ref_field.
  ls_fieldcat-fieldname = field.
  ls_fieldcat-edit = edit.
  ls_fieldcat-do_sum = sum.
  ls_fieldcat-drdn_hndl = drop.
*  ls_fieldcat-OUTPUTLEN = n.
  if  texto <> space.
    ls_fieldcat-coltext = texto.
    ls_fieldcat-seltext = texto.
    ls_fieldcat-reptext = texto.

  endif.
  append ls_fieldcat to pt_fieldcat. clear ls_fieldcat.

ENDFORM.                    " c_alv
*&---------------------------------------------------------------------*
*&      Module  STATUS_0100  OUTPUT
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
MODULE STATUS_0100 OUTPUT.
  perform set_status_alv.
ENDMODULE.                 " STATUS_0100  OUTPUT
*---------------------------------------------------------------------*
*       FORM set_status_alv                                           *
*---------------------------------------------------------------------*

form set_status_alv.

  types: begin of l_ty_s_excl,
           func type syucomm,
         end   of l_ty_s_excl,
         l_ty_t_excl type standard table of l_ty_s_excl.

  data: lt_excl type l_ty_t_excl.

  set pf-status 'STATUS_100' excluding lt_excl.

endform.                    " d0100_set_status
*&---------------------------------------------------------------------*
*&      Module  USER_COMMAND_0100  INPUT
*&---------------------------------------------------------------------*

MODULE USER_COMMAND_0100 INPUT.
  perform user_command.
ENDMODULE.                 " USER_COMMAND_0100  INPUT
*&---------------------------------------------------------------------*
*&      Module  exit  INPUT
*&---------------------------------------------------------------------*

MODULE exit INPUT.
  perform user_command.
ENDMODULE.                 " exit  INPUT
*&---------------------------------------------------------------------*
*&      Form  user_command
*&---------------------------------------------------------------------*

FORM user_command.
  data: l_okcode like sy-ucomm.

  l_okcode = sy-ucomm.

  case l_okcode.
    when 'EXIT' or 'BACK' or 'CANC'.
      perform exit.

    when 'SAVE'.
      call method gr_alvgrid->check_changed_data.

  endcase.

ENDFORM.                    " user_command
*&---------------------------------------------------------------------*
*&      Form  exit
*&---------------------------------------------------------------------*

FORM exit.
  call method gr_alvgrid->free.
  call method gr_ccontainer->free.
  call method cl_gui_cfw=>flush.
  clear gr_ccontainer.
  clear gr_alvgrid.

  set screen 0.
  leave screen.

ENDFORM.                    " exit

*&---------------------------------------------------------------------*
*&      Form  double_click
*&---------------------------------------------------------------------*
FORM double_click USING    P_ROW
                           P_COLUMN.
  read table i_tab index p_row.
* lo que deseis hacer sobre la fila seleccionada del alv
ENDFORM.                    " double_click

*&---------------------------------------------------------------------*
*&      Form  handle_data_changed
*&---------------------------------------------------------------------*
* manejamos los datos cambiados al salir de una celda modificada
FORM handle_data_changed
           USING P_DATA type ref to cl_alv_changed_data_protocol.
* algo chungo de contar... veamos           

  data: ls_mod_cell type lvc_s_modi,
        lv_value type lvc_value,
        sw_ok type i.
* ordenamos la lista de celdas modificadas por el numero de fila       
  sort p_data->mt_mod_cells by row_id.
* vamos metiendo esas celdas en  ls_mod_cell
  loop at p_data->mt_mod_cells into ls_mod_cell.
* para chequear el dato insertado
    sw_ok = 0.
* nombre de la celda/columna, solo nos interesan controlar las editables   
    case ls_mod_cell-fieldname.
      when 'PLANETYPE'.
        perform check_tipoavion using ls_mod_cell-value
                            changing sw_ok.

      when 'SEATSOCC'.
        perform check_n_ocupados using ls_mod_cell-value
                            changing sw_ok.

     
    endcase.
* si todo correcto modificamos la celda   
    if sw_ok <> 0. "la condicion puede variar segun implementeis los
                   " check_*
      call method p_data->modify_cell
        exporting i_row_id = ls_mod_cell-row_id
                  i_fieldname = ls_mod_cell-fieldname
                  i_value = ''.
    endif.
  endloop.

ENDFORM.                    " handle_data_changed
*&---------------------------------------------------------------------*
*&      Form  check_tipoavion
*&---------------------------------------------------------------------*

FORM check_tipoavion using value type lvc_s_modi-value
                  changing sw_ok type i.
* y tratamos la informacion                 

ENDFORM.                    " check_kostl
*&---------------------------------------------------------------------*
*&      Form  check_n_ocupados
*&---------------------------------------------------------------------*

FORM check_n_ocupados using value type lvc_s_modi-value
                 changing sw_ok type i.

* y tratamos value

ENDFORM.                    " check_order

*&---------------------------------------------------------------------*
*&      Form  cargar_desplegables
*&---------------------------------------------------------------------*
*   En nuestro caso solo el tipo de avion
FORM cargar_desplegables.
  data: lt_ddval type lvc_t_drop,
        ls_ddval type lvc_s_drop.
* ls_ddval-handle creo que diferencia los distintos desplegables
* en caso de que haya dos no estoy seguro de como se asignan a las columnas
* supongo que sera en orden de izquierda a derecha o algo asi
  ls_ddval-handle = '1'.
  ls_ddval-value = 'B-747'.
  append ls_ddval to lt_ddval.
  ls_ddval-handle = '1'.
  ls_ddval-value = 'C130'.
  append ls_ddval to lt_ddval.
  ls_ddval-handle = '1'.
  ls_ddval-value = 'F18 Hornet'.
  append ls_ddval to lt_ddval.

  call method gr_alvgrid->set_drop_down_table
    exporting
      it_drop_down = lt_ddval.
ENDFORM.                    " cargar_desplegables

Mostrar logotipo en la cabecera

A traves de la funcion REUSE_ALV_COMMENTARY_WRITE es posible mostrar un Logotipo en la cabecera de un listado.

FORM header_init.
 DATA: ls_header TYPE slis_listheader.
 CLEAR gt_header_top. REFRESH gt_header_top.

 CLEAR ls_header.
 ls_header-typ = 'H'.
 ls_header-info = 'AGENDA - Lista de contac tos'.
 APPEND ls_header TO gt_header_top.


ENDFORM.                    " header_init

FORM alv_events .
 DATA: ls_event TYPE slis_alv_event.

 CLEAR gt_events. REFRESH gt_events.
 CLEAR ls_event.
 ls_event-name = slis_ev_top_of_page.
 ls_event-form = 'TOP-OF-PAGE'.
 APPEND ls_event TO gt_events.
ENDFORM.                    " alv_events

FORM top-of-page .
 CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE'
   EXPORTING
     it_list_commentary       = gt_header_top
     i_logo = 'ENJOYSAP_LOGO'
*   I_END_OF_LIST_GRID       =
*   I_ALV_FORM               =
           .
ENDFORM.                    " top-of-page
Error al crear miniatura: No se ha podido guardar la miniatura

Enlaces

Herramientas personales
Espacios de nombres

Variantes
Acciones
Navegación
Herramientas
Google AdSense