programa alv

111
INCLUDE z_alvbtop . INCLUDE z_alvbs01 . INCLUDE z_alvbf01 . START-OF-SELECTION . PERFORM fp_lectura_de_datos . PERFORM fp_validacion . PERFORM fp_campos . PERFORM display_logo . ***************TOP*********************** *&---------------------------------------------------------------------* *& Include Z_ALVBTOP Report Z_ALVB *& *&---------------------------------------------------------------------* REPORT Z_ALVB . *------------------------------------------------------------------*** ** DECLARACIÓN DE ESTRUCTURAS Y VARIABLES ** ***------------------------------------------------------------------* TYPE-POOLS : slis . "Contiene todas las declaraciones de tipos necesarios para la ALV... TYPES : BEGIN OF ty_flight , carrid TYPE sflight - carrid , connid TYPE sflight - connid , fldate TYPE sflight - fldate , price TYPE sflight - price , seatsmax TYPE sflight - seatsmax , seatsocc TYPE sflight - seatsocc , paymentsum TYPE sflight - paymentsum , ahorro TYPE sflight - price ,

Upload: karma-avelcain

Post on 31-Dec-2015

200 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Programa ALV

INCLUDE z_alvbtop.INCLUDE z_alvbs01.INCLUDE z_alvbf01.

START-OF-SELECTION.

  PERFORM fp_lectura_de_datos.  PERFORM fp_validacion.  PERFORM fp_campos.  PERFORM display_logo.

***************TOP***********************

*&---------------------------------------------------------------------**& Include Z_ALVBTOP                                         Report Z_ALVB*&*&---------------------------------------------------------------------*

REPORT   Z_ALVB.

*------------------------------------------------------------------*****               DECLARACIÓN DE ESTRUCTURAS Y VARIABLES             *****------------------------------------------------------------------*

TYPE-POOLS : slis. "Contiene todas las declaraciones de tipos necesarios para la ALV...

TYPES : BEGIN OF ty_flight,        carrid     TYPE sflight-carrid,        connid     TYPE sflight-connid,        fldate     TYPE sflight-fldate,        price      TYPE sflight-price,        seatsmax   TYPE sflight-seatsmax,        seatsocc   TYPE sflight-seatsocc,        paymentsum TYPE sflight-paymentsum,        ahorro     TYPE sflight-price,        descuento  TYPE sflight-price,       END OF ty_flight.

CONSTANTS:  pr TYPE  sflight-price VALUE '0.20'.

Page 2: Programa ALV

DATA : it_flight        TYPE TABLE OF ty_flight,       wa_flight        TYPE ty_flight,       it_sflight       TYPE TABLE OF ty_flight,       wa_sflight       TYPE ty_flight,       it_fieldcat      TYPE slis_t_fieldcat_alv,       wa_fieldcat      TYPE slis_fieldcat_alv,       it_fieldcat1     TYPE slis_t_fieldcat_alv,       wa_fieldcat1     TYPE slis_fieldcat_alv,       wa_layout        TYPE slis_layout_alv,       wa_layout1       TYPE slis_layout_alv,       it_header        TYPE slis_t_listheader,       wa_header        TYPE slis_listheader,       it_header1       TYPE slis_t_listheader,       wa_header1       TYPE slis_listheader,       gv_resultado1    TYPE  sflight-price,       gv_resultado     TYPE sflight-price,       gv_inicio        TYPE c.

**********************F01¨*************************

*&---------------------------------------------------------------------**&  Include           Z_ALVBS01*&---------------------------------------------------------------------*

*------------------------------------------------------------------*****               DECLARACIÓN DE PARÁMETROS                          *****------------------------------------------------------------------*

If gv_inicio is not INITIAL.

SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.  "definen un bloque en la actual pantalla de selecciónPARAMETERS: pa_nom(10) TYPE c,            pa_edad(2) TYPE n,            pa_fecha   TYPE sy-datum.SELECTION-SCREEN END OF BLOCK b1.

SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.SELECT-OPTIONS : s_carrid FOR wa_flight-carrid,               s_connid FOR  wa_flight-connid.              " s_fldate FOR wa_flight-fldate.

SELECTION-SCREEN END OF BLOCK b2.

Page 3: Programa ALV

ENDIF.

*********************F01********************

*&---------------------------------------------------------------------**&  Include           Z_ALVBF01*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Form  FP_LECTURA_DE_DATOS*&---------------------------------------------------------------------*

*------------------------------------------------------------------*****               LECTURA DE LA TABLA SFLIGHT                        *****------------------------------------------------------------------*

FORM fp_lectura_de_datos .

  SELECT * FROM sflight   INTO CORRESPONDING FIELDS OF TABLE it_flight   WHERE carrid IN s_carrid AND connid IN s_connid.

ENDFORM.                    " FP_LECTURA_DE_DATOS*&---------------------------------------------------------------------**&      Form  FP_VALIDACION*&---------------------------------------------------------------------*

*------------------------------------------------------------------*****                   VALIDACIÓN SI > 60 Ó < 60                      *****------------------------------------------------------------------*

FORM fp_validacion .

  IF pa_nom IS NOT INITIAL " nombre  AND pa_edad IS NOT INITIAL. " edad    PERFORM fp_lectura_de_datos.  ELSE.    MESSAGE 'Ingrese sus datos' TYPE 'I'.  ENDIF.

  IF it_flight[] IS NOT INITIAL.   "Si la tabla contiene datos, recorre la tabla interna.    LOOP AT it_flight INTO wa_flight.

Page 4: Programa ALV

      "Si la edad ingresada es mayor o igual de 60, tendrá un 20% de descuento.      IF  pa_edad >= 60.        wa_flight-ahorro = wa_flight-price *  pr."- gv_resultado1.        wa_flight-price = wa_flight-price - wa_flight-ahorro.        MODIFY it_flight  FROM wa_flight.

      ENDIF.

    ENDLOOP.    "si la tabla no contiene información deseada, manda un mensaje informativo y muestra sugerencias.  ELSEIF  sy-subrc NE 0.    MESSAGE 'No hay vuelos disponibles en esa fecha, éstas son las sugerencias' TYPE 'I'.    CLEAR it_flight[]."Hace la lectura de todos los datos.    SELECT * FROM sflight   INTO CORRESPONDING FIELDS OF TABLE it_flight."Si la tabla no contiene datas entra a la rutina Sugerencias.    IF  it_flight[] IS NOT INITIAL.      PERFORM sugerencias.    ENDIF.

  ENDIF.ENDFORM.                    " FP_VALIDACION*&---------------------------------------------------------------------**&      Form  FP_CAMPOS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*FORM fp_campos .

*------------------------------------------------------------------*****       ALIMENTACIÓN Y VISUALIZACIÓN DE CAMPOS                     *****------------------------------------------------------------------*

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 1.              "Posición de la columna.  wa_fieldcat-fieldname = 'CARRID'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-key = 'X'.

Page 5: Programa ALV

  wa_fieldcat-seltext_s = 'FLIGHT CODE'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 2.  wa_fieldcat-fieldname = 'CONNID'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-key = 'X'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 3.  wa_fieldcat-fieldname = 'FLDATE'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-key = 'X'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 4.  wa_fieldcat-fieldname = 'PRICE'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-emphasize = 'C501'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 8.  wa_fieldcat-fieldname = 'AHORRO'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-reptext_ddic = 'Ahorro'.  "wa_fieldcat = gv_resultado1.  wa_fieldcat-emphasize = 'C201'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

*-------------------------------------------------------------------**             Llamada a la función; cabecera y logo                 **-------------------------------------------------------------------*

  CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'

Page 6: Programa ALV

    EXPORTING      i_callback_program     = sy-cprog      i_callback_top_of_page = 'DISPLAY_LOGO'      i_background_id        = 'LOGO_ALV2'      i_grid_title           = 'Información de vuelo'      is_layout              = wa_layout      it_fieldcat            = it_fieldcat    TABLES      t_outtab               = it_flight.

ENDFORM.                    " FP_CAMPOS*&---------------------------------------------------------------------**&      Form  DISPLAY_LOGO*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*

*-------------------------------------------------------------------**          CONTENIDO DE LA CABECERA                                 **-------------------------------------------------------------------*

FORM display_logo .

  wa_header-typ = 'S'.  wa_header-key = 'Usuario:'.  wa_header-info = sy-uname.  APPEND wa_header TO it_header.  CLEAR wa_header.

  wa_header-typ = 'S'.  wa_header-key = 'Fecha:'.  DATA: fecha_sistema(10).  WRITE sy-datum TO fecha_sistema USING EDIT MASK '__/__/____'.  wa_header-info = fecha_sistema.  APPEND wa_header TO it_header.  CLEAR wa_header.

  wa_header-typ = 'S'.  wa_header-key = 'Hora: '.  DATA: hora_sistema(10).  WRITE sy-uzeit TO hora_sistema USING EDIT MASK '__:__:____'.  wa_header-info = hora_sistema.  APPEND wa_header TO it_header.  CLEAR wa_header.

Page 7: Programa ALV

  wa_header-typ = 'S'.  wa_header-key = 'Nombre del cliente:'.  wa_header-info = pa_nom.

  APPEND wa_header TO it_header.  CLEAR wa_header.

  wa_header-typ = 'S'.  wa_header-key = 'Edad:'.  wa_header-info = pa_edad.  APPEND wa_header TO it_header.  CLEAR wa_header.

*  wa_header-typ = 'S'.*  wa_header-key = 'Ahorro:'.*  wa_header-info = gv_resultado1.*  APPEND wa_header TO it_header.*  CLEAR wa_header.

  CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE'    EXPORTING      it_list_commentary = it_header      i_logo             = 'AEROPLANE'.

  REFRESH it_header.

ENDFORM.                    " DISPLAY_LOGO*&---------------------------------------------------------------------**&      Form  SUGERENCIAS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*FORM sugerencias."Ordenamos la tabla con fechas. SORT it_flight BY  fldate. "Si la tabla it_flight no contiene datos  IF it_flight[] IS NOT INITIAL."Borramos los registros distintos a la fecha de selección.    DELETE it_flight WHERE  fldate NE pa_fecha.  ENDIF.

ENDFORM.                    " SUGERENCIAS

Page 8: Programa ALV

*****************************ALV_2B ************

INCLUDE: Z_ALV2B_TOP,   " global Data         Z_ALV2B_S01,         Z_ALV2B_F01." FORM-Routines

START-OF-SELECTION.

PERFORM LECTURA_DATOS.PERFORM VALIDACIONES.PERFORM ALV.

*************************TOP*************************

*&---------------------------------------------------------------------**& Include Z_ALV2B_TOP                                       Report Z_ALV_2B*&*&---------------------------------------------------------------------*

REPORT   Z_ALV_2B.TABLES: spfli, sflight.

DATA :

       gv_resultado1    TYPE  sflight-price,       gv_resultado     TYPE sflight-price.

TYPES: BEGIN OF tt_salida,carrid    TYPE s_carrid,connid    TYPE s_conn_id,fldate    TYPE s_date,countryfr TYPE land1,cityto    TYPE s_to_city,airpto    TYPE s_fromairp,deptime   TYPE s_dep_time,arrtime   TYPE s_arr_time,price     TYPE s_price,

Page 9: Programa ALV

currency  TYPE s_currcode,ahorro    TYPE s_price,"nombre    TYPE c,"edad      TYPE n,

END OF tt_salida.

CONSTANTS:  pr TYPE  s_price VALUE '0.20'.

DATA: BEGIN OF gt_sflight OCCURS 0,carrid    LIKE sflight-carrid,connid    LIKE sflight-connid,fldate    LIKE sflight-fldate,currency  LIKE sflight-currency,price     LIKE sflight-price,END OF gt_sflight.

DATA: BEGIN OF gt_spfli OCCURS 0,countryfr  LIKE spfli-countryfr,cityto     LIKE spfli-cityto ,airpto     LIKE spfli-airpto,deptime    LIKE spfli-deptime,arrtime    LIKE spfli-arrtime,

END OF gt_spfli.

DATA: gt_salida TYPE STANDARD TABLE OF tt_salida,wa_salida TYPE tt_salida,contador TYPE p,lv_count TYPE p, wa_sflight LIKE gt_sflight,lv_columns TYPE REF TO cl_salv_columns_table,lv_column  TYPE REF TO cl_salv_column,lv_alv_object TYPE REF TO cl_salv_table,g_functions TYPE REF TO cl_salv_functions,gr_display type ref to cl_salv_display_settings.

*************************S01************************

*&---------------------------------------------------------------------**&  Include           Z_ALV2B_S01*&---------------------------------------------------------------------*

SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.  "definen un bloque en la actual pantalla de selecciónPARAMETERS: pa_nom(10) TYPE c,

Page 10: Programa ALV

            pa_edad(2) TYPE n.SELECTION-SCREEN END OF BLOCK b1.

SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.SELECT-OPTIONS : s_carrid FOR sflight-carrid,                 s_connid FOR sflight-connid,                 s_fldate FOR sflight-fldate.

SELECTION-SCREEN END OF BLOCK b2.

*************************************F01****************************

*&---------------------------------------------------------------------**&  Include           Z_ALV2B_F01*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Form  LECTURA_DATOS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*FORM lectura_datos.Clear: gt_sflight[],       gt_spfli[],       gt_salida[].

  SELECT carrid          connid          fldate          price          currency   FROM   sflight   INTO CORRESPONDING FIELDS OF TABLE gt_sflight   WHERE carrid IN s_carrid AND connid IN s_connid                             AND fldate IN s_fldate.

  LOOP AT gt_sflight.

Page 11: Programa ALV

    MOVE-CORRESPONDING gt_sflight TO wa_salida.

    SELECT           countryfr           cityto           airpto           deptime           arrtime     INTO gt_spfli     FROM spfli.

      MOVE-CORRESPONDING  gt_spfli TO wa_salida.      APPEND wa_salida TO gt_salida.

    ENDSELECT.  ENDLOOP.

