abap globalsap
DESCRIPTION
AbapTRANSCRIPT
Field name Key Type Length DescriptionPEL_ID X NUMC 10 Código
PelículaPELTXT CHAR 40 Nombre
Película original
AGNO NUMC 4 Año DURACION NUMC 4 Duración en
minutosPAIS_ID CHAR 2 Pais de origen (
Código Pais ISO )
GENERO_ID NUMC 3 Código género(Terror, Drama, etc.)
DIRECTOR_ID NUMC 10 Código directorTabla ZPELICULAS : Películas
Crear tabla ZPELICULAS en SAP(SE11) con los campos requeridos, para cada campo crear su respectivo Elementos de Datos y Dominio. Para Género crear en el dominio, ámbito de valores, con la siguiente lista:
Cine de acción Cine de animación Cine de aventuras Cine Bélico Serie B Ciencia Ficción Cine de autor Cine fantástico Cine negro
Cine pornográfico Comedia (cine) Comedia romántica Documental Drama Melodrama Cine histórico Intriga y suspense Cine musical Cine policíaco Cine de terror Western
Crear tabla ZDIRECTORES con los siguientes campos
Field name Key Type Length DescriptionDIRECTOR_ID X NUMC 10 Código directorNOMBRE CHAR 60 Nombre Completo
directorNACION NUMC 2 Nacionalidad(Código
ISO pais)FEC_NAC DATS 8 Fecha nacimientoFEC_MUE DATS 8 Fecha Fallecimiento
Crear Elemento de datos Respectivo para cada campo.
Tabla ZDVD
Field name Key Type Length decimals DescriptionDVD_ID X NUMC 10 Código DVDPEL_ID X NUMC 10 Código
PelículaPRECIO CURR 15 2 Precio
Unitario DVDMONEDA cuky 5 Moneda STOCK DEC 5 0 Stock DVDZONA numc 1 Zona DVD
En Moneda usar elemento de datos waers. Para DVD_ID, PRECIO y STOCK, crear elemento de datos.
Cláusula SELECT
Seleccionar todas las películas e imprimir código y nombre:
TABLES ZPELICULAS.
SELECT * FROM ZPELICULAS .WRITE:/ ZPELICULAS-PEL_ID, ZPELICULAS-PELTXT.ENDSELECT.
Lo anterior es equivalente a,
Data wa_zpeliculas like zpeliculas.
SELECT * into wa_zpeliculas FROM ZPELICULAS .WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.
Seleccionar todas las películas con país origen Chile e imprimir código y nombre:
Data wa_zpeliculas like zpeliculas.
SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID = ‘CL’.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.
Seleccionar todas las películas con país origen Chile o Argentina e imprimir código y nombre:
Data wa_zpeliculas like zpeliculas.
SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID = ‘CL’ OR PAIS_ID EQ ‘AR’.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.
Operator Meaning
=, EQ True, if the content of col is the same as the content of f.
<>, NE True, if the content of col is different to the content of f.
<, LT True, if the content of col is less than the content of f.
>, GT True, if the content of col is greater than the content of f.
<=, LE True, if the content of col is less than or equal to the content of f.
>=, GE True, if the content of col is greater than or equal to the content of f.
Seleccionar todas las películas con país origen Chile o Argentina cuya duración no sea mayor a 120 minutos, e imprimir código y nombre:
Data wa_zpeliculas like zpeliculas.
SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE ( PAIS_ID = ‘CL’ OR PAIS_ID EQ ‘AR’ ) AND DURACION <= ‘120’. .WRITE:/ wa_ZPELICULAS-PEL_ID,
Wa_ZPELICULAS-PELTXT.ENDSELECT.
Notar que lo anterior es equivalente a:
SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE ( PAIS_ID = ‘CL’ AND DURACION <= ‘120’ ) OR ( PAIS_ID EQ ‘AR’ AND DURACION <= ‘120’. .WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.
PARAMETERS
PARAMETERS p_pais like ZPELICULAS-pais_id.
Data wa_zpeliculas like zpeliculas.
SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID = p_pais.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.
SELECT-OPTIONS
SELECT-OPTIONS s_pais for ZPELICULAS-pais_id.
Data wa_zpeliculas like zpeliculas.
SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID IN s_pais.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.
SELECT-OPTIONS: s_pais for ZPELICULAS-pais_id, s_dura for ZPELICULAS-duracion.
Data wa_zpeliculas like zpeliculas.
SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID IN s_pais AND DURACION IN s_dura.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.
Ejercicio:
Crear reporte que dada la nacionalidad del director, imprimir Nombre de Película, Nombre de Director, Nacionalidad Director, Duración Película. ( Usar select-options para leer nacionalidad de director )
TABLAS INTERNAS
Formas de definir tablas internas.
Data: begin of tb_pel occurs 0, Pel_id like zpeliculas-pel_id, Peltxt like zpeliculas-peltxt,End of tb_pel.
lo anterior es equivalente a :
Data : begin of wa_pel, Pel_id like zpeliculas-pel_id, Peltxt like zpeliculas-peltxt,End of wa_pel.
Data tb_pel like standard table of wa_pel with header line.
Seleccionar todas las películas e imprimir código y nombre:
Data tb_zpeliculas like Standard table of zpeliculas with header line.
SELECT * into table tb_zpeliculas FROM ZPELICULAS .
Loop at tb_zpeliculas
WRITE:/ tb_ZPELICULAS-PEL_ID, tb_ZPELICULAS-PELTXT.Endloop.
****************************************************Data tb_zpeliculas like Standard table of zpeliculas.Data wa like tb_zpeliculas.
SELECT * into table tb_zpeliculas FROM ZPELICULAS .
Loop at tb_zpeliculas into wa.
WRITE:/ wa-PEL_ID, wa-PELTXT.Endloop.
into corresponding fields
Data : begin of wa_aux, Pel_id like zpeliculas-pel_id, Peltxt like zpeliculas-peltxt,End of wa_aux.
Data tb_aux like standard table of wa_aux with header line.
SELECT * into corresponding fields of table tb_aux FROM ZPELICULAS .
Loop at tb_aux.
WRITE:/ tb_aux-PEL_ID, tb_aux-PELTXT.Endloop.
Crear reporte que dada la nacionalidad del director, imprimir Nombre de Película, Nombre de Director, Nacionalidad Director, Duración Película. Usar tablas internas.
MODULARIZACION
Subrutinas
Data tb_zpeliculas like Standard table of zpeliculas with header line.
Perform leer_peliculas.Perform write_peliculas.
Form leer_peliculas. SELECT * into table tb_zpeliculas FROM ZPELICULAS .Endform.
Form write_peliculas. Loop at tb_zpeliculas
WRITE:/ tb_ZPELICULAS-PEL_ID, tb_ZPELICULAS-PELTXT. Endloop.Endform.
Ejemplo de subrutina con parámetros de entrada.
Data tb_zpeliculas like Standard table of zpeliculas with header line.
PARAMETERS p_pais like ZPELICULAS-pais_id.
Perform leer_peliculas using p_pais.
Perform write_peliculas.
Form leer_peliculas using p_pais_de_entrada. SELECT * into table tb_zpeliculas FROM ZPELICULAS Where pais_id = p_pais_de_entrada.Endform.
Form write_peliculas. Loop at tb_zpeliculas
WRITE:/ tb_ZPELICULAS-PEL_ID, tb_ZPELICULAS-PELTXT. Endloop.Endform.
Ejemplo de subrutina con parámetros de entrada y salida
Data tb_zpeliculas like Standard table of zpeliculas with header line.Data v_peltxt like ZPELICULAS-PELTXT.
PARAMETERS p_id like ZPELICULAS-pel_id.
Perform leer_peliculas using p_id changing v_peltxt.Perform write_peliculas using p_id V_peltxt..
Form leer_peliculas using p_pel_id changing p_nombre_pel. SELECT single peltxt into p_nombre_pel FROM ZPELICULAS Where pel_id = p_pel_id.Endform.
Form write_peliculas using p_pel_id P_nombre_pel.
WRITE:/ p_PEL_ID, P_nombre_pel.Endform.
Includes
Creamos dos Includes, se crean igual que los programas, pero son de tipo ‘I’.
ZPELICULAS_TOP.: Para declarar variablesZPELICULAS_F01 : Para declarar subrutinas
***********************************************************************INCLUDE ZPELICULAS_TOP.
Data tb_zpeliculas like Standard table of zpeliculas with header line.Data v_peltxt like ZPELICULAS-PELTXT.
*INCLUDE ZPELICULAS_F01
Form leer_peliculas using p_pel_id changing p_nombre_pel. SELECT single peltxt into p_nombre_pel FROM ZPELICULAS Where pel_id = p_pel_id.Endform.
Form write_peliculas using p_pel_id P_nombre_pel.
WRITE:/ p_PEL_ID, P_nombre_pel.Endform.
Entonces el programa principal queda:
INCLUDE ZPELICULAS_TOP.
PARAMETERS p_id like ZPELICULAS-pel_id.
Perform leer_peliculas using p_id changing v_peltxt.Perform write_peliculas using p_id V_peltxt.INCLUDE ZPELICULAS_F01 .
EVENTOS
INITIALIZATION
En este ejemplo se propondrá el año actual para la búsqueda de películas.
PARAMETERS: p_agno like zpeliculas-agno.SELECT-OPTIONS s_pais for ZPELICULAS-pais_id.
Data wa_zpeliculas like zpeliculas.
INITIALIZATION. p_agno = sy-datum(4).
START-OF-SELECTION.SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID IN s_pais AND agno = p_agno.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.END-OF-SELECTION.
En este ejemplo siempre se propondrá el país ‘CL’ en la búsqueda.
SELECT-OPTIONS s_pais for ZPELICULAS-pais_id.
Data wa_zpeliculas like zpeliculas.
INITIALIZATION. s_pais-sign = ‘I’ s_pais-option = ‘EQ’. s_pais-low = ‘CL’.append s_pais.
START-OF-SELECTION.SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID IN s_pais.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.END-OF-SELECTION.
AT-SELECTION-SCREEN.
Validar datos en la pantalla inicial del reporte. En este ejemplo validamos que en parámetro país este prohibido ingresar Argentina(AR).
PARAMETERS p_pais like ZPELICULAS-pais_id.
Data wa_zpeliculas like zpeliculas.
AT-SELECTION-SCREEN.
if p_pais = ‘AR’. Message E398(00) with ‘Codigo de pais inválido’.Endif.
START-OF-SELECTION.SELECT * into wa_zpeliculas FROM ZPELICULAS WHERE PAIS_ID EQ p_pais.WRITE:/ wa_ZPELICULAS-PEL_ID, Wa_ZPELICULAS-PELTXT.ENDSELECT.END-OF-SELECTION.
OBS: los mensajes están en la tabla T100.
FUNCTIONS
Crear función Z_LEER_PELICULA que dado un id de película entregue el nombre.Entonces ahora en el programa principal esta función se llamaría:
Data tb_zpeliculas like Standard table of zpeliculas with header line.Data v_peltxt like ZPELICULAS-PELTXT.
PARAMETERS p_id like ZPELICULAS-pel_id.
Perform leer_peliculas using p_id changing v_peltxt.Perform write_peliculas using p_id V_peltxt..
Form leer_peliculas using p_pel_id changing p_nombre_pel.* SELECT single peltxt into p_nombre_pel FROM ZPELICULAS * Where pel_id = p_pel_id.
CALL FUNCTION ‘Z_LEER_PELICULA’EXPORTING PEL_ID = p_pel_idIMPORTING PELTXT = p_nombre_pelEXCEPTIONS Not_ found = 1.If sy-subrc ne 0. Clear p_nombre_pel .
Endif.
Endform.
Form write_peliculas using p_pel_id P_nombre_pel.
WRITE:/ p_PEL_ID, P_nombre_pel.Endform.
Crear función (SE37) Z_READ_DVD que dado un código de DVD, como salida entregue:
ID_DVDNombre PelículaNombre DirectorAño PelículaDuración en minutosPaís de origen GéneroPrecio DVD
Stock DVD
Crear función Z_READ_DVD_2 que dado un código de DVD, como salida entregue estructura con siguientes campos. OBS: crear estructura ZQ_DVD con la SE11, para los campos usar las mismas definiciones que las tablas ZPELICULAS; ZDIRECTORES Y ZDVD
Field name Key Type Length DescriptionDVD_ID NUMC 10PEL_ID NUMC 10 Código
PelículaPELTXT CHAR 40 Nombre
Película original
AGNO NUMC 4 Año DURACION NUMC 4 Duración en
minutosPAIS_ID CHAR 2 Pais de origen (
Código Pais ISO )
GENERO_ID NUMC 3 Código género(Terror, Drama, etc.)
DIRECTOR_ID NUMC 10 Código directorNOMBREPRECIO Precio Unitario
DVDMONEDA MonedaSTOCK Stock DVD
Usar function GUI_UPLOAD ejemplo
report ztest_upload .
data : begin of itab occurs 0, pelicula like zpeliculas-pel_id, nombre like zpeliculas-peltxt, end of itab.
parameters : p_fname like rlgrap-filename default 'c:\' obligatory.
Data filename type string.*-- Select Directory where Upload File Residesat selection-screen on value-request for p_fname. call function 'F4_FILENAME' exporting field_name = 'P_FNAME' importing file_name = p_fname.
start-of-selection.
filename = p_fname.call function 'GUI_UPLOAD' exporting filename = filename filetype = 'ASC'* HAS_FIELD_SEPARATOR = ' '
* HEADER_LENGTH = 0* READ_BY_LINE = 'X'* DAT_MODE = ' '* IMPORTING* FILELENGTH =* HEADER = tables data_tab = itab.* EXCEPTIONS* FILE_OPEN_ERROR = 1* FILE_READ_ERROR = 2* NO_BATCH = 3* GUI_REFUSE_FILETRANSFER = 4* INVALID_TYPE = 5* NO_AUTHORITY = 6* UNKNOWN_ERROR = 7* BAD_DATA_FORMAT = 8* HEADER_NOT_ALLOWED = 9* SEPARATOR_NOT_ALLOWED = 10* HEADER_TOO_LONG = 11* UNKNOWN_DP_ERROR = 12* ACCESS_DENIED = 13* DP_OUT_OF_MEMORY = 14* DISK_FULL = 15* DP_TIMEOUT = 16* OTHERS = 17 .if sy-subrc <> 0.* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.endif.
end-of-selection.
loop at itab. write : / 'Pel id :' , itab-pelicula, 'NAME :', itab-nombre.endloop.
Tarea: dado un archivo plano que tiene el siguiente formato
Field name Key Type Length DescriptionDIRECTOR_ID X NUMC 10 Código directorNOMBRE CHAR 60 Nombre Completo
directorNACION NUMC 2 Nacionalidad(Código
ISO pais)FEC_NAC DATS 8 Fecha nacimientoFEC_MUE DATS 8 Fecha Fallecimiento
Cargar directores en la tabla zdirectores. Usar instrucción INSERT.
Ejemplo
0000000099Brian de Palma US19400911000000000000000100David Lynch US19460120000000000000000101Sam Peckinpah US19250221198412280000000102Sergio Leone IT1929939119890430
Tarea: usar la function GUI_DOWNLOAD para bajar todas las películas, bajar archivo plano con id, y nombre de película.
*&---------------------------------------------------------------------**& Report ZUPLOADTAB **& **&---------------------------------------------------------------------**& Example of Uploading tab delimited file **& **&---------------------------------------------------------------------*REPORT zuploadtab .
PARAMETERS: p_infile LIKE rlgrap-filename OBLIGATORY DEFAULT '/usr/sap/'..
*DATA: ld_file LIKE rlgrap-filename.DATA: gd_file type string.
*Internal tabe to store upload dataTYPES: BEGIN OF t_record, name1 LIKE pa0002-vorna, name2 LIKE pa0002-name2, age TYPE i, END OF t_record.DATA: it_record TYPE STANDARD TABLE OF t_record INITIAL SIZE 0, wa_record TYPE t_record.
*Internal table to upload data intoDATA: BEGIN OF it_datatab OCCURS 0, row(500) TYPE c, END OF it_datatab.
*Text version of data tableTYPES: BEGIN OF t_uploadtxt, name1(10) TYPE c, name2(15) TYPE c, age(5) TYPE c, END OF t_uploadtxt.DATA: wa_uploadtxt TYPE t_uploadtxt.
*String value to data in initially.DATA: wa_string(255) TYPE c.
CONSTANTS: con_tab TYPE x VALUE '09'.
*If you have Unicode check active in program attributes then you will*need to declare constants as follows:
*class cl_abap_char_utilities definition load.*constants:* con_tab type c value cl_abap_char_utilities=>HORIZONTAL_TAB.
*************************************************************************AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_INFILE.AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_infile. CALL FUNCTION 'WS_FILENAME_GET' EXPORTING def_filename = p_infile mask = ',*.txt.' mode = 'O' title = 'Upload File'(078) IMPORTING filename = p_infile EXCEPTIONS inv_winsys = 1 no_batch = 2 selection_cancel = 3 selection_error = 4 OTHERS = 5.
*************************************************************************START-OF-SELECTIONSTART-OF-SELECTION. gd_file = p_infile.
CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = gd_file has_field_separator = 'X' "file is TAB delimited TABLES data_tab = it_record EXCEPTIONS file_open_error = 1 file_read_error = 2 no_batch = 3 gui_refuse_filetransfer = 4 invalid_type = 5 no_authority = 6 unknown_error = 7 bad_data_format = 8 header_not_allowed = 9 separator_not_allowed = 10 header_too_long = 11 unknown_dp_error = 12 access_denied = 13 dp_out_of_memory = 14 disk_full = 15 dp_timeout = 16 OTHERS = 17. IF sy-subrc NE 0. write: 'Error ', sy-subrc, 'returned from GUI_UPLOAD FM'. skip. endif.
* Alternative method, where by you split fields at each TAB after you * have returned the data. No point unless you dont have access to
* GUI_UPLOAD but just included for information ** CALL FUNCTION 'GUI_UPLOAD'* EXPORTING* filename = gd_file* filetype = 'ASC'* TABLES* data_tab = it_datatab "ITBL_IN_RECORD[]* EXCEPTIONS* file_open_error = 1* OTHERS = 2.* IF sy-subrc NE 0.* ELSE.* LOOP AT it_datatab.* CLEAR: wa_string, wa_uploadtxt.* wa_string = it_datatab.* SPLIT wa_string AT con_tab INTO wa_uploadtxt-name1* wa_uploadtxt-name2* wa_uploadtxt-age.* MOVE-CORRESPONDING wa_uploadtxt TO wa_record.* APPEND wa_record TO it_record.* ENDLOOP.* ENDIF.
*************************************************************************END-OF-SELECTIONEND-OF-SELECTION.*!! Text data is now contained within the internal table IT_RECORD
* Display report data for illustration purposesLOOP AT it_record INTO wa_record. WRITE:/ sy-vline, (10) wa_record-name1, sy-vline, (10) wa_record-name2, sy-vline, (10) wa_record-age, sy-vline.
ENDLOOP.
OPEN DATASET.
For input(leer datos DESDE SERVIDOR DE APLICACIÖN)
report ztest_upload .
data : begin of itab occurs 0, pel_id like zpeliculas-pel_id, peltxt like zpeliculas-peltxt, end of itab.
parameters : p_fname like rlgrap-filename obligatory.
start-of-selection.
Open dataset p_fname for input in text mode.Check sy-subrc = 0.
Do.read dataset p_fname into itab.If sy-subrc <> 0. Exit.Endif.Append itab.
Enddo.
end-of-selection.
loop at itab. write : / 'Pel id :' , itab-pelicula, 'NAME :', itab-nombre.endloop.
For output(transferir datos DESDE SERVIDOR DE APLICACION)
report ztest_download .
data : begin of itab occurs 0, pelicula like zpeliculas-pel_id, nombre like zpeliculas-peltxt, end of itab.
parameters : p_fname like rlgrap-filename obligatory.
start-of-selection.
SELECT * into corresponding fields of table itab FROM ZPELICULAS .*ENDSELECT.
end-of-selection.
Open dataset p_fname for output in text mode.Check sy-subrc = 0.loop at itab. Transfer itab to p_fname.endloop.
Close dataset p_fname.
Reportes ALV
Ejemplo 1
report grid_edit.*type-pools: slis.* Data to be displayeddata: gs_layout type slis_layout_alv.
Data tb_zpeliculas type table of zpeliculas .
PARAMETERS p_pais like ZPELICULAS-pais_id.
*---------------------------------------------------------------------** Selection
SELECT * into table tb_zpeliculas FROM ZPELICULAS Where pais_id = p_pais_de_entrada.
* Eingabebereitgs_layout-edit = 'X'.
* Call ABAP List Viewer (ALV)call function 'REUSE_ALV_GRID_DISPLAY' exporting i_callback_program = sy-cprog i_callback_user_command = 'USER_COMMAND' i_structure_name = 'ZPELICULAS' is_layout = gs_layout tables t_outtab = tb_zpeliculas.
form user_command using r_ucomm type sy-ucomm rs_selfield type slis_selfield. if r_ucomm = '&DATA_SAVE'.
message i000(0k) with text-001.
call function 'REUSE_ALV_LIST_DISPLAY' exporting i_structure_name = 'ZPELICULAS' tables t_outtab = tb_zpeliculas. endif.endform.
Ejemplo 2
report grid_edit.*type-pools: slis.* Data to be displayeddata: gs_layout type slis_layout_alv, it_fieldcat type slis_t_fieldcat_alv with header line.***********************************
Data tb_zpeliculas type table of zpeliculas .
PARAMETERS p_pais like ZPELICULAS-pais_id.
*---------------------------------------------------------------------*
* Selection
SELECT * into table tb_zpeliculas FROM ZPELICULAS Where pais_id = p_pais_de_entrada.
* Eingabebereitgs_layout-edit = 'X'.
perform create_fieldcat.
* Call ABAP List Viewer (ALV)call function 'REUSE_ALV_GRID_DISPLAY' exporting i_callback_program = sy-cprog is_layout = gs_layout it_fieldcat = it_fieldcat[] tables t_outtab = tb_zpeliculas.
form create_fieldcat.* Esturctura SLIS_FIELDCAT_ALV* tabname : Nombre de la tabla* fieldname : Nombre del campo de la tabla interna* ref_tabname : Tabla de referencia SAP* ref_fieldname: Campo de referencia SAP (el campo fieldname toma* las características del campo ref_fieldname)* ddictxt : El texto del encabezado sera (S)hort (M)iddle (L)ong* reptext_ddic : Información del encabezado de la columna* seltext_l : Texto largo* seltext_m : Texto medio* seltext_s : Texto pequeño* outputlen : 18. (ancho de la columna)* hotspot : 'X'. (se activa mano de selección)* key : 'X'. (muestra la columna en color verde y queda* fija en scrolling)* key_sel : Hace que la clave no sea obligatoria* col_pos : Numero de la posición de la columna* just : Justificación de salida (R)ight (L)eft (C)ent.* do_sum : El campo será sumado* currency : Moneda de calculo* no_zero : No muestra valores con 0* no_out : El campo no aparece en la salida del reporte it_fieldcat-fieldname = 'PEL_ID'. it_fieldcat-tabname = 'TB_ZPELICULAS'. it_fieldcat-ref_tabname = 'ZPELICULAS'.
* it_fieldcat-seltext_l = 'XXX'.* it_fieldcat-seltext_m = 'XXX'.* it_fieldcat-seltext_s = 'XXX'.* it_fieldcat-reptext_ddic = 'XXX'. APPEND it_fieldcat.
it_fieldcat-fieldname = 'PELTXT'. it_fieldcat-tabname = 'TB_ZPELICULAS'. it_fieldcat-ref_tabname = 'ZPELICULAS'. APPEND it_fieldcat.
it_fieldcat-fieldname = 'AGNO'. it_fieldcat-tabname = 'TB_ZPELICULAS'. it_fieldcat-ref_tabname = 'ZPELICULAS'. APPEND it_fieldcat.
it_fieldcat-fieldname = 'DURACION'. it_fieldcat-tabname = 'TB_ZPELICULAS'. it_fieldcat-ref_tabname = 'ZPELICULAS'. APPEND it_fieldcat.
it_fieldcat-fieldname = 'PAIS_ID'. it_fieldcat-tabname = 'TB_ZPELICULAS'. it_fieldcat-ref_tabname = 'ZPELICULAS'. APPEND it_fieldcat.
it_fieldcat-fieldname = 'GENERO_ID'. it_fieldcat-tabname = 'TB_ZPELICULAS'. it_fieldcat-ref_tabname = 'ZPELICULAS'. APPEND it_fieldcat.
it_fieldcat-fieldname = 'DIRECTOR_ID'. it_fieldcat-tabname = 'TB_ZPELICULAS'. it_fieldcat-ref_tabname = 'ZPELICULAS'. APPEND it_fieldcat.
endform.
Tarea: crear reporte alv, dado nombre de película y nombre de director(select-options), entregue el siguiente listado:
DVD IDNombre Película originalAño Duración en minutosPais de origen Género Nombre directorPrecio Unitario DVDMonedaStock DVD
Hint: Crear tabla interna con la mismos campos que se exigen en la salida del reporte, después crear el fieldcat con esos campos.
Hint: buscar en la se38 programas BCALV*, que son ejemplos dados por SAP. Por ejemplo el
BCALV_FULLSCREEN_DEMO
Solucion:
Tables: zpeliculas, Zdirectores.
Data tb_dvd like Standard table of zdvd with header line.
Select-options: s_dnombre for zdirectores-nombre, S_pnombre for zpeliculas-peltxt.
Start-of-selection.
.
Form read_dvd.
Data v_director_id like zdirectores-director_id.Data v_pel_id like zpeliculas-pel_id.
Select director_id into v_director_id from zdirectores Where nombre in s_dnombre.
Select pel_id into v_pel_id from zpeliculas Where peltxt in s_pnombre And director_id = v_director_id.
Select * into table tb_dvd from zdvd Where pel_id = v_pel_id. Endselect.
Endselect.
Endform.
DYNPROS
Con la se38 creamos programa tipo M(modulpool)
Después vamos a la transac. Se51
Y creamos la dynpro, en este caso la ‘0200’. OBS : el N° es arbitrario. Atributos
Disposición
Seleccionando esta opción, “dibujaremos” la pantalla,
disposición
A la izquierda objetos que podemos agregar a una dynpro. En nuestro caso queremos agregar “campos de entrada/salida” para ingresar datos de directores.
Ahora agregaremos un texto, para describir el campo de entrada. Para ello agregamos “campo de texto”.
Variable ABAP en que “guardaremos” valor de campo de entrada
largo
tipo
Usamos el mismo procedimiento para crear los otros campos,
Texto a desplegar
Log. Proceso
Acá tenemos el PBO y en el PAI.
En el PBO definiremos el status GUI, de la dynpro, y el titulo. Para ello definiremos el modulo STATUS_0200. Tip: basta descomentar la línea y doble clic sobre “Module…” y lo creas.En este caso lo crearemos dentro del mismo programa ZDIRECTORES, pero se estila crearlo en un include para modulos PBO.
*&---------------------------------------------------------------------**& Module STATUS_0200 OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*module STATUS_0200 output. SET PF-STATUS 'STATUS'. SET TITLEBAR 'T01'.
endmodule. " STATUS_0200 OUTPUT
Definimos un status gui “STATUS” y un Titulo “T01”. Tip: doble clic sobre cada línea y directamente lo creamos.
Lo damos si
Grabamos y activamos. Volvemos a la dynpro, lógica. Creamos el título, equivalentemente, con doble clic:
Le damos nombre y eso es todo.
Volvamos a la lógica del programa:
En el PAI tenemos que “traspasar” los campos de entrada en la pantalla al programa principal. Para ello usamos la instrucción field para cada campo de entrada.
A los iconos le asignamos un nombre de comando:SAVEBACKCANC
Cada comando que ejecutamos en la dynpro tiene que asignarse a una variable, para ello, nos vamos a “Lista de Elemen.”
Instrucción
FIELD
Lo definimos como “OK_CODE”. Ahora agregamos la variable en el codigo ABAP
*&---------------------------------------------------------------------**& Modulpool ZDIRECTORES*&*&---------------------------------------------------------------------**&*&*&---------------------------------------------------------------------*
PROGRAM ZDIRECTORES.
data ok_code like sy-ucomm.
Ahora tenemos que definir que hacer por cada acción que existe dentro de la pantalla, para eso creamos el modulo USER_COMMAND_0200 (doble clic).
*&---------------------------------------------------------------------**& Module USER_COMMAND_0200 INPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*MODULE user_command_0200 INPUT. DATA fcode LIKE ok_code.
fcode = ok_code. CLEAR ok_code.
CASE fcode. WHEN 'SAVE'.
OK_CODE es solo un nombre
PERFORM grabar_director USING zdirectores. WHEN 'BACK'. LEAVE TO SCREEN 0. ENDCASE.
ENDMODULE. " USER_COMMAND_0200 INPUT
*&---------------------------------------------------------------------**& Form grabar_director*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** -->ZDIRECTORES text*----------------------------------------------------------------------*FORM grabar_director USING zdirectores STRUCTURE zdirectores. INSERT INTO zdirectores VALUES zdirectores. IF sy-subrc = 0. MESSAGE s000(fb) WITH 'Director ingresado con éxito'.Clear zdirector. ELSE. MESSAGE e000(fb) WITH 'Error ingreso director'. ENDIF.ENDFORM. "grabar_director
si observan, utilizamos la variable ok_code para determinar que “boton se presionó”. En este caso definimos que para el boton SAVE (ver status GUI), grabamos el director y en el caso de BACK salimos de la transacción.
Ahora hay que asignar una transacción a la dynpro
codigo
nombre
tipo
Y ejecutamos la transacción, via comando
*&---------------------------------------------------------------------*
*& Modulpool ZDIRECTORES*&*&---------------------------------------------------------------------**&*&*&---------------------------------------------------------------------*
program zdirectores.
data ok_code like sy-ucomm.
data: begin of zdirectores, director_id(10) type c, nombre(10) type c, nacion(2) type n, fec_nac type d, fec_mue type d,end of zdirectores.*&---------------------------------------------------------------------**& Module STATUS_0200 OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*module status_0200 output. set pf-status 'STATUS'. set titlebar 'T01'.
endmodule. " STATUS_0200 OUTPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0200 INPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*module user_command_0200 input. data fcode like ok_code.
fcode = ok_code. clear ok_code.
case fcode. when 'SAVE'. perform grabar_director using zdirectores. when 'BACK'. leave to screen 0. endcase.
endmodule. " USER_COMMAND_0200 INPUT
*&---------------------------------------------------------------------**& Form grabar_director*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** -->ZDIRECTORES text*----------------------------------------------------------------------*form grabar_director using zdirectores structure zdirectores. INSERT INTO zdirectores VALUES zdirectores. if sy-subrc = 0. message s000(fb) with 'Director ingresado con éxito'. clear zdirectores. else. message e000(fb) with 'Error ingreso director'. endif.
endform. "grabar_director
process before output. module status_0200.*process after input.
field zdirectores-director_id.field zdirectores-nombre.field zdirectores-nacion.field zdirectores-fec_nac.field zdirectores-fec_mue.
module user_command_0200.
SMARTFORMS
Ejercicio N° 1.
El jefe quiere el listado de los usuarios que hay en Sap y quiere imprimir la siguiente carta:
Santiago, 23 de Enero del 2006
LISTADO DE USUARIOS SAP
Empresa GlobalSap consulting, tiene los siguientes usuarios registrados en SAP
Codigo Usuario NombreJVASQUEZ Jaime VazquezCRUIZ Cristian RuizGGONZALEZ German GonzalezPTAPIA Pablo Tapia
Solución:
Vamos a la transacción SMARTFORM, creamos el smartform y definimos la tabla de entrada usuarios
En este ejemplo usaremos la ventana MAIN que se crea por defecto, acuérdense que el concepto de MAIN es el mismo que en el de los SAPSCRIPT.
A la ventana main le definiremos un texto llamado HEADER para colocar el texto de cabecera de la tabla.
1. Interface form.
2. TABLAS
3. Def. Tabla USUARIOS
Fíjate en el botón Lista de campos, ahí en el extremo inferior izquierdo, salen todos los campos visibles para programa smartform, para poner la fecha utilizaremos la variable de sistema DATE, fíjate que esto es drag & drop , que bonito no.
Crear texto, HEADER
De ahí simplemente le colocas el texto tal cual como en un editor.
1. Lista de campos
2. Lista de campos
3. variable de sistema DATE
4. drag & drop
Ahora hay que definir la tabla para la impresión de los usuarios:
Creamos tabla:
Lo que hay que definir es lo siguiente, la cantidad de columnas que tendrá,
Vamos a details
1. Details
Ojo con esto
Definimos las columnas, en este caso son 2, una para usuario y otra para nombre, ojo con los largos que tiene que ser igual al ancho de tabla.
Para trabajar con la tabla tenemos que definir un work area, que definimos en definiciones globales
Volvamos a la tabla
Work area para la tabla
1. Datos globales
Fíjate que las tablas tienen áreas paraCabecera: típico que aquí definimos el nombre de las columnas.Principal: las líneas se imprimen aquí.Pie: Ejemplo, impresión de los totales
pie,
Entonces creamos “Entrada en tabla, y definimos el tipo de linea
Fijate que en cada columna(CELL), ponemos un campo de la work area y eso es todo
Para que esto tengo sentido, hay que crear el programa ABAP de impresión, en este caso el YTEST_SMART, en la rutina siguiente se imprime:
*&---------------------------------------------------------------------**& Form print_data*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*form print_data.data:*smartforms related func_module_name type rs38l_fnam, control_parameters type ssfctrlop, output_options type ssfcompop. data: pa_form LIKE ssfscreen-fname .
pa_form = 'YTEST_SMART'.
output_options-tdnewid = 'X'. output_options-tdimmed = 'X'. output_options-tddelete = 'X'. control_parameters-no_dialog = ' '.
* determine the name of the generated function module for the SMartform CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME' EXPORTING formname = pa_form IMPORTING fm_name = func_module_name EXCEPTIONS no_form = 1 no_function_module = 2 OTHERS = 3.
* call the generated function module of the form CALL FUNCTION func_module_name EXPORTING control_parameters = control_parameters output_options = output_options user_settings = space TABLES usuarios = user_name_address_tab EXCEPTIONS formatting_error = 1 internal_error = 2 send_error = 3 user_canceled = 4 my_exception = 5 OTHERS = 6.
endform. "print_data
Lo ejecutamos y tah tan que bonito!!!!!!!!!!!!
Ojo que un smartform es una función(SE37), entonces aca le pasas el nombre del smartform y te pasa el nombre de la funcion. El nombre es del estilo
/1BCDWB/SF00000172
Aca ejecutamos la llamada al smartform como una función, le pasamos los parámetros de impresión y la tabla USUARIOS para imprimir
*&---------------------------------------------------------------------**& Report YTEST_SMART*&*&---------------------------------------------------------------------**&*&*&---------------------------------------------------------------------*
REPORT YTEST_SMART.
data USER_NAME_TAB like standard table of USUSERS.data USER_NAME_ADDRESS_TAB like standard table of USADDR3.
start-of-selection.
perform get_users. perform print_data.
*&---------------------------------------------------------------------**& Form get_users*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*form get_users.
CALL FUNCTION 'SUSR_USER_ADDRESS_READ_ARRAY' EXPORTING ALL_USERS = 'X'* IMPORTING* RETURNCODE = TABLES USER_NAME_TAB = user_name_tab* USER_ADDRESS_TAB = USER_NAME_ADDRESS_TAB = user_name_address_tab* EXCEPTIONS* INTERNAL_ERROR = 1* USER_NAME_TAB_IS_EMPTY = 2* OTHERS = 3 . IF SY-SUBRC <> 0.* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF.
endform. "get_users
*&---------------------------------------------------------------------**& Form print_data*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*form print_data.data:*smartforms related func_module_name type rs38l_fnam, control_parameters type ssfctrlop, output_options type ssfcompop. data: pa_form LIKE ssfscreen-fname .
pa_form = 'YTEST_SMART'.
output_options-tdnewid = 'X'. output_options-tdimmed = 'X'. output_options-tddelete = 'X'. control_parameters-no_dialog = ' '.
* determine the name of the generated function module for the SMartform CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME' EXPORTING formname = pa_form IMPORTING fm_name = func_module_name EXCEPTIONS no_form = 1 no_function_module = 2 OTHERS = 3.
* call the generated function module of the form CALL FUNCTION func_module_name EXPORTING control_parameters = control_parameters output_options = output_options user_settings = space TABLES usuarios = user_name_address_tab EXCEPTIONS formatting_error = 1 internal_error = 2 send_error = 3 user_canceled = 4 my_exception = 5 OTHERS = 6.
endform. "print_data