Search code examples
abapalvrtts

Create dynamic ABAP internal table


On selection screen, the user needs to insert a table name, and I need to get first 3 fields from that table and display them in an ALV for the output. What I understand from reading tutorials is that I need to call method cl_alv_table_create=>create_dynamic_table, but I don't know how to create the fieldcatalog.

DATA: t_newtable   TYPE REF TO data,
      t_fldcat     TYPE lvc_t_fcat,

CALL METHOD cl_alv_table_create=>create_dynamic_table
  EXPORTING
    it_fieldcatalog = t_fldcat
  IMPORTING
    ep_table        = t_newtable.

Solution

  • I assume that the table name which user enters is a data dictionary table (like SFLIGHT). If yes, then you can generate the field catalog as follows.


    data : it_tabdescr type abap_compdescr_tab,
         wa_tabdescr type abap_compdescr.
    data : ref_table_descr type ref to cl_abap_structdescr.
    
      ref_table_descr ?= cl_abap_typedescr=>describe_by_name( p_table ).
      it_tabdescr[] = ref_table_descr->components[].
      loop at it_tabdescr into wa_tabdescr.
        clear wa_fieldcat.
        wa_fieldcat-fieldname = wa_tabdescr-name .
        wa_fieldcat-datatype  = wa_tabdescr-type_kind.
        wa_fieldcat-inttype   = wa_tabdescr-type_kind.
        wa_fieldcat-intlen    = wa_tabdescr-length.
        wa_fieldcat-decimals  = wa_tabdescr-decimals.
        append wa_fieldcat to it_fieldcat.
      endloop.
    

    Here, "p_table" is the selection screen parameter containing the table name.