ENDFORM.                    " LECTURA_DATOS*&---------------------------------------------------------------------**&      Form  VALIDACIONES*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*FORM validaciones .

  IF  gt_salida[] is not initial .  "Si la tabla contiene datos, recorre la tabla interna.    LOOP AT gt_salida  INTO wa_salida .*      "Si la edad ingresada es mayor o igual de 60, tendrá un 20% de descuento.      IF  pa_edad >= 60.*        gv_resultado1 = wa_sflight-price * '0.20'.        wa_salida-ahorro =  wa_salida-price * pr.        wa_salida-price = wa_salida-price - wa_salida-ahorro.

        "wa_salida-price = wa_salida-price - wa_salida-price."- gv_resultado1.        MODIFY gt_salida  FROM wa_salida.      ENDIF.    ENDLOOP.*    "si la tabla no contiene información deseada, manda un mensaje informativo.

Page 12: Programa ALV

  ELSEIF  sy-subrc NE 0.    MESSAGE 'No hay vuelos disponibles en esa fecha seleccione otra' TYPE 'I'.

  ENDIF.

ENDFORM.                    " VALIDACIONES*&---------------------------------------------------------------------**&      Form  ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*FORM alv .

  IF gt_salida[] IS NOT INITIAL.

"CL_SALV_TABLE. Con ella podemos contruirnos un informe con tan solo llamar a un método el factory y luego al displa    cl_salv_table=>factory(    IMPORTING    r_salv_table = lv_alv_object    CHANGING    t_table = gt_salida    ).

    g_functions = lv_alv_object->get_functions( ).    g_functions->set_all( abap_true ).

    lv_columns = lv_alv_object->get_columns( ).    lv_columns->set_optimize( 'X' ).

 gr_display = lv_alv_object->get_display_settings( ). gr_display->set_striped_pattern( cl_salv_display_settings=>true ). gr_display->set_list_header( 'Vuelos y precios' ).

** Visualizamos el ALV    lv_alv_object->display( ).  ELSE.

Page 13: Programa ALV

    MESSAGE 'No tiene itinerario' TYPE 'I'.

  ENDIF.

ENDFORM.                    " ALV

********************************** Orientado a Objetos ************************

INCLUDE: z_alv_oo_top,         z_alv_oo_s01,         z_alv_oo_f01,         z_alv_oo_i01,         z_alv_oo_o01.

START-OF-SELECTION.  PERFORM validaciones.

************************Top******************************

*&---------------------------------------------------------------------**& Include Z_ALV_OO_TOP                                      Report Z_ALV_OO*&*&---------------------------------------------------------------------*

REPORT   Z_ALV_OO.

*------------------------------------------------------------------*****               DECLARACIÓN DE ESTRUCTURAS Y VARIABLES             *****------------------------------------------------------------------*

types : begin of ty_flight,        carrid   type sflight-carrid,        connid   type sflight-connid,        fldate   type sflight-fldate,        price    type sflight-price,        seatsmax type sflight-seatsmax,        seatsocc type sflight-seatsocc,        paymentsum type sflight-paymentsum,        ahorro     TYPE sflight-price,

Page 14: Programa ALV

        end of ty_flight.

DATA:      g_custom_container TYPE REF TO cl_gui_custom_container,      g_container TYPE scrfname VALUE 'CC_ALV',      alv_grid  TYPE REF TO cl_gui_alv_grid.

DATA:      ok_code       LIKE sy-ucomm, " Sy-ucomm para hacer las funciones de lo que el usuario desea hacer      wa_sflight    TYPE ty_flight,      it_sflight    TYPE STANDARD TABLE OF ty_flight,      gt_sflight    TYPE TABLE OF sflight,      gs_layout     TYPE lvc_s_layo,      gt_fieldcat   TYPE STANDARD TABLE OF lvc_s_fcat,      wa_fieldcat   TYPE lvc_s_fcat,      wa_exclude    TYPE ui_func,      gt_exclude    TYPE ui_functions.

CONSTANTS:  pr TYPE  sflight-price VALUE '0.20'.

data : it_flight        type table of ty_flight,       wa_flight        type ty_flight,

" Slis_layaout_alv,se utiliza para optimizar el Ancho de columna,"los colores alternos

       wa_layout        type slis_layout_alv,       wa_layout1       type slis_layout_alv,       it_header        type slis_t_listheader,       wa_header        type slis_listheader,       it_header1       type slis_t_listheader,       wa_header1       type slis_listheader.

DATA: it_spfli TYPE TABLE OF spfli.

"Nombre del programa ABAP actualDATA: g_repid TYPE sy-repid.

"slis_t_listheader da el título de una lista."está compuesto por el título de la lista en la barra de título y"de las cabeceras de columna.

Page 15: Programa ALV

DATA: it_listheader TYPE slis_t_listheader,      wa_listheader TYPE slis_listheader.

**************************************S01*****************************

*&---------------------------------------------------------------------**&  Include           Z_ALV_OO_S01*&---------------------------------------------------------------------*

*------------------------------------------------------------------*****               DECLARACIÓN DE PARÁMETROS                          *****------------------------------------------------------------------*

SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.PARAMETERS: pa_nom(20)    TYPE c,            p_edad(2)    TYPE n.SELECTION-SCREEN END OF BLOCK b1.

SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.

SELECT-OPTIONS : s_carrid FOR wa_sflight-carrid,                 s_connid FOR  wa_sflight-connid,                 s_fldate FOR wa_sflight-fldate.

SELECTION-SCREEN END OF BLOCK b2.

*------------------------------------------------------------------*****               Llamada a la pantalla                              *****------------------------------------------------------------------*

********************F01********************************

*&---------------------------------------------------------------------**&  Include           Z_ALV_OO_F01*&---------------------------------------------------------------------*

"Clase de receptor de eventos. Esta clase añade el nuevo botón a la barra de

Page 16: Programa ALV

"herramientas y controla el evento cuando se pulsa el botón

CLASS lcl_event_receiver DEFINITION.    PUBLIC SECTION.    METHODS:        m_toolbar FOR EVENT toolbar OF cl_gui_alv_gridIMPORTING e_object,

        m_user_command FOR EVENT user_command OF cl_gui_alv_gridIMPORTING e_ucomm.ENDCLASS.

CLASS lcl_event_receiver IMPLEMENTATION.  METHOD m_toolbar.   " Método de controlador de eventos para la barra de herramientas de eventos.    PERFORM f_toolbarUSING e_object.  ENDMETHOD.                    "m_toolbar

  METHOD m_user_command.    PERFORM f_user_command_1000USING e_ucomm.  ENDMETHOD.                    "m_user_commandENDCLASS.                    "lcl_event_receiver IMPLEMENTATION

*&---------------------------------------------------------------------**&      Form  RETRIEVE_DATA*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*FORM retrieve_data.

  SELECT * FROM sflight     INTO CORRESPONDING FIELDS OF TABLE gt_sflight     WHERE carrid IN s_carrid AND connid IN s_connid                              AND fldate IN s_fldate.

ENDFORM.                    " RETRIEVE_DATA

*&---------------------------------------------------------------------**&      Form  BUILD_FIELD_CATALOG*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*FORM build_field_catalog.

  REFRESH: gt_fieldcat.

Page 17: Programa ALV

  CLEAR: wa_fieldcat.***  wa_fieldcat-fieldname   = 'CARRID'.*  wa_fieldcat-scrtext_s   = 'ID'.*  wa_fieldcat-scrtext_m   = 'Compañía aérea'.*  wa_fieldcat-scrtext_l   = 'Compañía aérea'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.**  wa_fieldcat-fieldname   = 'CONNID'.*  wa_fieldcat-scrtext_s   = 'Núm.'.*  wa_fieldcat-scrtext_m   = 'Núm vuelo'.*  wa_fieldcat-scrtext_l   = 'Número de vuelo'.*  wa_fieldcat-emphasize   = 'C201'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.**  wa_fieldcat-fieldname   = 'FLDATE'.*  wa_fieldcat-scrtext_s   = 'Fecha'.*  wa_fieldcat-scrtext_m   = 'Fecha vuelo'.*  wa_fieldcat-scrtext_l   = 'Fecha del vuelo'.*  wa_fieldcat-emphasize   = 'C301'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.**  wa_fieldcat-fieldname   = 'PRICE'.*  wa_fieldcat-scrtext_s   = 'Precio'.*  wa_fieldcat-scrtext_m   = 'Precio vuelo'.*  wa_fieldcat-scrtext_l   = 'Precio del vuelo'.*  wa_fieldcat-emphasize   = 'C401'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.**  wa_fieldcat-fieldname   = 'CURRENCY'.*  wa_fieldcat-scrtext_s   = 'Moneda'.*  wa_fieldcat-scrtext_m   = 'Moneda'.*  wa_fieldcat-scrtext_l   = 'Moneda'.*  wa_fieldcat-emphasize   = 'C501'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.**  wa_fieldcat-fieldname   = 'SEATSMAX'.*  wa_fieldcat-scrtext_s   = 'Ocupación'.*  wa_fieldcat-scrtext_m   = 'Ocupación max.'.*  wa_fieldcat-scrtext_l   = 'Ocupación máxima'.*  wa_fieldcat-emphasize   = 'C601'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.

Page 18: Programa ALV

****  wa_fieldcat-fieldname   = 'SEATSOCC'.*  wa_fieldcat-scrtext_s   = 'Asientos oc.'.*  wa_fieldcat-scrtext_m   = 'Asientos oc.'.*  wa_fieldcat-scrtext_l   = 'Asientos ocupados'.*  wa_fieldcat-emphasize   = 'C701'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.*** wa_fieldcat-fieldname   = 'AHORRO'.*  wa_fieldcat-scrtext_s   = 'AHORRO.'.*  wa_fieldcat-scrtext_m   = 'AHORRO.'.*  wa_fieldcat-scrtext_l   = 'AHORRO'.*  wa_fieldcat-emphasize   = 'C701'.*  APPEND wa_fieldcat TO gt_fieldcat.*  CLEAR wa_fieldcat.*** wa_fieldcat-fieldname   = 'DESCUENTO'.**  wa_fieldcat-scrtext_s   = 'DESCUENTO.'.**  wa_fieldcat-scrtext_m   = 'DESCUENTO.'.**  wa_fieldcat-scrtext_l   = 'DESCUENTO'.**  wa_fieldcat-emphasize   = 'DESCUENTO'.**  APPEND wa_fieldcat TO gt_fieldcat.**  CLEAR wa_fieldcat.*

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 1.              "Posición de la columna.  wa_fieldcat-fieldname = 'CARRID'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-key = 'X'.  wa_fieldcat-seltext_s = 'FLIGHT CODE'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 2.  wa_fieldcat-fieldname = 'CONNID'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-key = 'X'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

Page 19: Programa ALV

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 3.  wa_fieldcat-fieldname = 'FLDATE'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-key = 'X'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 4.  wa_fieldcat-fieldname = 'PRICE'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-emphasize = 'C501'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

  wa_fieldcat-row_pos = 1.  wa_fieldcat-col_pos = 8.  wa_fieldcat-fieldname = 'AHORRO'.  wa_fieldcat-tabname = 'IT_FLIGHT'.  wa_fieldcat-ref_tabname = 'SFLIGHT'.  wa_fieldcat-reptext_ddic = 'Ahorro'.  "wa_fieldcat = gv_resultado1.  wa_fieldcat-emphasize = 'C201'.  APPEND wa_fieldcat TO it_fieldcat.  CLEAR wa_fieldcat.

ENDFORM.                    " BUILD_FIELD_CATALOG

*&---------------------------------------------------------------------**&      Form  BUILD_LAYOUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*FORM build_layout.  gs_layout-cwidth_opt  = 'X'.  gs_layout-col_opt     = 'X'.  gs_layout-zebra       = 'X'.ENDFORM.                    " BUILD_LAYOUT

*&---------------------------------------------------------------------**&      Form  EXCLUDE_BUTTONS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*

Page 20: Programa ALV

"excluyendo funciones para la barra de herramientas editable alv

FORM exclude_buttons.  REFRESH:    gt_exclude.

**********************************************************************mc_fc_check  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_check.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_refresh  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_refresh.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_cut  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_cut.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_copy  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_copy.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_paste  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_paste.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_paste_new_row  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_paste_new_row.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_undo  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_undo.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_append_row  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_append_row.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_insert_row

Page 21: Programa ALV

  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_insert_row.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_delete_row  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_delete_row.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_loc_copy_row  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_loc_copy_row.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_sort_asc

**********************************************************************mc_mb_sum  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_mb_sum.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_subtot  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_subtot.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_print  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_print.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_views  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_views.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_mb_export

**********************************************************************mc_fc_current_variant  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_current_variant.  APPEND wa_exclude TO gt_exclude.**********************************************************************mc_fc_graph  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_graph.  APPEND wa_exclude TO gt_exclude.

Page 22: Programa ALV

**********************************************************************mc_fc_info  CLEAR wa_exclude.  wa_exclude = cl_gui_alv_grid=>mc_fc_info.  APPEND wa_exclude TO gt_exclude.ENDFORM.                    " EXCLUDE_BUTTONS

*&---------------------------------------------------------------------**&      Form  EXIT_PROGRAM*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*FORM exit_program.  CALL METHOD g_custom_container->free.  CALL METHOD cl_gui_cfw=>flush.  LEAVE PROGRAM.  " Esta declaración inmediatamente termina el programa principal actual y elimina su interior sesión  " incluyendo todos los programas cargados,  "instancias y sus datos.ENDFORM.                    " EXIT_PROGRAM

*&---------------------------------------------------------------------**&      Form  F_TOOLBAR*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**      -->P_TOOLBAR  text*----------------------------------------------------------------------*FORM f_toolbar USING p_toolbar TYPE REF TO cl_alv_event_toolbar_set.  DATA:    lv_stb_button TYPE stb_button.

  "añadir separador  lv_stb_button-butn_type = '3'.  APPEND lv_stb_button TO p_toolbar->mt_toolbar.

  "añadir botón Salir  lv_stb_button-text = 'Salir'.  lv_stb_button-function = 'EXIT'.  lv_stb_button-icon = icon_cancel.  lv_stb_button-quickinfo = 'Salir'.  lv_stb_button-butn_type = ''.  APPEND lv_stb_button TO p_toolbar->mt_toolbar.ENDFORM.                    " F_TOOLBAR

*&---------------------------------------------------------------------**&      Form  F_USER_COMMAND_1000*&---------------------------------------------------------------------*

