ABAP – Fill BAPI structures from SAP table structures dynamically

SAPDue to fact that BAPI structures uses different field names than standard SAP tables I used to apply a trick I’m going to present in this article – map BAPI fileds to SAP fields in a Z-table and fill BAPI structures dynamically during runtime

In this article we will use as an example BAPI structure and SAP table for material master global data

  • SAP table MARA
  • BAPI structures called BAPI_MARA and BAPI_MARAX (save flags)

At first we create a mapping table in the following format with some example data – it can be of course extended with further info you might find usefull, but we will use it in this simple format just to demonstrate the approach. Let’s call it Z_BAPIMAP

TABNAME FIELDNAME BAPIFIELD
MARA MSTAE PURCH_STATUS
MARA MATKL MATL_GROUP
MARA NTGEW NET_WEIGHT
MARA GEWEI UNIT_OF_WT
MARC MINBE REORDER_PT
MARC EISBE SAFETY_STK
MARC BSTMI MIN_LOT_SIZE
MARC BSTMA MAX_LOT_SIZE

When it comes to code filling the BAPI from SAP structures, you can encapsulate it to a nice class method, function module or a form – I’ll present a form/perform code.

FORM fill_bapi 
  USING i_source_line TYPE any
        i_tabname     TYPE tabname16
  CHANGING
        c_bapi        TYPE any
        c_bapix       TYPE any.

  DATA:
    lt_mapping TYPE TABLE OF z_bapimap.

  FIELD-SYMBOLS:
    <fs_bapimap>      TYPE z_bapimap,
    <fs_source_field> TYPE any,
    <fs_bapi_field>   TYPE any,
    <fs_bapi_fieldx>  TYPE any.

* The following SELECT command can be done 
* on global scope and here only global itab would be accessed
  SELECT * 
    INTO TABLE lt_mapping
    FROM z_bapimap
    WHERE tabname = i_tabname.

  LOOP AT lt_mapping ASSIGNING <fs_bapimap>.

    ASSIGN COMPONENT <fs_bapimap>-fieldname OF STRUCTURE i_source_line TO <fs_source_field>.
    CHECK <fs_source_field> IS ASSIGNED.

*   Uncomment the following line in case you don't want blank 
*   values to be sent to SAP
*   CHECK <fs_source_field> IS NOT INITIAL.   

    ASSIGN COMPONENT <fs_bapimap>-bapifield OF STRUCTURE c_bapi TO <fs_bapi_field>.
    ASSIGN COMPONENT <fs_bapimap>-bapifield OF STRUCTURE c_bapix TO <fs_bapi_fieldx>.
    CHECK <fs_bapi_field>  IS ASSIGNED AND
          <fs_bapi_fieldx> IS ASSIGNED.

    <fs_bapi_field>  = <fs_source_field>.
    <fs_bapi_fieldx> = 'X'.    

  ENDLOOP.

ENDFORM.

Now we can call our new FORM to fill a BAPI structure from a SAP structure:

FORM update_material
  USING i_mara TYPE mara.

  DATA:
    l_bapi_mara  TYPE bapi_mara,
    l_bapi_marax TYPE bapi_marax.

  PERFORM fill_bapi
    USING    i_mara
             'MARA'
    CHANGING l_bapi_bara
             l_bapi_marax.      

*  ... The rest of code for update material
*  i.e. Call the BAPI function module ...
*  ...and Rollback/Commit work :-)

ENDFORM.

Leave a Reply