Page 23: Programa ALV

*       text*----------------------------------------------------------------------**      -->P_UCOMM    text*----------------------------------------------------------------------*FORM f_user_command_1000 USING p_ucomm TYPE sy-ucomm.  "UserCommand para el Toolbar del ALV  CASE p_ucomm.

    WHEN 'NEW'.    WHEN 'EDIT'.    WHEN 'REFRESH'.    WHEN 'EXIT'.      PERFORM exit_program.

  ENDCASE.ENDFORM.                    " F_USER_COMMAND_1000*&---------------------------------------------------------------------**&      Module  STATUS_0100  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*MODULE status_0100 OUTPUT.  SET PF-STATUS 'Z_ALV_OO_SG'.

  PERFORM build_field_catalog.  PERFORM build_layout.  PERFORM retrieve_data.

  CREATE OBJECT g_custom_container    EXPORTING      container_name = g_container.

  CREATE OBJECT alv_grid    EXPORTING      i_parent = g_custom_container.

  DATA: event_receiver TYPE REF TO lcl_event_receiver.

  CREATE OBJECT event_receiver.  SET HANDLER event_receiver->m_toolbar FOR alv_grid.  SET HANDLER event_receiver->m_user_command FOR alv_grid.

  CALL METHOD alv_grid->set_table_for_first_display    EXPORTING      i_structure_name     = 'WA_SFLIGHT'      is_layout            = gs_layout      it_toolbar_excluding = gt_exclude    CHANGING

Page 24: Programa ALV

      it_outtab            = gt_sflight      it_fieldcatalog      = gt_fieldcat.

  CALL METHOD cl_gui_control=>set_focus    EXPORTING      control = alv_grid.ENDMODULE.                 " STATUS_0100  OUTPUT

*----------------------------------------------------------------------**  MODULE USER_COMMAND_0100 INPUT*----------------------------------------------------------------------***----------------------------------------------------------------------*MODULE user_command_0100 INPUT.

  ok_code = sy-ucomm.

  CASE ok_code.    WHEN 'EXIT'.      PERFORM exit_program.  ENDCASE.ENDMODULE.                    "USER_COMMAND_0100 INPUT

" USER_COMMAND_0100  INPUT*&---------------------------------------------------------------------**&      Form  VALIDACIONES*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*FORM validaciones .  IF it_sflight[] is not INITIAL.   "Si la tabla contiene datos, recorre la tabla interna.    LOOP AT it_sflight INTO wa_sflight."Si la edad ingresada es mayor o igual de 60, tendrá un 20% de descuento.      IF  p_edad >= 60.       wa_sflight-ahorro = wa_sflight-price *  pr."- gv_resultado1.       wa_sflight-price = wa_sflight-price - wa_sflight-ahorro.        MODIFY it_sflight  FROM wa_sflight.

      ENDIF.    ENDLOOP."si la tabla no contiene información deseada, manda un mensaje informativo.  ELSEIF  sy-subrc NE 0.    MESSAGE 'No hay vuelos disponibles en esa fecha' TYPE 'I'.

Page 25: Programa ALV

  ENDIF.ENDFORM.                    " VALIDACIONES

FORM build_alv_header .

"Código de cabecera

  wa_listheader-typ = 'S'.  wa_listheader-key = 'Date :' .  CONCATENATE  sy-datum+6(2)               sy-datum+4(2)               sy-datum(4)               INTO wa_listheader-info               SEPARATED BY '/'.  APPEND wa_listheader TO it_listheader.  CLEAR wa_listheader.

 wa_listheader-typ  = 'H'.  wa_listheader-info ='Nombre'.   wa_listheader-info = pa_nom.  APPEND wa_listheader TO it_listheader.  CLEAR wa_listheader.

   wa_listheader-typ  = 'H'.  wa_listheader-info ='Edad'.   wa_listheader-info = p_edad.  APPEND wa_listheader TO it_listheader.  CLEAR wa_listheader.

  wa_listheader-typ = 'A'.  wa_listheader-info ='SAP ALV O.O'.  APPEND wa_listheader TO it_listheader.  CLEAR wa_listheader.ENDFORM.                    " BUILD_ALV_HEADER*&---------------------------------------------------------------------**&      Form  top_of_page*&---------------------------------------------------------------------*FORM top_of_page.

  CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE'    EXPORTING      it_list_commentary = it_listheader   i_callback_program     = g_repid     i_callback_top_of_page = 'TOP_OF_PAGE'      i_structure_name       = 'SFLIGHT'.

Page 26: Programa ALV

ENDFORM.

********************EJERcicio 2**********************************+

*&---------------------------------------------------------------------**& Report  Z_ALV_EJERCICIO*&*&---------------------------------------------------------------------**&*&*&---------------------------------------------------------------------*

report  z_alv_ejercicio.

tables: bkpf, t003t.

select-options: s_bukrs for bkpf-bukrs,s_gjahr for bkpf-bukrs,s_blart for bkpf-blart,s_monat for bkpf-monat,s_usnam for bkpf-usnam.

data: begin of gt_bkpf occurs 0,bukrs like bkpf-bukrs,blart like bkpf-blart,usnam like bkpf-usnam,belnr like bkpf-belnr,gjahr like bkpf-gjahr.data: end of gt_bkpf.

data: wa_bkpf like gt_bkpf.

types: begin of tt_salida,bukrs type bukrs,blart type blart,ltext type t003t-ltext,usnam type uname,contador type i,end of tt_salida.

data: gt_salida type standard table of tt_salida,wa_salida type tt_salida,contador type p,lv_count type p,lv_columns type ref to cl_salv_columns_table,

Page 27: Programa ALV

lv_column  type ref to cl_salv_column,lv_alv_object type ref to cl_salv_table,g_functions type ref to cl_salv_functions.

start-of-selection.refresh: gt_bkpf, gt_salida.

select blart belnr bukrs gjahr usnamfrom bkpfinto corresponding fields of table gt_bkpfwhere bukrs in s_bukrs andgjahr in s_gjahr andblart in s_blart andmonat in s_monat andusnam in s_usnam.

sort gt_bkpf by bukrs blart usnam.

loop at gt_bkpf.

clear: wa_bkpf, wa_salida.move-corresponding gt_bkpf to wa_bkpf.

clear lv_count.select single count( * )from   bseginto   lv_countwhere  belnr = gt_bkpf-belnr andbukrs = gt_bkpf-bukrs andgjahr = gt_bkpf-gjahr.

contador = contador + lv_count.

at end of usnam.

select single *from t003twhere blart = wa_bkpf-blart andspras = 'S'.

move-corresponding wa_bkpf to wa_salida.wa_salida-ltext = t003t-ltext.wa_salida-contador = contador.append wa_salida to gt_salida.clear: wa_salida.

clear contador.

endat.

Page 28: Programa ALV

endloop.

if gt_salida[] is not initial.

cl_salv_table=>factory(importingr_salv_table = lv_alv_objectchangingt_table = gt_salida).

g_functions = lv_alv_object->get_functions( ).g_functions->set_all( abap_true ).

lv_columns = lv_alv_object->get_columns( ).lv_columns->set_optimize( 'X' ).

** Cambiamos el nombre de la columna contador para que saque su descripciónlv_column = lv_columns->get_column('CONTADOR').lv_column->set_long_text( text-001 ).lv_column->set_medium_text( text-001 ).lv_column->set_short_text( text-001 ).** Visualizamos el ALVlv_alv_object->display( ).endif.

***********************************Ejercico2222 Pulsador **********

report z_alv_ejercicio2.include <icon>.

types : begin of ty_flight,        carrid   type sflight-carrid,        connid   type sflight-connid,        fldate   type sflight-fldate,        price    type sflight-price,        seatsmax type sflight-seatsmax,        seatsocc type sflight-seatsocc,        paymentsum type sflight-paymentsum,       end of ty_flight.

data: ok_code like sy-ucomm,      gt_spfli   type table of spfli,

Page 29: Programa ALV

      gt_sflight type table of sflight,      g_repid like sy-repid,      g_max type i value 100,      gs_layout   type lvc_s_layo,      gs_toolbar  type stb_button,      cont_on_100   type scrfname value 'BCALVC_TOOLBAR_D100_C1',      cont_on_200   type scrfname value 'BCALVC_TOOLBAR_D200_C1',      grid1  type ref to cl_gui_alv_grid,      grid2  type ref to cl_gui_alv_grid,      custom_container1 type ref to cl_gui_custom_container,      custom_container2 type ref to cl_gui_custom_container.

call screen 100.

*****************************************************************clases locales.*****************************************************************===============================================================

class lcl_event_receiver definition.

  public section.

    class-methods:    handle_toolbar        for event toolbar of cl_gui_alv_grid            importing e_object e_interactive,

    handle_menu_button        for event menu_button of cl_gui_alv_grid            importing e_object e_ucomm,

    handle_user_command        for event user_command of cl_gui_alv_grid            importing e_ucomm.

  private section.

endclass.

** lcl_event_receiver (Definition)*===============================================================

****************************************************************

Page 30: Programa ALV

* LOCAL CLASSES: Implementation*****************************************************************===============================================================* class lcl_event_receiver (Implementation)**class lcl_event_receiver implementation.

"*definir un elemento de la barra de herramientas de tipo 1 mediante el uso de" E_OBJECT evento paramenter. Recuerde que su código de función.  method handle_toolbar.

"añadir separador.    clear gs_toolbar.    move 3 to gs_toolbar-butn_type.    append gs_toolbar to e_object->mt_toolbar.

"Añadie un menú con el botón predeterminado.

    move 'TO_SFLIGHT' to gs_toolbar-function."Este código de función se evalúa en 'handle_menu_button'    move icon_detail to gs_toolbar-icon.    move 'Flights'(200) to gs_toolbar-quickinfo.    move 1 to gs_toolbar-butn_type.    move space to gs_toolbar-disabled.    append gs_toolbar to e_object->mt_toolbar.

  endmethod.*--------------------------------------------------------------------  method handle_menu_button."consultar su código de función y definir un"menú de la misma manera como un menú de contexto.   if e_ucomm = 'TO_SFLIGHT'.      call method e_object->add_function                  exporting fcode   = 'TO_SPFLI'                            text    = text-100. "Overview" Se elije una función por defecto y se define  el mismo código de función"que es utilizado para el menú.        call method e_object->add_function                  exporting fcode   = 'TO_SFLIGHT'                            text    = text-200.

    endif.  endmethod.*---------------------------------------------------------------------  method handle_user_command.

Page 31: Programa ALV

"Evaluación de comando de usuario para invocar el correspondiente...

    data: lt_rows type lvc_t_row.

   call method grid1->get_selected_rows             importing et_index_rows = lt_rows.    call method cl_gui_cfw=>flush.    if sy-subrc ne 0.    call function 'POPUP_TO_INFORM'           exporting                titel = g_repid                txt2  = sy-subrc                txt1  = 'Error in Flush'(500).    endif.

*Ir a la otra tabla    case e_ucomm.      when 'TO_SPFLI'.        leave to screen 100.      when 'TO_SFLIGHT'.        perform load_sflight_table tables lt_rows.        call screen 200.

    endcase.  endmethod.                           "handle_user_commandendclass.** lcl_event_receiver (Implementation)*===================================================================

*---------------------------------------------------------------------**       FORM EXIT_PROGRAM                                             **---------------------------------------------------------------------*form exit_program." instancia no se liberará hasta que el programa "sale de la pantalla principal.

  call method custom_container1->free.  if not custom_container2 is initial.    call method custom_container2->free.  endif.

  call method cl_gui_cfw=>flush.  if sy-subrc ne 0.    call function 'POPUP_TO_INFORM'         exporting              titel = g_repid              txt2  = sy-subrc

Page 32: Programa ALV

              txt1  = 'Error in Flush'(500).  endif.  leave program.endform.*&---------------------------------------------------------------------**&      Module  PBO_100  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module pbo_100 output.

  set pf-status 'MAIN100'.  set titlebar 'MAIN100'.  g_repid = sy-repid.  if custom_container1 is initial.

 perform select_table_spfli changing gt_spfli.

"Crear el contenedor.    create object custom_container1        exporting            container_name = cont_on_100.

"create una instancia del alv.    create object grid1           exporting i_parent = custom_container1.

"Barra de título para el control del grid.

    gs_layout-grid_title = text-100.    call method grid1->set_table_for_first_display         exporting i_structure_name = 'SPFLI'                   is_layout        = gs_layout         changing  it_outtab        = gt_spfli.

*********" Crear objeto para recibir eventos y vincularlos a handler métodos." Cuando el control ALV provoca el evento"El método correspondiente es llamado automáticamente para todas las instancias.

    set handler lcl_event_receiver=>handle_user_command                lcl_event_receiver=>handle_menu_button

Page 33: Programa ALV

                lcl_event_receiver=>handle_toolbar for all instances.*********

    call method grid1->set_toolbar_interactive.  endif.  call method cl_gui_control=>set_focus exporting control = grid1.

endmodule.                             " PBO_100  OUTPUT*&---------------------------------------------------------------------**&      Module  PAI_100  INPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module pai_100 input.

  case ok_code.    when 'EXIT'.      perform exit_program.

  endcase.  clear ok_code.endmodule.                             " PAI_100  INPUT*&---------------------------------------------------------------------**&      Module  PBO_200  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module pbo_200 output.

  set pf-status 'MAIN100'.  g_repid = sy-repid.  if custom_container2 is initial.

"Crear un control contenedor personalizado para nuestro control ALV:

    create object custom_container2        exporting            container_name = cont_on_200.

"Crear una instancia para el ALV.    create object grid2           exporting i_parent = custom_container2.

*"Establece una barra de títulos.*

Page 34: Programa ALV

    gs_layout-grid_title = text-200.    call method grid2->set_table_for_first_display         exporting i_structure_name = 'SFLIGHT'                   is_layout        = gs_layout         changing  it_outtab        = gt_sflight.

    call method grid2->set_toolbar_interactive.

  else."Con los nuevos datos se refresca la información del grid2.    call method grid2->refresh_table_display.  endif.  call method cl_gui_control=>set_focus exporting control = grid2.

endmodule.                             " PBO_200  OUTPUT*&---------------------------------------------------------------------**&      Module  PAI_200  INPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module pai_200 input.

  case ok_code.    when 'EXIT'.      perform exit_program.

  endcase.  clear ok_code.endmodule.                             " PAI_200  INPUT*&---------------------------------------------------------------------**&      Form  SELECT_TABLE_SFLIGHT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**      <--P_GT_SFLIGHT  text*----------------------------------------------------------------------*form select_table_sflight using    p_ls_spfli like line of gt_spfli                          changing p_gt_sflight like gt_sflight[].  select * from sflight into table p_gt_sflight up to g_max rows              where carrid = p_ls_spfli-carrid              and   connid = p_ls_spfli-connid.

endform.                               " SELECT_TABLE_SFLIGHT

*&---------------------------------------------------------------------**&      Form  SELECT_TABLE_SPFLI*&---------------------------------------------------------------------**       text

Page 35: Programa ALV

*----------------------------------------------------------------------**      <--P_it_spfli  text*----------------------------------------------------------------------*form select_table_spfli changing p_gt_spfli like gt_spfli[].  select * from spfli into table p_gt_spfli.endform.                               " SELECT_TABLE_SPFLI*&---------------------------------------------------------------------**&      Form  load_sflight_table*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**      -->P_LT_ROWS  text*----------------------------------------------------------------------*

form load_sflight_table tables p_et_index_rows structure lvc_s_row.

  data: ls_selected_line like lvc_s_row,        lf_row_index type lvc_index,        ls_spfli like line of gt_spfli.

  clear gt_sflight[].  read table p_et_index_rows index 1 into ls_selected_line.  if sy-subrc eq 0.    lf_row_index = ls_selected_line-index.

"Leer la información de la tabla interna it_sflight     read table gt_spfli index lf_row_index into ls_spfli.

"Seleccionar líneas correspondientes de la tabla spfli

    perform select_table_sflight using ls_spfli                               changing gt_sflight..  endif.

endform.

************************ ALV dinámico********************

*&---------------------------------------------------------------------**& Report  Z_ALV_4*&*&---------------------------------------------------------------------**&*&*&---------------------------------------------------------------------*

Page 36: Programa ALV

report  z_alv_4.

field-symbols:<f_tab1> type standard table.

parameters:p_tname type tabname16 obligatory, " DEFAULT 'MARA' ,p_rows(5) type c default '200'.*----------------------------------------------------------------------**       CLASS lcl_dynamic DEFINITION*----------------------------------------------------------------------***----------------------------------------------------------------------*class lcl_dynamic definition .  public section.    methods:    check_selection     exceptions invalid_table,    main     exceptions no_data_found,    display.

  private section.

    type-pools: abap.

    data: tab type ref to cl_abap_structdescr,          wa_tab type ref to cl_abap_structdescr,          comp_tab   type cl_abap_structdescr=>component_table,          i_tab type ref to cl_abap_tabledescr,          i_table type ref to data.endclass.                    "lcl_dynamic DEFINITION*----------------------------------------------------------------------**       CLASS lcl_dynamic IMPLEMENTATION*----------------------------------------------------------------------***----------------------------------------------------------------------*class lcl_dynamic implementation.  method check_selection.

    select count( * )      from dd02l      where tabname  = p_tname      and   as4local = 'A'      and   tabclass = 'TRANSP'.

    if sy-subrc <> 0.

Page 37: Programa ALV

      raise invalid_table.    endif.  endmethod.                    "check_selection

  method main.    tab ?= cl_abap_typedescr=>describe_by_name( p_tname ).

    comp_tab = tab->get_components( ).

    wa_tab  = cl_abap_structdescr=>create( comp_tab ).

    i_tab   = cl_abap_tabledescr=>create( wa_tab ).

    create data i_table type handle i_tab.

    assign i_table->* to <f_tab1>.

    if p_rows is initial.

      p_rows = '50000'.

    endif.

*Get data

    select * from (p_tname)    into table <f_tab1>    up to p_rows rows.    if sy-subrc <> 0.      raise no_data_found.    endif.

  endmethod.                    "main

  method display.

    set titlebar sy-title    of program sy-cprog    with 'Display table:' p_tname.

    data:

    l_gr_alv type ref to cl_salv_table,    l_gr_functions type ref to cl_salv_functions.

    try.

        call method cl_salv_table=>factory          importing

Page 38: Programa ALV

            r_salv_table = l_gr_alv          changing            t_table      = <f_tab1>.      catch cx_salv_msg .                               "#EC NO_HANDLER

    endtry.

    l_gr_functions = l_gr_alv->get_functions( ).    l_gr_functions->set_all( abap_true ).    l_gr_alv->display( ).

  endmethod.                    "display

endclass.                    "lcl_dynamic IMPLEMENTATION

at selection-screen.

  data oref_check type ref to lcl_dynamic.  create object oref_check.  call method oref_check->check_selection    exceptions      invalid_table = 1.

  if sy-subrc <> 0.    message e001(00) with    p_tname ' No es un tabla transparente'.  endif.

start-of-selection.  data oref_main type ref to lcl_dynamic.  create object oref_main.  call method oref_main->main    exceptions      no_data_found = 1.  if sy-subrc <> 0.    message i001(00) with 'No se encontraron datos'.    leave list-processing.  endif.

end-of-selection.

  call method oref_main->display.

*********************EXAMEN *******************

Page 39: Programa ALV

*&---------------------------------------------------------------------**& Report  Z_EXAMEN_MGB1*&*&---------------------------------------------------------------------**&*&*&---------------------------------------------------------------------*

report  z_alv9 message-id zrt02.

include z_examen_mgb1_top.include z_examen_mgb1_s01.include z_examen_mgb1_f01.include z_examen_mgb1_pai.include z_examen_mgb1_pbo.

start-of-selection.  perform f_initiar_alv.  perform f_build_fieldcatalog.*  PERFORM f_llena_la_tabla.  call function 'ZF_EXAMEN_MGB01'       exporting         i_carrid         = p_carrid       importing         e_zsflight       = it_sflight       exceptions         not_datafound    = 1       others             = 2.

 perform f_cal_precioxtcambio. perform f_display_alv.

end-of-selection.

call screen 0100.

*&---------------------------------------------------------------------**&  Include           Z_EXAMEN_MGB1_TOP*&---------------------------------------------------------------------*

tables sflight.

data: it_sflight  type standard table of sflight.data: wa_sflight  type sflight.

Page 40: Programa ALV

data: w_pxtipoc   type sflight-price.

data: fieldcatalog type slis_t_fieldcat_alv with header line.data: lt_fieldcat  type lvc_t_fcat,      wa_fieldcat  type lvc_s_fcat,      gd_tab_group type slis_t_sp_group_alv,      gd_layout    type lvc_s_layo,     "slis_layout_alv,      gd_repid     like sy-repid.

data: gv_container type ref to cl_gui_custom_container,      gv_grid      type ref to cl_gui_alv_grid,      gv_okcode    type sy-ucomm,      gs_fieldcat  type lvc_s_fcat,      gt_fieldcat_tree type lvc_t_fcat,      g_custom_container type ref to cl_gui_custom_container.

*&---------------------------------------------------------------------**&  Include           Z_EXAMEN_MGB1_S01*&---------------------------------------------------------------------*selection-screen begin of block ss02 with frame title text-002.   parameters     : p_carrid type s_carr_id.selection-screen end of block ss02.

*&---------------------------------------------------------------------**&  Include           Z_EXAMEN_MGB1_F01*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Form  F_INITIAR_ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_initiar_alv .  create object gv_container    exporting      container_name = 'GV_CONTAINER'.

  create object gv_grid    exporting      i_parent = gv_container.

Page 41: Programa ALV

endform.                    " F_INITIAR_ALV*&---------------------------------------------------------------------**&      Form  F_BUILD_FIELDCATALOG*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_build_fieldcatalog .call function 'LVC_FIELDCATALOG_MERGE'    exporting      i_structure_name       = 'SFLIGHT'    changing      ct_fieldcat            = lt_fieldcat    exceptions      inconsistent_interface = 1      program_error          = 2      others                 = 3.endform.*&---------------------------------------------------------------------**&      Form  F_LLENA_LA_TABLA*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_llena_la_tabla .select * from sflight into table it_sflight where carrid = p_carrid.endform.*&---------------------------------------------------------------------**&      Form  F_DISPLAY_ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_display_alv .call method gv_grid->set_table_for_first_display    exporting      i_default       = 'X'    changing      it_fieldcatalog = lt_fieldcat      it_outtab       = it_sflight.endform.

Page 42: Programa ALV

*&---------------------------------------------------------------------**&      Form  F_CAL_PRECIOXTCAMBIO*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_cal_precioxtcambio .loop at it_sflight into wa_sflight.    call function 'ZF_EXAMEN_MGB02'      exporting        i_price             = wa_sflight-price     importing       e_pxtipoc           =  wa_sflight-price     exceptions       not_datafound       = 1       others              = 2              .    if sy-subrc <> 0.* Implement suitable error handling here    endif.

modify it_sflight from wa_sflight.endloop.endform.                    " F_CAL_PRECIOXTCAMBIO

*&---------------------------------------------------------------------**&  Include           Z_EXAMEN_MGB1_PAI*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Module  STATUS_0100  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module status_0100 output.  set pf-status '0100'.*  SET TITLEBAR 'xxx'.

endmodule.            

Page 43: Programa ALV

*&---------------------------------------------------------------------**&  Include           Z_EXAMEN_MGB1_PBO*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Module  USER_COMMAND_0100  INPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module user_command_0100 input.case gv_okcode.    when 'ZBACK'.      set screen 0.      leave screen.    when  'ZFIN'.      call transaction 'SE80'.    when   'ZCANCEL'.      message i000 with 'Boton Cancel'.  endcase.endmodule.                 " USER_COMMAND_0100  INPUT

*

Orientado a objeots mara

include: z_alv_objetos_top,         z_alv_objetos_o01,         z_alv_objetos_i01,

Page 44: Programa ALV

         z_alv_objetos_f01.

start-of-selection.

  perform obtener_datos.

end-of-selection.

*&---------------------------------------------------------------------**&  Include           Z_ALV_OBJETOS_TOP*&---------------------------------------------------------------------*report  z_alv_objetos.*--------------------------------------------------------------------*****    ESTRUCTURAS                                                     *****--------------------------------------------------------------------*data: wa_fieldcat type lvc_s_fcat,      wa_layout   type lvc_s_layo .*--------------------------------------------------------------------*****  T A B L A S   I N T E R N A S                                     *****--------------------------------------------------------------------*data: it_fieldcat type lvc_t_fcat,      it_mara     type standard table of mara.

*--------------------------------------------------------------------*****  F I E L D S   S Y M B O L S                                       *****--------------------------------------------------------------------*data: ob_alvgrid    type ref to cl_gui_alv_grid,      ob_container  type ref to cl_gui_custom_container.*--------------------------------------------------------------------*****  V A R I A B L E S                                                 *****--------------------------------------------------------------------*data: w_container_name type scrfname value 'C_ALV'.

*&---------------------------------------------------------------------**&  Include           Z_ALV_OBJETOS_O01

Page 45: Programa ALV

*&---------------------------------------------------------------------*module status_0100 output.  set pf-status 'PF_100'.

endmodule.                 " STATUS_0100  OUTPUT*&---------------------------------------------------------------------**&      Module  ALV  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module alv output.

  if not it_mara[] is initial.    perform crea_alv.

    perform crea_fieldcat.

    perform crea_layout.

    perform muestra_alv.

  endif.

endmodule.                 " ALV  OUTPUT

*&---------------------------------------------------------------------**&  Include           Z_ALV_OBJETOS_I01*&---------------------------------------------------------------------*

module user_command_0100 input.

  case sy-ucomm.

    when 'BACK'.

      leave program.

  endcase.

endmodule.

Page 46: Programa ALV

*&---------------------------------------------------------------------**&  Include           Z_ALV_OBJETOS_F01*&---------------------------------------------------------------------*

form obtener_datos .

  select *    from mara    up to 15 rows    into table it_mara.    if sy-subrc eq 0.

    call screen 100.

  endif.

endform.                    " OBTENER_DATOS*&---------------------------------------------------------------------**&      Form  CREA_ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form crea_alv .

*  Crear container  if ob_container is initial .    create object ob_container      exporting        container_name              = w_container_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.

      create object ob_alvgrid        exporting          i_parent          = ob_container        exceptions          error_cntl_create = 1          error_cntl_init   = 2

Page 47: Programa ALV

          error_cntl_link   = 3          error_dp_create   = 4          others            = 5.      if sy-subrc <> 0.

        message 'Error al crear objeto ALV'           type 'E'.

      endif.

    endif.

  endif.

endform.                    " CREA_ALV*&---------------------------------------------------------------------**&      Form  CREA_FIELDCAT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form crea_fieldcat .

  call function 'LVC_FIELDCATALOG_MERGE'    exporting

      i_structure_name       = 'MARA'

    changing      ct_fieldcat            = it_fieldcat    exceptions      inconsistent_interface = 1      program_error          = 2      others                 = 3.  if sy-subrc <> 0.

    message 'Error al crear Fieldcat'       type 'E'.

  endif.

endform.                    " CREA_FIELDCAT*&---------------------------------------------------------------------**&      Form  CREA_LAYOUT*&---------------------------------------------------------------------**       text

Page 48: Programa ALV

*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form crea_layout .

  wa_layout-zebra = 'X' .  wa_layout-grid_title = 'ALV O.O' .

endform.                    " CREA_LAYOUT*&---------------------------------------------------------------------**&      Form  MUESTRA_ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form muestra_alv .

  call method ob_alvgrid->set_table_for_first_display    exporting      is_layout                     = wa_layout

    changing      it_outtab                     = it_mara[]      it_fieldcatalog               = it_fieldcat    exceptions      invalid_parameter_combination = 1      program_error                 = 2      too_many_lines                = 3      others                        = 4.  if sy-subrc ne 0.

    message 'Error Al Mostrar ALV'       type 'E'.

  endif.

endform.                    " MUESTRA_ALV

***********************Tree

Page 49: Programa ALV

************************+

report  z_alv_tree.*######################**  DECLARACION DE TYPES                                            **######################*types: begin of ty_spfli,       carrid type spfli-carrid,       connid type spfli-connid,       countryfr type spfli-countryfr,       cityfrom type spfli-cityfrom,       airpfrom type spfli-airpfrom,       countryto type spfli-countryto,       cityto type spfli-cityto,       end of ty_spfli.

types: begin of ty_header,       carrid type spfli-carrid,       end of ty_header.

*######################**  DECLARACION DE TABLAS INTERNAS                                 **######################*data: t_spfli type standard table of ty_spfli      with header line,      tab_tree type standard table of ty_spfli      with header line,      t_tree type standard table of ty_spfli      with header line,      t_header type standard table of ty_header      with header line.

*######################**  DECLARACION DE VARIABLES                                       **######################*data: g_alv_tree type ref to cl_gui_alv_tree,      l_hierarchy_header type treev_hhdr,      gs_fieldcat type lvc_s_fcat,      gt_fieldcat_tree type lvc_t_fcat,      g_custom_container type ref to cl_gui_custom_container.

Page 50: Programa ALV

*######################**  DECLARACION DE FIELD-SYMBOLS                                   **######################*field-symbols:  <header> like line of t_header,                <spfli> like line of t_spfli.

*######################**   SELECTION-SCREEN                                              **######################*selection-screen begin of screen 1001.selection-screen end of screen 1001.

*######################**   START-OF-SELECTION                                            **######################*start-of-selection.

  perform obtener_datos.

  if g_alv_tree is initial.

    call method cl_gui_cfw=>flush            exceptions cntl_system_error = 1                       cntl_error        = 2.

    perform init_tree.  endif.

  call screen 100.

*######################**       FORM init_tree                                            **######################*form init_tree.

  data: l_tree_container_name(30) type c.

  l_tree_container_name = 'TREE_CONTROL'(001).

  create object g_custom_container      exporting            container_name = l_tree_container_name      exceptions            cntl_error                  = 1            cntl_system_error           = 2            create_error                = 3            lifetime_error              = 4            lifetime_dynpro_dynpro_link = 5.

Page 51: Programa ALV

  create object g_alv_tree    exporting        parent              = g_custom_container        node_selection_mode = cl_gui_column_tree=>node_sel_mode_single*        ITEM_SELECTION      = "#        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.

  perform fill_catalog_tree.  perform build_hierarchy_header changing l_hierarchy_header.

  call method g_alv_tree->set_table_for_first_display       exporting                 is_hierarchy_header  = l_hierarchy_header       changing                 it_outtab        = t_tree[]                 it_fieldcatalog  = gt_fieldcat_tree.

  perform create_hierarchy.

endform.

*######################**   FORM FILL_CATALOG_TREE                                        **######################*form fill_catalog_tree.

  data: gs_fieldcat_add type lvc_s_fcat.

  clear gs_fieldcat.  gs_fieldcat-col_pos   = 1.  gs_fieldcat-reptext   = 'Flight'.  gs_fieldcat-scrtext_s = 'Flight'.  gs_fieldcat-fieldname = 'CONNID'.  gs_fieldcat-tabname = 'T_SPFLI'.  append gs_fieldcat to gt_fieldcat_tree.

  clear gs_fieldcat.  gs_fieldcat-col_pos   = 2.  gs_fieldcat-reptext   = 'Country'.  gs_fieldcat-scrtext_s = 'Country'.

Page 52: Programa ALV

  gs_fieldcat-fieldname = 'COUNTRYFR'.  gs_fieldcat-tabname = 'T_SPFLI'.  append gs_fieldcat to gt_fieldcat_tree.

  clear gs_fieldcat.  gs_fieldcat-col_pos   = 3.  gs_fieldcat-reptext   = 'Dep.City'.  gs_fieldcat-scrtext_s = 'Dep.City'.  gs_fieldcat-fieldname = 'CITYFROM'.  gs_fieldcat-tabname = 'T_SPFLI'.  gs_fieldcat-outputlen = '15'.  append gs_fieldcat to gt_fieldcat_tree.

  clear gs_fieldcat.  gs_fieldcat-col_pos   = 4.  gs_fieldcat-reptext   = 'Dep.Airp'.  gs_fieldcat-scrtext_s = 'Dep.Airp'.  gs_fieldcat-fieldname = 'AIRPFROM'.  gs_fieldcat-tabname = 'T_SPFLI'.  gs_fieldcat-outputlen = '20'.  append gs_fieldcat to gt_fieldcat_tree.

  clear gs_fieldcat.  gs_fieldcat-col_pos   = 5.  gs_fieldcat-reptext   = 'Country'.  gs_fieldcat-scrtext_s = 'Country'.  gs_fieldcat-fieldname = 'COUNTRYTO'.  gs_fieldcat-tabname = 'T_SPFLI'.  gs_fieldcat-outputlen = '15'.  append gs_fieldcat to gt_fieldcat_tree.

  clear gs_fieldcat.  gs_fieldcat-col_pos   = 6.  gs_fieldcat-reptext   = 'Arr.City'.  gs_fieldcat-scrtext_s = 'Arr.City'.  gs_fieldcat-fieldname = 'CITYTO'.  gs_fieldcat-tabname = 'T_SPFLI'.  gs_fieldcat-outputlen = '20'.  append gs_fieldcat to gt_fieldcat_tree.

endform.

*#######################**       FORM build_hierarchy_header                                   **#######################*form build_hierarchy_header changing                               p_hierarchy_header type treev_hhdr.

  clear p_hierarchy_header.

Page 53: Programa ALV

  p_hierarchy_header-heading = 'Airline carrier'(300).  p_hierarchy_header-width = 18.  p_hierarchy_header-width_pix = ' '.

endform.

*#######################**       FORM create_hierarchy                                         **#######################*form create_hierarchy.

  data: l_root_key type lvc_nkey,        l_next_key type lvc_nkey,        l_last_key type lvc_nkey,        header type string,        w_menge_text(13) type c.

  clear l_root_key.

  loop at t_header assigning <header>.    clear l_root_key.    clear l_next_key.    perform add_node using <header>-carrid l_root_key                     changing l_next_key.    loop at t_spfli assigning <spfli>    where carrid eq <header>-carrid.

      move-corresponding  <spfli> to tab_tree.

      perform add_leaf using tab_tree l_next_key                       changing l_last_key.    endloop.  endloop.

  call method g_alv_tree->frontend_update.

endform.

*#######################**       FORM ADD_NODE                                                 **#######################*form add_node using l_name l_root_key              changing l_next_key.

  data: l_node_text type lvc_value,        ls_tree type ty_spfli.

  l_node_text =  l_name.  call method g_alv_tree->add_node

Page 54: Programa ALV

    exporting          i_relat_node_key = l_root_key          i_relationship   = cl_gui_column_tree=>relat_last_child          i_node_text      = l_node_text          is_outtab_line   = ls_tree    importing          e_new_node_key   = l_next_key.

endform.

*#######################**       FORM ADD_LEAF                                                 **#######################*form add_leaf using l_tree type ty_spfli                    l_next_key              changing l_last_key.

  call method g_alv_tree->add_node    exporting          i_relat_node_key = l_next_key          i_relationship   = cl_gui_column_tree=>relat_last_child          is_outtab_line   = tab_tree       importing          e_new_node_key = l_last_key.

endform.

*#######################**       FORM OBTENER_DATOS                                            **#######################*form obtener_datos.

  select carrid connid countryfr cityfrom         airpfrom countryto cityto  into table t_spfli  from spfli.

  if sy-subrc eq 0.    loop at t_spfli assigning <spfli>.      move <spfli>-carrid to t_header-carrid.      append t_header.    endloop.

    sort t_header.    delete adjacent duplicates from t_header.

  endif.

endform.

Page 55: Programa ALV

Lorena

*&---------------------------------------------------------------------**& Report  ZLSG_EJ1ALVOO*&*&---------------------------------------------------------------------**& Consultor: Lorena Silva (NOUSFERA).*& Fecha:    2013.12.27*& Objetivo: Mostrar en un listado ALV, una cosulta de vuelos.*&           de tratarse de una persona de la tercera edad aplicarle*&           el 20% descuento y mostrar el ahorro.*&---------------------------------------------------------------------*

report  zlsg_ej1alvoo.

include zlsg_ej1alvoo_top.include zlsg_ej1alvoo_s01.include zlsg_ej1alvoo_f01.

start-of-selection.  perform fp_procesos.

*********Top************+

Page 56: Programa ALV

*&---------------------------------------------------------------------**&  Include           ZLSG_EJ1ALVOO_TOP*&---------------------------------------------------------------------*

" Tipos de datostypes:begin of ty_sflight,carrid   type  sflight-carrid,connid   type  sflight-connid,fldate   type  sflight-fldate,price    type  sflight-price,currency type  sflight-currency,end of ty_sflight,tt_sflight type standard table of ty_sflight,begin of ty_scarr, carrid type scarr-carrid, carrname type scarr-carrname,end of ty_scarr,tt_scarr type standard table of ty_scarr,

begin of ty_spfli,  carrid      type  spfli-carrid,  connid      type  spfli-connid,  countryfr   type  spfli-countryfr,  cityfrom    type  spfli-cityfrom,  airpfrom    type  spfli-airpfrom,  countryto   type  spfli-countryto,  cityto      type  spfli-cityto,  airpto      type  spfli-airpto,  fltime      type  spfli-fltime,  deptime     type  spfli-deptime,  arrtime     type  spfli-arrtime,end of ty_spfli,tt_spfli type standard table of ty_spfli,

begin of ty_salida,carrid   type  sflight-carrid,connid   type  sflight-connid,carrname type  scarr-carrname,fldate   type  sflight-fldate,countryfr type  spfli-countryfr,cityfrom  type  spfli-cityfrom,airpfrom  type  spfli-airpfrom,countryto type  spfli-countryto,cityto    type  spfli-cityto,airpto    type  spfli-airpto,fltime    type  spfli-fltime,deptime   type  spfli-deptime,arrtime   type  spfli-arrtime,

Page 57: Programa ALV

price    type  sflight-price,currency type  sflight-currency, ahorr   type  p length 6 decimals 3,end of ty_salida,tt_salida type standard table of ty_salida.

" Declaración de tablas internas y work areasdata:it_flight type standard table of ty_sflight,wa_flight type ty_sflight,it_scarr type standard table of ty_scarr,wa_scarr type ty_scarr,it_spfli type standard table of ty_spfli,wa_spfli type ty_spfli,it_salida type standard table of ty_salida,wa_salida type ty_salida.

" Declaración de variables globales del reportdata: gv_ok type c, gv_sug type c.

" Declaración de constantesconstants:c_x     type c value 'X',c_a     type c value 'A',c_0     type i value '0',c_60(2) type c value '60',c_80    type f value '0.80'.

" Variables necesarias para la creación de ALV...data: it_fieldcat   type lvc_t_fcat,      wa_fieldcat   type lvc_s_fcat,      wa_layout     type lvc_s_layo,      it_sort_alv   type lvc_t_sort,      ob_container  type ref to cl_gui_custom_container,      ob_alv_grid   type ref to cl_gui_alv_grid.

***************S01*******

selection-screen begin of block b1 with frame title text-001.parameters: p_nmbr    type char50,            p_edad    type i.selection-screen end of block b1.

selection-screen begin of block b2 with frame title text-002.

Page 58: Programa ALV

parameters: p_line     type  sflight-carrid,            p_fecha    type  sy-datum.selection-screen end of block b2.

*****************F01************

*&---------------------------------------------------------------------**&  Include           ZLSG_EJ1ALVOO_F01*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Form  FP_PROCESOS*&---------------------------------------------------------------------**  Éste subrutina encierra todos los procesos del programa*  ZLSG_EJ1ALVOO*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_procesos .  clear: gv_ok, gv_sug.  " Continuar solo si se tienen los datos del cliente...  if p_nmbr is not initial " nombre  and p_edad is not initial. " edad    " Lee los datos de tabla SFLIGHT    perform fp_lee_sflight changing it_flight                                    gv_ok                                    gv_sug.    if it_flight[] is not initial.      perform fp_lee_scarr    using it_flight                           changing it_scarr.      perform fp_lee_spfli using it_flight                        changing it_spfli.    endif.    " Si tengo datos del vuelo, continuo...    if gv_ok eq c_x.      " Se calcula el precio y el ahorro, dependiendo edad del cliente.      perform fp_filtro_cliente using    it_flight                                changing it_salida                                         gv_ok.

      " Si se tiene éxito...      if gv_ok eq c_x.        " Se imprime información en pantalla...*        PERFORM fp_mostrar USING it_salida*                                 gv_sug.

        " Llamar pantalla que mostrará ALV Grid        call screen 0100.

Page 59: Programa ALV

      endif.    endif.

  else.    " implementar mensaje de error  endif.endform.                    " FP_PROCESOS

*&---------------------------------------------------------------------**&      Form  FP_LEE_SLIGHT*&---------------------------------------------------------------------**   Lee los vuelos correspondientes en tabla transparente   SFLIGHT.*----------------------------------------------------------------------**      -->P_P_NMBR  text*      -->P_P_EDAD  text*      <--P_IT_FLIGHT  text*      <--P_GV_OK  text*----------------------------------------------------------------------*form fp_lee_sflight changing pt_flight type tt_sflight                             pv_ok type c                             pv_sug type c.  " Limpio mi tabla a alimentar...  refresh pt_flight[].  " limpio mi bandera de "éxito"  clear pv_ok.* Traigo los datos referentes a la aerolínea electa por el cliente  select carrid      connid      fldate      price      currencyfrom sflightinto table pt_flightwhere carrid eq p_line. " ID de Aerolínea*     AND fldate EQ p_fecha. " Fecha del vuelo

  " Si se tienen datos...  if pt_flight[] is not initial.    " filtrar por fecha    perform fp_fecha changing pt_flight[].    " Si se siguen teniendo datos, indico que tuve éxito    " en mi lectura...    if pt_flight[] is not initial.      pv_ok = c_x. " Se prende bandera de éxito...

    else. " Sino, se traen sugerencias de otras aerolíneas      " Limpio mi tabla interna de vuelos...      refresh pt_flight[].

Page 60: Programa ALV

      " Hago mi lectura sin where condition, para traer la      " información de todas las aerolíneas      select carrid             connid             fldate             price             currency        from sflight        into table pt_flight.

      if pt_flight[] is not initial.        " Filtro por fecha..        perform fp_fecha changing pt_flight[].        " Si se tienen datos...        if pt_flight[] is not initial.          pv_sug = c_x. " Indico que devolveré sugerencias...          pv_ok = c_x. " Se tiene éxito ..        endif.      endif.    endif.  endif.

endform.                    " FP_LEE_SLIGHT*&---------------------------------------------------------------------**&      Form  FP_FILTRO_CLIENTE*&---------------------------------------------------------------------**    Dependiendo el cliente se lleva a cabo el calculo del descuento*    y el ahorro.*----------------------------------------------------------------------**      -->P_IT_FLIGHT  text*      <--P_GV_OK  text*----------------------------------------------------------------------*form fp_filtro_cliente  using    pt_flight type tt_sflight                        changing pt_salida type tt_salida                                 pv_ok type c.

  " Declaración de variables locales...  data lv_3era type c.  " procesos ...  if p_edad ge c_60.

    lv_3era = c_x. " indico que es de la tercera edad.    perform fp_salida using  pt_flight                             lv_3era                    changing pt_salida.    if pt_salida[] is not initial.      " Indico que si se tienen datos en tabla de salida      pv_ok = c_x.    endif.

Page 61: Programa ALV

  elseif p_edad lt c_60.

    clear lv_3era. " indico que no pertenece a la 3era edad.    perform fp_salida using pt_flight                            lv_3era                   changing pt_salida.    if pt_salida[] is not initial.      " Indico que si se tienen datos en tabla de salida      pv_ok = c_x.    endif.  endif.endform.                    " FP_FILTRO_CLIENTE*&---------------------------------------------------------------------**&      Form  FP_DESC*&---------------------------------------------------------------------**  Peform que permite aplicar el 20 % de descuento al precio, en caso*  de tratarse de  un cliente  de la 3era edad.*----------------------------------------------------------------------**      -->PT_FLIGHT  Tabla con datos del vuelo(s)*      <--PT_SALIDA  Tabla de salida*----------------------------------------------------------------------*form fp_salida  using    pt_flight type tt_sflight                         pv_3era  type c              changing   pt_salida type tt_salida.  "Declaración de variables locales, exclusivas del perform  data: lv_desc type f, "Numerico con longitud de 8        lv_ahrr type f.

  " Limpio mi tabla interna de salida...  refresh pt_salida[].  if pv_3era is not initial.    " Se realiza un ciclo a tabla interna,  de datos del vuelo...    loop at pt_flight into wa_flight.      lv_desc = wa_flight-price *  c_80. " se aplica el 20% de descuento      lv_ahrr = wa_flight-price - lv_desc. " se calcúla el ahorro      read table it_scarr into wa_scarr with key carrid = wa_flight-carrid.      if sy-subrc eq 0.        wa_salida-carrname = wa_scarr-carrname. " Nonbre de aerolínea      endif.      " mapeo de datos...      wa_salida-carrid   = wa_flight-carrid.      wa_salida-connid   = wa_flight-connid.      wa_salida-fldate   = wa_flight-fldate.      wa_salida-price    = lv_desc.      wa_salida-currency = wa_flight-currency.      wa_salida-ahorr    = lv_ahrr.      "Agrego registro en tabla interna de salida

Page 62: Programa ALV

      append wa_salida to pt_salida.      "Limpio mis workareas para evitar llevar basura a la siguiente...      clear: wa_salida, wa_flight, wa_scarr.    endloop.  elseif pv_3era ne c_x.    loop at pt_flight into wa_flight.      read table it_scarr into wa_scarr with key carrid = wa_flight-carrid.      if sy-subrc eq 0.        wa_salida-carrname = wa_scarr-carrname. " Nonbre de aerolínea      endif.

      " mapeo de datos...      wa_salida-carrid   = wa_flight-carrid.      wa_salida-connid   = wa_flight-connid.      wa_salida-fldate   = wa_flight-fldate.      wa_salida-price    = wa_flight-price.      wa_salida-currency = wa_flight-currency.      wa_salida-ahorr    = c_0. "No hay ahorro..      "Agrego registro en tabla interna de salida      append wa_salida to pt_salida.      "Limpio mis workareas para evitar llevar basura a la siguiente...      clear: wa_salida, wa_flight.    endloop.

  endif.endform.                    " FP_DESC" FP_IT_SALIDA*&---------------------------------------------------------------------**&      Form  FP_FECHA*&---------------------------------------------------------------------**    Se descartan los vuelos que no coincidan con la fecha electa*    por el cliente.*----------------------------------------------------------------------**      -->P_PT_FLIGHT[]  text*----------------------------------------------------------------------*form fp_fecha  changing pt_flight type tt_sflight.  data: lt_tmp type standard table of ty_sflight,        lw_tmp type ty_sflight.

  clear wa_flight.  " Siempre antes de un DELETE ADJACENT DUPLICATES se debe ordenar  " la información  " En éste caso se ordena por ID de Aerolínea y Fecha de vuelo...  sort pt_flight by carrid fldate.  " Se elimina de la tabla la posible información duplicada  delete adjacent duplicates from pt_flight comparing carrid                                                      fldate.  " Si nuestra tabla aún tiene datos ...

Page 63: Programa ALV

  if pt_flight[] is not initial.    " La asigno a una tabla interna local, para trabajar sobre ésta...    lt_tmp[] = pt_flight[].

    loop at pt_flight into wa_flight.      " Si la fecha no coincide con la fecha deseada ...      if wa_flight-fldate ne p_fecha.        "Elimino el registro...        delete lt_tmp where carrid = wa_flight-carrid                        and connid = wa_flight-connid                        and fldate = wa_flight-fldate.      endif.    endloop.

  endif.  " Limpio mi tabla interna de vuelos, ya que contendrá lo que se  " logró filtrar...  refresh pt_flight[].

  " Si la tabla temporal tiene datos quiere decir que si hay  " aerolíneas ofreciendo vuelos con la fecha deseada por el cliente...  if lt_tmp[] is not initial.    " Asigno los vuelos que si cumplen de nuevo en mi tabla interna    " de  vuelos disponibles...    pt_flight[] = lt_tmp[].  endif.endform.                    " FP_FECHA*&---------------------------------------------------------------------**&      Form  FP_MOSTRAR*&---------------------------------------------------------------------**  Impresión en pantalla, de la información correspondiente, por medio*   de sentencia WRITE.*----------------------------------------------------------------------**      -->P_IT_SALIDA  text*----------------------------------------------------------------------*form fp_mostrar  using    pt_salida type tt_salida                          pv_sug  type c.  " Si no fue necesario traer información de sugerencias...  if pv_sug is initial.    " Muestro datos del cliente...    write:/ 'Cliente', ':', p_nmbr.    write:/'Edad', ':', p_edad.    " Hago un salto de línea...    write: /.    " Escribo encabezados...    write:/ 'Aerolínea', '|', 'Vuelo','|','  Fecha   ','|',            '     Precio     ','    |','Moneda','|','    Ahorro   ',            '|'.    " Escribo el contenido de mi tabla interna de salida...

Page 64: Programa ALV

    loop at pt_salida into wa_salida.      write : / wa_salida-carrid,'      |',wa_salida-connid,' |',              wa_salida-fldate,'|', wa_salida-price,'| ',              wa_salida-currency,'|', wa_salida-ahorr, '|'.      " Limpio mi work area para no traer datos basura en la siguiente      " vuelta.      clear wa_salida.

    endloop.    " Si se traen sugerencias, indicar que no se encontró lo que se buscaba...  elseif pv_sug eq c_x.    write:/ 'Cliente', ':', p_nmbr.    write:/'Edad', ':', p_edad.    write: /.    write:'SIN DISPONIBILIDAD en aerolínea electa. Sugerencias de vuelo:'.    write: /.    write:/ 'Aerolínea', '|', 'Vuelo','|','  Fecha   ','|',            '     Precio     ','    |','Moneda','|','    Ahorro   ',            '|'.    loop at pt_salida into wa_salida.      write : / wa_salida-carrid,'      |',wa_salida-connid,' |',              wa_salida-fldate,'|', wa_salida-price,'| ',              wa_salida-currency,'|', wa_salida-ahorr, '|'.      " Limpio mi work area para no traer datos basura en la siguiente      " vuelta.      clear wa_salida.

    endloop.

  endif.

endform.                    " FP_MOSTRAR*&---------------------------------------------------------------------**&      Module  STATUS_0100  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module status_0100 output.  set pf-status '0100'.*  SET TITLEBAR 'xxx'.

endmodule.                 " STATUS_0100  OUTPUT*&---------------------------------------------------------------------**&      Module  MOSTRAR_ALV  OUTPUT*&---------------------------------------------------------------------**   Se muestra en pantalla los vuelos disponibles según las necesidades*   del cliente, por medio de listado ALV.

Page 65: Programa ALV

*----------------------------------------------------------------------*module mostrar_alv output.  if ob_container is not bound.* Crea el custom container control para el control ALV    create object ob_container      exporting        container_name              = 'CC_ALV1'      exceptions        cntl_error                  = 1        cntl_system_error           = 2        create_error                = 3        lifetime_error              = 4        lifetime_dynpro_dynpro_link = 5.* Crea una instancia del control ALV    create object ob_alv_grid      exporting        i_parent = ob_container.* Layout ALV    perform f_layout_alv.* Carga el Catálogo de campos ALV    perform: f_fieldcat_alv.  endif.* Ejecuto el ALV  call method ob_alv_grid->set_table_for_first_display    exporting      i_save          = c_a      is_layout       = wa_layout*     is_variant      = wa_variant    changing      it_outtab       = it_salida      it_fieldcatalog = it_fieldcat.*      it_sort         = gt_sort_alv.*  CALL METHOD cl_gui_control=>set_focus*    EXPORTING*      control = ob_alv_grid.endmodule.                 " MOSTRAR_ALV  OUTPUT*&---------------------------------------------------------------------**&      Module  USER_COMMAND_0100  INPUT*&---------------------------------------------------------------------**   Indica las acciones a realizar con los comandos EXIT, CANCEL Y BACK*   del Status GUI correspondiente a Dynpro 0100.*----------------------------------------------------------------------*module user_command_0100 input.  if     sy-ucomm eq 'EXIT'      or sy-ucomm eq 'CANCEL'      or sy-ucomm eq 'BACK'.    set screen 0.    leave screen.  endif.

Page 66: Programa ALV

endmodule.                 " USER_COMMAND_0100  INPUT*&---------------------------------------------------------------------**&      Form  F_LAYOUT_ALV*&---------------------------------------------------------------------**  Indica que "formato" que manejará mi ALV Grid.*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_layout_alv .  wa_layout-zebra = c_x.  wa_layout-cwidth_opt = c_x.  wa_layout-frontend = c_x.endform.                    " F_LAYOUT_ALV*&---------------------------------------------------------------------**&      Form  F_FIELDCAT_ALV*&---------------------------------------------------------------------**  Se alimenta tabla interna de "catálogo de campos" para nuestro ALV.*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_fieldcat_alv .  " se limpian las variables con las que se trabajarán  refresh it_fieldcat.  clear wa_fieldcat.  " Se comienza a alimentar nuestro "catálogo de campos" para el ALV...  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'CARRID'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'CARRID'.  wa_fieldcat-col_opt    = c_x.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'CONNID'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'CONNID'.  wa_fieldcat-col_opt    = c_x.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'CARRNAME'.  wa_fieldcat-ref_table  = 'SCARR'.  wa_fieldcat-ref_field  = 'CARRNAME'.  wa_fieldcat-col_opt    = c_x.  append wa_fieldcat to it_fieldcat.

Page 67: Programa ALV

  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'FLDATE'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'FLDATE'.  wa_fieldcat-col_opt    = c_x.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'PRICE'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'PRICE'.  wa_fieldcat-col_opt    = c_x.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'CURRENCY'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'CURRENCY'.  wa_fieldcat-col_opt    = c_x.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'AHORR'.*  wa_fieldcat-ref_table  = 'SFLIGHT'.*  wa_fieldcat-ref_field  = 'CONNID'.  wa_fieldcat-scrtext_l  = 'Ahorro'.  wa_fieldcat-scrtext_m  = 'Ahorro'.  wa_fieldcat-scrtext_s  = 'Ahorro'.  wa_fieldcat-col_opt    = c_x.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

endform.                    " F_FIELDCAT_ALV*&---------------------------------------------------------------------**&      Form  FP_LEE_SCARR*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**      <--P_IT_SCARR  text*      <--P_GV_OK  text*----------------------------------------------------------------------*form fp_lee_scarr     using pt_flight type tt_sflight                   changing pt_scarr  type tt_scarr.

Page 68: Programa ALV

  refresh pt_scarr[].

  select carrid         carrname   from scarr   into table pt_scarr   for all entries in pt_flight   where carrid = pt_flight-carrid.

endform.                    " FP_LEE_SCARR*&---------------------------------------------------------------------**&      Form  FP_LEE_SPFLI*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**      -->P_IT_FLIGHT  text*      <--P_IT_SPFLI  text*----------------------------------------------------------------------*form fp_lee_spfli  using    pt_flight type tt_sflight                   changing pt_spfli  type tt_spfli.

  refresh pt_spfli[].

  select carrid         connid         countryfr         cityfrom         airpfrom         countryto         cityto         airpto         fltime         deptime         arrtime    from spfli    into table pt_spfli    for all entries in pt_flight    where carrid eq pt_flight-carrid      and connid eq pt_flight-connid.

endform.                    " FP_LEE_SPFLI

Page 69: Programa ALV

---------------------------------------------------------------*

include znsfer_alv_top.    "  DECLARAMOS Datos Globales.include znsfer_alv_s01.    " Parametrosinclude znsfer_alv_f01.    " FORM-Routines

initialization.

start-of-selection.

perform fp_leer_tablas.perform fp_armar_datos.perform fp_obtener_carrname.perform fp_validaciones."PERFORM FP_IMPRIME_DATOS."IMPRIME DATOS CON WRITEperform fp_alv. "imprime datos con ALV DE FUNCIONES.

*&---------------------------------------------------------------------**& Include ZNSFER_ALV_TOP                                    Report ZNSFER_ALV*&*&---------------------------------------------------------------------*

report   znsfer_alv.*Declaramos las tablas que vamos a leer.tables:  sflight,  scarr." Declaramos los tipos de datostypes:      begin of ty_str_sflight,        carrid   type sflight-carrid,        connid  type sflight-connid,        fldate   type sflight-fldate,        price    type sflight-price,        currency type sflight-currency,        seatsmax type sflight-seatsmax,        seatsocc type sflight-seatsocc,        carrname type scarr-carrname,        ahorro    type sflight-price,        end of ty_str_sflight,        ty_st_sflight type standard table of ty_str_sflight,

      begin of ty_str_scarr,        carrid   type scarr-carrid,        carrname type scarr-carrname,

Page 70: Programa ALV

      end of ty_str_scarr,      ty_st_scarr type standard table of ty_str_scarr.

      constants gv_oper type sflight-price value '0.20'.

"Declaramos nuestras Tablas Internas y nuestras W.areas.

data:     it_sflight      type ty_st_sflight,     it_sflight2     type ty_st_sflight,     it_sflight3     type ty_st_sflight,     wa_sflight      type ty_str_sflight,     it_scarr        type ty_st_scarr,     gv_resultado    type sflight-price,     gv_resultado1   type sflight-price,     wa_scarr        type ty_str_scarr.

" Declaramos las Variables que necesitamos para la creación de ALV DE FUNCIONES.data: it_fieldcat  type slis_t_fieldcat_alv,      wa_fieldcat  type slis_fieldcat_alv,      header_text(20) type c.

*&---------------------------------------------------------------------**&  Include           ZNSFER_ALV_S01*&---------------------------------------------------------------------*

" Parametros que vamos a utilizarparameters:           pa_nom(10)  type c,           pa_edad(2) type n,           pa_id   type sflight-carrid.

select-options              s_fldate for sflight-fldate.

Page 71: Programa ALV

*&---------------------------------------------------------------------**&  Include           ZNSFER_ALV_F01*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Form  FP_LEER_TABLAS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------**En este perfor vamos a hacer la lectura de las tablas que utilizaremos* a la B.D y las colocaremos en nuestras tablas internas para trabajar.form fp_leer_tablas .

  refresh: it_sflight[],         it_scarr[].  select carrid         connid         fldate         price         currency         seatsmax         seatsocc

  from sflight  into table it_sflight  where carrid = pa_id and fldate in s_fldate.  if  sy-subrc = 0.    select carrid           carrname    from scarr    into table it_scarr    for all entries in it_sflight    where carrid = it_sflight-carrid.

    else.perform fp_sugerencia.

    message 'NO HAY VUELOS DISPONIBRES EN LA AEROLINEA SELECCIONADA,LE DAMOS LAS SIGUIENTES SUJERENCIAS:' type 'I'.

endif.

Page 72: Programa ALV

endform.                    " FP_LEER_TABLAS*&---------------------------------------------------------------------**&      Form  FP_ARMAR_DATOS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_armar_datos .

  if  it_scarr[] is not initial.    loop at it_sflight into wa_sflight.      if wa_sflight-fldate in s_fldate.        append wa_sflight to it_sflight2.      endif.    endloop.  endif.

endform.                    " FP_ARMAR_DATOS*&---------------------------------------------------------------------**&      Form  FP_OBTENER_CARRNAME*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_obtener_carrname .

  data:      lv_tabix type sy-tabix.

  loop at it_sflight2 into wa_sflight.    lv_tabix = sy-tabix.    read table it_scarr into wa_scarr               with key carrid = wa_sflight-carrid               binary search.    if sy-subrc = 0.      wa_sflight-carrname = wa_scarr-carrname.      modify it_sflight2 from wa_sflight index lv_tabix                         transporting carrname.    endif.  endloop.

Page 73: Programa ALV

endform.                    " FP_OBTENER_CARRNAME*&---------------------------------------------------------------------**&      Form  FP_VALIDACIONES*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_validaciones .

  loop at it_sflight2 into wa_sflight.         if  pa_edad >= 60.        wa_sflight-ahorro = wa_sflight-price *  gv_oper."- gv_resultado1.        wa_sflight-price = wa_sflight-price - wa_sflight-ahorro.        modify it_sflight2  from wa_sflight.

      endif.

endloop.

endform.                    " FP_VALIDACIONES*&---------------------------------------------------------------------**&      Form  FP_IMPRIME_DATOS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_imprime_datos .

  write:/ 'NOMBRE', ':', pa_nom.  write:/ 'EDAD', ':', pa_edad.  write:/ 'AEROLINEA', ':', pa_id.  write:/  .  write:/ ' CARRID   ', '|','CONNID ','   |', 'FLDATE','    |','CURRENCY','|',   'SEATSMAX','  |','SEATSOCC','    |',          'PRICE','               |'.

  loop at  it_sflight2 into wa_sflight.

    write: /   wa_sflight-carrid,'       |', wa_sflight-connid, '      |',wa_sflight-fldate, '|',    wa_sflight-currency, '   |', wa_sflight-seatsmax, '|', wa_sflight-seatsocc, '  |',wa_sflight-price,'|'.

  endloop.

Page 74: Programa ALV

  write:/.  write:/'Precio con el 20% de Descuento', ':', gv_resultado.  write:/'Su ahorro fue de', ':', gv_resultado1.

endform.                    " FP_IMPRIME_DATOS*&---------------------------------------------------------------------**&      Form  FP_ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_alv .

*Armamos nuestro catalogo de campos

 " se limpian las variables con las que se trabajarán

  refresh it_fieldcat.  clear wa_fieldcat.

  wa_fieldcat-fieldname  = 'CARRNAME'.  wa_fieldcat-seltext_m  = 'AEROLINEA.'.  wa_fieldcat-emphasize  = 'C600'.  wa_fieldcat-tabname    = 'IT_SFLIGHT2'.

  append wa_fieldcat to it_fieldcat.  wa_fieldcat-fieldname  = 'CONNID'.    " Nombre del campo de referencia  wa_fieldcat-seltext_m  = 'NO. VUELO'.   " Nombre de nuestro campo  wa_fieldcat-tabname    = 'IT_SFLIGHT2'. "Nombre de nuestra tabla interna

  append wa_fieldcat to it_fieldcat.

  wa_fieldcat-fieldname  = 'FLDATE'.  wa_fieldcat-seltext_m  = 'FLDATE'.  wa_fieldcat-tabname = 'IT_SFLIGHT'.  wa_fieldcat-emphasize = 'C101'.  append wa_fieldcat to it_fieldcat.

  wa_fieldcat-fieldname  = 'PRICE'.  wa_fieldcat-seltext_m  = 'PRICE'.  wa_fieldcat-tabname = 'IT_SFLIGHT2'.

Page 75: Programa ALV

  wa_fieldcat-emphasize = 'C611'.  append wa_fieldcat to it_fieldcat.

  wa_fieldcat-tabname    = 'IT_SFLIGHT2'.  wa_fieldcat-fieldname  = 'AHORRO'.  wa_fieldcat-seltext_m  = 'AHORRO'.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  call function 'REUSE_ALV_GRID_DISPLAY'    exporting      it_fieldcat   = it_fieldcat    tables      t_outtab      = it_sflight2    exceptions      program_error = 1      others        = 2.

endform.                    " FP_ALV*&---------------------------------------------------------------------**&      Form  FP_SUGERENCIA*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_sugerencia .

  refresh: it_sflight[],         it_scarr[].  select carrid         connid         fldate         price         currency         seatsmax         seatsocc

  from sflight  into table it_sflight  where  fldate in s_fldate.  if  sy-subrc = 0.    select carrid           carrname    from scarr    into table it_scarr    for all entries in it_sflight    where carrid = it_sflight-carrid.

Page 76: Programa ALV

      endif.

endform.                    " FP_SUGERENCIA

Orientado a objetos

include znsfer_alvo_top. " DECLARAMOS Datos Globales.include znsfer_alvo_s01. " Parametrosinclude znsfer_alvo_f01.  " FORM-Routines

start-of-selection.

perform fp_leer_tablas.perform fp_armar_datos.perform fp_obtener_carrname.perform fp_validaciones."PERFORM FP_IMPRIME_DATOS."IMPRIME DATOS CON WRITEcall screen 0180. " Llamar a la dympro para que imprima datos

*&---------------------------------------------------------------------*

report   znsfer_alvo.*Declaramos las tablas que vamos a leer.tables:  sflight,  scarr,  spfli.

" Declaramos los tipos de datostypes:      begin of ty_str_sflight,        carrid   type sflight-carrid,        connid   type sflight-connid,        fldate   type sflight-fldate,        price    type sflight-price,        currency type sflight-currency,        carrname type scarr-carrname,        end of ty_str_sflight,        ty_st_sflight type standard table of ty_str_sflight,

Page 77: Programa ALV

      begin of ty_str_scarr,        carrid   type scarr-carrid,        carrname type scarr-carrname,      end of ty_str_scarr,      ty_st_scarr type standard table of ty_str_scarr,

      begin of ty_str_spfli,        carrid    type spfli-carrid,        connid    type spfli-connid,        countryfr type spfli-countryfr,        cityto    type spfli-cityto,        airpto    type spfli-airpto,        fltime    type spfli-fltime,        deptime   type spfli-deptime,        arrtime   type spfli-arrtime,        carrname  type scarr-carrname,        end of ty_str_spfli,        ty_st_spfli type standard table of ty_str_spfli,

        begin of ty_str_salida,        carrid   type sflight-carrid,        connid   type sflight-connid,        fldate   type sflight-fldate,        price    type sflight-price,        currency type sflight-currency,        carrname type scarr-carrname,        countryfr type spfli-countryfr,        cityto    type spfli-cityto,        airpto    type spfli-airpto,        fltime    type spfli-fltime,        deptime   type spfli-deptime,        arrtime   type spfli-arrtime,        ahorro    type sflight-price,        end of ty_str_salida.

        data:               it_salida type standard table of ty_str_salida,               wa_salida type ty_str_salida,               gv_indi type c.

"Declaramos nuestras Tablas Internas y nuestras W.areas.

data:     it_sflight      type ty_st_sflight,     it_sflight2     type ty_st_sflight,     wa_sflight      type ty_str_sflight,

Page 78: Programa ALV

     it_scarr        type ty_st_scarr,     gv_resultado    type sflight-price,     gv_resultado1   type sflight-price,     wa_scarr        type ty_str_scarr,     it_spfli        type ty_st_spfli,     wa_spfli        type ty_str_spfli.

" Declaramos las Variables que necesitamos para la creación de ALV OO.

data: it_fieldcat   type lvc_t_fcat,      wa_fieldcat   type lvc_s_fcat,      wa_layout     type lvc_s_layo,      it_sort_alv   type lvc_t_sort,      ob_container  type ref to cl_gui_custom_container,      ob_alv_grid   type ref to cl_gui_alv_grid.

*&---------------------------------------------------------------------**&  Include           ZNSFER_ALVO_S01*&---------------------------------------------------------------------*

" Parametros que vamos a utilizarparameters:           pa_nom(10)  type c,           pa_edad(2) type n,           pa_id   type sflight-carrid.

select-options              s_fldate for sflight-fldate.

form fp_leer_tablas .clear gv_indi.

  refresh: it_sflight[],           it_scarr[],           it_spfli[].

  select carrid         connid

Page 79: Programa ALV

         fldate         price         currency

  from sflight  into table it_sflight  where carrid = pa_id and fldate in s_fldate.  if  sy-subrc = 0.    select carrid           carrname    from scarr    into table it_scarr    for all entries in it_sflight    where carrid = it_sflight-carrid.

    select carrid           connid           countryfr           cityto           airpto           fltime           deptime           arrtime

     from spfli     into table it_spfli     for all entries in it_sflight     where carrid = it_sflight-carrid.  else.perform fp_sugerencia.

gv_indi = 'X'.

    message 'NO HAY VUELOS DISPONIBRES EN LA AEROLINEA SELECCIONADA,LE DAMOS LAS SIGUIENTES SUJERENCIAS:' type 'I'.

endif.

endform.                    " FP_LEER_TABLAS*&---------------------------------------------------------------------**&      Form  FP_ARMAR_DATOS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_armar_datos .

Page 80: Programa ALV

  if  it_scarr[] is not initial.    loop at it_sflight into wa_sflight.      if wa_sflight-fldate in s_fldate.        append wa_sflight to it_sflight2.      endif.    endloop.  endif.endform.                    " FP_ARMAR_DATOS*&---------------------------------------------------------------------**&      Form  FP_OBTENER_CARRNAME*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_obtener_carrname .  data:     lv_tabix type sy-tabix.

  loop at it_sflight into wa_sflight.    lv_tabix = sy-tabix.    move-corresponding wa_sflight to wa_salida.

    read table it_scarr into wa_scarr               with key carrid = wa_sflight-carrid               binary search.    if sy-subrc = 0.      wa_salida-carrname = wa_scarr-carrname.      "MODIFY it_sflight2 FROM wa_sflight INDEX lv_tabix      "TRANSPORTING carrname.    endif.

    read table it_spfli into wa_spfli               with key carrid = wa_sflight-carrid               binary search.    if sy-subrc = 0.      wa_salida-countryfr = wa_spfli-countryfr.      wa_salida-cityto = wa_spfli-cityto.      wa_salida-airpto = wa_spfli-airpto.      wa_salida-fltime  = wa_spfli-fltime.      wa_salida-deptime = wa_spfli-deptime.      wa_salida-arrtime = wa_spfli-arrtime.

*      wa_sflight-carrname = wa_scarr-carrname.*      MODIFY it_sflight2 FROM wa_sflight INDEX lv_tabix*                         TRANSPORTING carrname.    endif.    append wa_salida to it_salida.

Page 81: Programa ALV

  endloop.

endform.                    " FP_OBTENER_CARRNAME*&---------------------------------------------------------------------**&      Form  FP_VALIDACIONES*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_validaciones .  loop at it_salida into wa_salida.    if pa_edad >= 60.

      wa_salida-ahorro = wa_salida-price * '0.20'.      wa_salida-price = wa_salida-price - wa_salida-ahorro.      "gv_resultado = wa_sflight-price - gv_resultado1.

*  ELSEIF pa_edad < 60.

    endif.

    modify it_salida from wa_salida.

  endloop.

endform.                    " FP_VALIDACIONES*&---------------------------------------------------------------------**&      Form  FP_IMPRIME_DATOS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_imprime_datos .  write:/ 'NOMBRE', ':', pa_nom.  write:/ 'EDAD', ':', pa_edad.  write:/ 'AEROLINEA', ':', pa_id.  write:/  .  write:/ ' CARRID   ', '|','CONNID ','   |', 'FLDATE','    |','CURRENCY','|',          'PRICE','               |'.

Page 82: Programa ALV

  loop at  it_sflight2 into wa_sflight.

    write: /   wa_sflight-carrid,'       |', wa_sflight-connid, '      |',wa_sflight-fldate, '|',    wa_sflight-currency, '   |',  '  |',wa_sflight-price,'|'.

  endloop.

  write:/.  write:/'Precio con el 20% de Descuento', ':', gv_resultado.  write:/'Su ahorro fue de', ':', gv_resultado1.

endform.                    " FP_IMPRIME_DATOS*&---------------------------------------------------------------------**&      Module  STATUS_0180  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module status_0180 output.  set pf-status '0180'. "No. de dympro que creamos  set titlebar 'VUELOS '.

endmodule.                 " STATUS_0180  OUTPUT*&---------------------------------------------------------------------**&      Module  IMPRIMIR_ALVOO  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*module imprimir_alvoo output.

  if ob_container is not bound.    "Crea el custom container control para nuestra ALVOO    create object ob_container      exporting        container_name              = 'CC_ALV0180' "Nombre que le dimos a nuestro custom container      exceptions        cntl_error                  = 1        cntl_system_error           = 2        create_error                = 3        lifetime_error              = 4        lifetime_dynpro_dynpro_link = 5.

    "Crea una instancia del control ALV    create object ob_alv_grid      exporting        i_parent = ob_container.

Page 83: Programa ALV

    "En el  perfor f_layout_alv daremos el formato que tendra nuestra tabla alvoo    perform f_layout_alv.    " En ell perform f_fieldcat_alv. construiremos  el Catálogo de campos de nuestra tabla ALV    perform: f_fieldcat_alv.  endif.

  "Ejecuto el ALV  call method ob_alv_grid->set_table_for_first_display    exporting      i_save          = 'x'      is_layout       = wa_layout    changing      it_outtab       = it_salida      it_fieldcatalog = it_fieldcat.

endmodule.                 " IMPRIMIR_ALVOO  OUTPUT*&---------------------------------------------------------------------**&      Form  F_LAYOUT_ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_layout_alv .  wa_layout-zebra = 'X'.  wa_layout-cwidth_opt = 'X'.  wa_layout-frontend = 'X'.

endform.                    " F_LAYOUT_ALV*&---------------------------------------------------------------------**&      Form  F_FIELDCAT_ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form f_fieldcat_alv .  " se limpian las variables con las que se trabajarán  refresh it_fieldcat.  clear wa_fieldcat.  " Se comienza a alimentar nuestro "catálogo de campos" para el ALV...

Page 84: Programa ALV

  wa_fieldcat-tabname    = 'IT_SALIDA'. "Nombre de nuestra tabla interna  wa_fieldcat-fieldname  = 'CARRID'.      "nombre de nuestro campo  wa_fieldcat-ref_table  = 'SFLIGHT'.     "Nombre de la Tabla referencia  wa_fieldcat-ref_field  = 'CARRID'.      "Nombre del campo de referencia.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'CONNID'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'CONNID'.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'FLDATE'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'FLDATE'.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'CURRENCY'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'CURRENCY'.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'PRICE'.  wa_fieldcat-ref_table  = 'SFLIGHT'.  wa_fieldcat-ref_field  = 'PRICE'.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

  wa_fieldcat-tabname    = 'IT_SALIDA'.  wa_fieldcat-fieldname  = 'AHORRO'.  wa_fieldcat-scrtext_l  = 'Ahorro'.  wa_fieldcat-scrtext_m  = 'Ahorro'.  wa_fieldcat-scrtext_s  = 'Ahorro'.  append wa_fieldcat to it_fieldcat.  clear  wa_fieldcat.

endform.                    " F_FIELDCAT_ALV*&---------------------------------------------------------------------**&      Module  USER_COMMAND_0180  INPUT*&---------------------------------------------------------------------*

Page 85: Programa ALV

*       text*----------------------------------------------------------------------*module user_command_0180 input.  if     sy-ucomm eq 'EXIT'      or sy-ucomm eq 'CANCEL'      or sy-ucomm eq 'BACK'.    set screen 0.    leave screen.  endif.

endmodule.                 " USER_COMMAND_0180  INPUT*&---------------------------------------------------------------------**&      Form  FP_SUGERENCIA*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form fp_sugerencia .

   refresh: it_sflight[],           it_scarr[],           it_spfli[].

  select carrid         connid         fldate         price         currency

  from sflight  into table it_sflight  where fldate in s_fldate.  if  sy-subrc = 0.    select carrid           carrname    from scarr    into table it_scarr    for all entries in it_sflight    where carrid = it_sflight-carrid.

    select carrid           connid           countryfr           cityto           airpto           fltime           deptime

Page 86: Programa ALV

           arrtime

     from spfli     into table it_spfli     for all entries in it_sflight     where carrid = it_sflight-carrid.endif.

endform.                    " FP_SUGERENCIA

include: z_alv2b_top,   " global Data         z_alv2b_s01,         z_alv2b_f01." FORM-Routines

Page 87: Programa ALV

start-of-selection.

perform lectura_datos.perform validaciones.perform alv.

*&---------------------------------------------------------------------**& Include Z_ALV2B_TOP                                       Report Z_ALV_2B*&*&---------------------------------------------------------------------*

report   z_alv_2b.tables: spfli, sflight.

data :

       gv_resultado1    type  sflight-price,       gv_resultado     type sflight-price.

types: begin of tt_salida,carrid    type s_carrid,connid    type s_conn_id,fldate    type s_date,countryfr type land1,cityto    type s_to_city,airpto    type s_fromairp,deptime   type s_dep_time,arrtime   type s_arr_time,price     type s_price,currency  type s_currcode,ahorro    type s_price,"nombre    TYPE c,"edad      TYPE n,

end of tt_salida.

constants:  pr type  s_price value '0.20'.

Page 88: Programa ALV

data: begin of gt_sflight occurs 0,carrid    like sflight-carrid,connid    like sflight-connid,fldate    like sflight-fldate,currency  like sflight-currency,price     like sflight-price,end of gt_sflight.

data: begin of gt_spfli occurs 0,countryfr  like spfli-countryfr,cityto     like spfli-cityto ,airpto     like spfli-airpto,deptime    like spfli-deptime,arrtime    like spfli-arrtime,

end of gt_spfli.

data: gt_salida type standard table of tt_salida,wa_salida type tt_salida,contador type p,lv_count type p, wa_sflight like gt_sflight,lv_columns type ref to cl_salv_columns_table,lv_column  type ref to cl_salv_column,lv_alv_object type ref to cl_salv_table,g_functions type ref to cl_salv_functions,gr_display type ref to cl_salv_display_settings.

*&---------------------------------------------------------------------**&  Include           Z_ALV2B_S01*&---------------------------------------------------------------------*

selection-screen begin of block b1 with frame title text-001.  "definen un bloque en la actual pantalla de selecciónparameters: pa_nom(10) type c,            pa_edad(2) type n.selection-screen end of block b1.

selection-screen begin of block b2 with frame title text-002.select-options : s_carrid for sflight-carrid,                 s_connid for sflight-connid,                 s_fldate for sflight-fldate.

selection-screen end of block b2.

Page 89: Programa ALV

*&---------------------------------------------------------------------**&  Include           Z_ALV2B_F01*&---------------------------------------------------------------------**&---------------------------------------------------------------------**&      Form  LECTURA_DATOS*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form lectura_datos.clear: gt_sflight[],       gt_spfli[],       gt_salida[].

  select carrid          connid          fldate          price          currency   from   sflight   into corresponding fields of table gt_sflight   where carrid in s_carrid and connid in s_connid                             and fldate in s_fldate.

  loop at gt_sflight.

    move-corresponding gt_sflight to wa_salida.

    select           countryfr           cityto           airpto           deptime           arrtime     into gt_spfli     from spfli.

Page 90: Programa ALV

      move-corresponding  gt_spfli to wa_salida.      append wa_salida to gt_salida.

    endselect.  endloop.

endform.                    " LECTURA_DATOS*&---------------------------------------------------------------------**&      Form  VALIDACIONES*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form validaciones .

  if  gt_salida[] is not initial .  "Si la tabla contiene datos, recorre la tabla interna.    loop at gt_salida  into wa_salida .*      "Si la edad ingresada es mayor o igual de 60, tendrá un 20% de descuento.      if  pa_edad >= 60.*        gv_resultado1 = wa_sflight-price * '0.20'.        wa_salida-ahorro =  wa_salida-price * pr.        wa_salida-price = wa_salida-price - wa_salida-ahorro.

        "wa_salida-price = wa_salida-price - wa_salida-price."- gv_resultado1.        modify gt_salida  from wa_salida.      endif.    endloop.*    "si la tabla no contiene información deseada, manda un mensaje informativo.  elseif  sy-subrc ne 0.    message 'No hay vuelos disponibles en esa fecha seleccione otra' type 'I'.

  endif.

endform.                    " VALIDACIONES*&---------------------------------------------------------------------*

Page 91: Programa ALV

*&      Form  ALV*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------**  -->  p1        text*  <--  p2        text*----------------------------------------------------------------------*form alv .

  if gt_salida[] is not initial.

"CL_SALV_TABLE. Con ella podemos contruirnos un informe con tan solo llamar a un método el factory y luego al displa    cl_salv_table=>factory(    importing    r_salv_table = lv_alv_object    changing    t_table = gt_salida    ).

    g_functions = lv_alv_object->get_functions( ).    g_functions->set_all( abap_true ).

    lv_columns = lv_alv_object->get_columns( ).    lv_columns->set_optimize( 'X' ).

 gr_display = lv_alv_object->get_display_settings( ). gr_display->set_striped_pattern( cl_salv_display_settings=>true ). gr_display->set_list_header( 'Vuelos y precios' ).

** Visualizamos el ALV    lv_alv_object->display( ).  else.    message 'No tiene itinerario' type 'I'.

  endif.

endform.                    " ALV

Page 92: Programa ALV

Árbol

REPORT demo_free_selections.

PARAMETERS dbtab TYPE tabname DEFAULT 'SPFLI'.

CLASS demo DEFINITION. PUBLIC SECTION. CLASS-METHODS main. PRIVATE SECTION. CLASS-METHODS check_existence_and_authority RETURNING value(checked_dbtab) TYPE tabname.ENDCLASS.

CLASS demo IMPLEMENTATION. METHOD main. DATA selid TYPE rsdynsel-selid. DATA field_tab TYPE TABLE OF rsdsfields. DATA table_tab TYPE TABLE OF rsdstabs. DATA table LIKE LINE OF table_tab. DATA cond_tab TYPE rsds_twhere. DATA dref TYPE REF TO data. DATA alv TYPE REF TO cl_salv_table.

FIELD-SYMBOLS <table> TYPE STANDARD TABLE. FIELD-SYMBOLS <cond> LIKE LINE OF cond_tab.

DATA checked_dbtab TYPE tabname. checked_dbtab = demo=>check_existence_and_authority( ).

table-prim_tab = dbtab. APPEND table TO table_tab. CALL FUNCTION 'FREE_SELECTIONS_INIT' EXPORTING kind = 'T' IMPORTING

Page 93: Programa ALV

selection_id = selid TABLES tables_tab = table_tab EXCEPTIONS OTHERS = 4. IF sy-subrc <> 0. MESSAGE 'Error in initialization' TYPE 'I' DISPLAY LIKE 'E'. LEAVE PROGRAM. ENDIF.

CALL FUNCTION 'FREE_SELECTIONS_DIALOG' EXPORTING selection_id = selid title = 'Free Selection' as_window = ' ' IMPORTING where_clauses = cond_tab TABLES fields_tab = field_tab EXCEPTIONS OTHERS = 4. IF sy-subrc <> 0. MESSAGE 'No free selection created' TYPE 'I'. LEAVE PROGRAM. ENDIF.

READ TABLE cond_tab WITH KEY tablename = dbtab ASSIGNING <cond>. IF sy-subrc <> 0. MESSAGE 'Error in condition' TYPE 'I' DISPLAY LIKE 'E'. LEAVE PROGRAM. ENDIF.

CREATE DATA dref TYPE TABLE OF (checked_dbtab). ASSIGN dref->* TO <table>.

TRY. SELECT * FROM (checked_dbtab) INTO TABLE <table> WHERE (<cond>-where_tab). CATCH cx_sy_dynamic_osql_error. MESSAGE 'Error in dynamic Open SQL' TYPE 'I' DISPLAY LIKE 'E'.

Page 94: Programa ALV

LEAVE PROGRAM. ENDTRY.

TRY. cl_salv_table=>factory( IMPORTING r_salv_table = alv CHANGING t_table = <table> ). alv->display( ). CATCH cx_salv_msg. MESSAGE 'Error in ALV display' TYPE 'I' DISPLAY LIKE 'E'. ENDTRY. ENDMETHOD. METHOD check_existence_and_authority. TRY. checked_dbtab = cl_abap_dyn_prg=>check_table_name_str( val = dbtab packages = 'SAPBC_DATAMODEL' ). CATCH cx_abap_not_a_table. MESSAGE 'Database table not found' TYPE 'I' DISPLAY LIKE 'E'. LEAVE PROGRAM. CATCH cx_abap_not_in_package. MESSAGE 'Only tables from the flight data model are allowed' TYPE 'I' DISPLAY LIKE 'E'. LEAVE PROGRAM. ENDTRY. ENDMETHOD.ENDCLASS.

START-OF-SELECTION. demo=>main( ).