557
Tutorials on SAP-ABAP Dictionary • Creating a Transparent Table • Creating a structure in ABAP Dictionary • Creating Search helps (Elementary and collective • Creating a secondary index) • Working with table maintenance generator • Creation of a Logical Database) • Creation of a View cluster • Row level locking of database tables • Creation of a table pool and pooled table Reports • PDF Viewer • Convert internal table data into HTML with out using Function Modules • Convert internal table data into HTML using Function Modules • Adding custom context menu in classical list • Dynamic Selection Screen (Drop downs, pushbuttons, radio buttons, icons)) • Creating Dynamic variant using table TVARV • Display images (like company logo) on the selection-screen • Custom Parameter-id Creation • Creating Dynamic Patterns • Scheduling a background job by triggering an event • Performance Tuning using Parallel Cursor • Creating a Transaction Variant • E-mailing the background jobs • ABAP Programming standards • ABAP Performance Tuning Checklist • Understanding SQL Trace • Changing the text "Sales Order" to "Billing Request" in the transactions VA01, VA02 and VA03 • Creation of a web service in SAP • Calling a web service in ABAP that validates an email id • Handling favorites in ABAP Workbench • Implementing events in Table Maintenance • Using Sorted table and Index while processing internal tables • Displaying Graphics using ABAP Program • The Features of ABAPTM New Editor - Part 2 • The Features of ABAPTM New Editor - Part 1

ABAP Tutorials

Embed Size (px)

DESCRIPTION

Screens are from SAP Application. Content is from www.

Citation preview

Page 1: ABAP Tutorials

Tutorials on SAP-ABAP

Dictionary• Creating a Transparent Table • Creating a structure in ABAP Dictionary • Creating Search helps (Elementary and collective • Creating a secondary index) • Working with table maintenance generator • Creation of a Logical Database) • Creation of a View cluster • Row level locking of database tables • Creation of a table pool and pooled table

Reports• PDF Viewer • Convert internal table data into HTML with out using Function Modules • Convert internal table data into HTML using Function Modules • Adding custom context menu in classical list • Dynamic Selection Screen (Drop downs, pushbuttons, radio buttons, icons)) • Creating Dynamic variant using table TVARV • Display images (like company logo) on the selection-screen • Custom Parameter-id Creation • Creating Dynamic Patterns • Scheduling a background job by triggering an event • Performance Tuning using Parallel Cursor • Creating a Transaction Variant • E-mailing the background jobs • ABAP Programming standards • ABAP Performance Tuning Checklist • Understanding SQL Trace • Changing the text "Sales Order" to "Billing Request" in the transactions VA01, VA02 and VA03 • Creation of a web service in SAP • Calling a web service in ABAP that validates an email id • Handling favorites in ABAP Workbench • Implementing events in Table Maintenance • Using Sorted table and Index while processing internal tables • Displaying Graphics using ABAP Program • The Features of ABAPTM New Editor - Part 2 • The Features of ABAPTM New Editor - Part 1 • Working with Menu Painter • Dynamic Variant in a report • Creating F1 helps with ease • Object oriented programming (OOP) explained with an example • Calling an RFC function module from one system to another • Updating Material Master long text (BASIC DATA TEXT, INSPECTION TEXT and INTERNAL COMMENT) • System debugging - Explained in detail • MESSAGE XXXX RAISING XXXX. What is this?

Page 2: ABAP Tutorials

• Differences between LSMW and BDC • ABAP Performance Standards • Create / Modify / Delete records in any table from CSV file • Download data from tables with user defined delimiters • Creation of a Number Range Object • Creation of a Dynamic Internal table • HR Infotype Creation • A real-time example on sending PDF file as an email (Complete program) • Developing a simple interactive report • Demo on Interactive reporting (One more example) • Downloading file on to the application server • Creating a Function Module • Creating a dynamic selection screen on a report • Displaying 3D Graphs in ABAP • Creating a Tabstrip on the selection screen • Dynamic SELECT statement • Downloading report output into Excel using OLE • Understanding ABAP Unit • Understanding "Checkpoint Group" • Understanding "Coverage Analyzer" • FTP file transfer in Background • Converting an XML file with many hierarchy levels to ABAP format

Dialog Programming• Table Control using wizard • Splitter Controls and Graphs • Text Edit Control Usage and Example • Displaying images on the screen • Working with Screen Painter • Demo on Tabstrips • Working with Checkbox • Demo using Table Control • Display Logo on Screen

BDC Programming• How to do BDC without writing BDC Program • Creating a simple database table using BDC • BDC recording from testing client to development client

Creation of Transparent Table

1. Enter the table name and press Create

Page 3: ABAP Tutorials

 

2. Enter the description, Delivery class and check on table maintenance allowed. Then click on the tab Fields.

Page 4: ABAP Tutorials

3. Enter the ZCHAR in fields tab and ZCHAR_DE in field type tab.

4. Double click on ZCHAR_DE. Then it will ask for Save. Press ‘YES”.

Page 5: ABAP Tutorials

 

5. Save it as a local object on pressing Local object button

 

Page 6: ABAP Tutorials

6. Now it will ask for the creation of the data element. Press Yes.

 

7. Click on the Field label tab and enter the lengths and descriptions accordingly.

Page 7: ABAP Tutorials

 

8. Then press Definition tab and enter the domain.

Page 8: ABAP Tutorials

9. Double click on that zchar_d to create domain, then it will ask for save before going next screen.

Press Yes. 

 

10. Save it as a local object.

Page 9: ABAP Tutorials

11. Now it will ask for domain creation. Press Yes.

Page 10: ABAP Tutorials

 

12. Give short description for that domain which you are creating. And mention the data type in data type field and length in no. characters field an press ENTER.

Page 11: ABAP Tutorials

13. Then press Ctrl+F3. It will ask for save before activation. Save it as a local Object.

 

Page 12: ABAP Tutorials

14. Press Enter.

 

15. Then the following screen appears. Press on back button.

Page 13: ABAP Tutorials

 

16. Press Ctrl+F3. You will get the following screen. Press Back button.

 

17. You will get the following screen.

Page 14: ABAP Tutorials

 

18. Create one more field ZNUM and give data element name as ZNUM_DE. And double click on ‘ZNUM_DE’

Page 15: ABAP Tutorials

 

19. Save it by pressing Yes.

 

20. Now it will ask for the data element creation. Press Yes.

 

Page 16: ABAP Tutorials

21. Give short description of the data element. And give the lengths and field labels accordingly in Field label tab.

 

22. Press on Definition tab and give the domain name in Domain field. Double click on ZNUM_D.

Page 17: ABAP Tutorials

 

23. It will ask for save. Press Yes.

 

24. Save it as a local Object.

Page 18: ABAP Tutorials

25. Now it asks for Domain creation. Press Yes.

 

26. Give short description in short text field. Enter the data type and no. characters, Press Enter.

Then Press on Activate button or Press Ctrl+F3. 

Page 19: ABAP Tutorials

 

27. Save this as a local object.

Page 20: ABAP Tutorials

28. Press enter.

Page 21: ABAP Tutorials

 

29. Now you will get the following screen. Press Back button.

Page 22: ABAP Tutorials

 

30. Activate the data element By pressing Activate button or Pressing Ctrl+F3.

Page 23: ABAP Tutorials

 

31. Press enter.

Page 24: ABAP Tutorials

 

32. Press Back button.

Page 25: ABAP Tutorials

33. Now we created two fields. And Data elements and Domain for these two fields.

Now we have to maintain the technical settings. Press on Technical settings button.

Page 26: ABAP Tutorials

 

34. Give the data class and size category of the table as per the requirement.

And press the back button. 

Page 27: ABAP Tutorials

35. Now activate the table by pressing the activate button or CTRL+F3.

Page 28: ABAP Tutorials

36. Press enter.

 

37. Now you will get the following screen.

Page 29: ABAP Tutorials

 

38. Now enter the data into table. Go to Utilitiesà Table contents à Create Entries.

Page 30: ABAP Tutorials

 

39. Now enter the data in the fields and Save it.

Page 31: ABAP Tutorials

 

40. You will get the following screen after clicking the Reset Button.

Page 32: ABAP Tutorials

41. Enter the data for the second entry into the table. 42. Save it and press reset.

Page 33: ABAP Tutorials

 

43. You will get the following screen.

Page 34: ABAP Tutorials

 

44.               Again enter the data for the third entry.

45.               Press save, Reset (Optional) and Back button.

Page 35: ABAP Tutorials

 

46.               Now you will get the following screen.

Page 36: ABAP Tutorials

 

47. To see the table contents go to Utilities à Table contents à Display. Or press Ctrl+Shift+F10.

Page 37: ABAP Tutorials

 

48. You will get the following screen.

Page 38: ABAP Tutorials

 

49. Press on run button or press F8. Now it will display the table contents.

Page 39: ABAP Tutorials

 

Now enjoy by creating tables on your own.

Creating a Structure in ABAP Dictionary

Go to transaction SE11 and select the radio button “Data type”. Enter a structure name starting with Y or Z. 

Page 40: ABAP Tutorials

Press create button. 

A pop-up screen appears with 3 different options. Select the radio button structure. 

 The screen will be displayed like this.

Provide the description and also components.

Page 41: ABAP Tutorials

Then press SAVE, CHECK and ACTIVATE.

Structure Created Successfully.

Creating Search Helps (Elementary and Secondary)

By Vikram Chellappa, Mouri Tech Solutions

Go To SE11 T-code.

 

Select the radio button of search help.

 

Provide the search help name. Select the create button. 

Page 42: ABAP Tutorials

 

Select ELEMENTARY search help.

 

Press Enter. 

Provide the short description, the selection method.

Provide the fields.

Page 43: ABAP Tutorials

Save it, Check It & Activate it.

Then execute it.

We can see the screen like this, and then press F4 in this page.

Page 44: ABAP Tutorials

Then press F4 View the output like this.

This is the output for elementary search help.

The Collective Search Help is like this. 

Page 45: ABAP Tutorials

Goto T-Code Se11.

Provide name. Select collective search help button.

Press enter.

Provide the Values

Page 46: ABAP Tutorials

Select include search help.

Then provide search help name, which is already define by the same fields.

Then save it, activate it & execute it. 

Page 47: ABAP Tutorials

Press F4 we can see the output like this.

 

Diff Between Elementary search helps & Collective search helps 

1) Elementary search helps describe a search path. The elementary search help must define where the data of the hit list should be read from (selection method), how the

Page 48: ABAP Tutorials

exchange of values between the screen template and selection method is implemented (interface of the search help) and how the online input help should be defined (online behavior of the search help).

2) Collective search helps combine several elementary search helps. Collective search help thus can offer several alternative search paths.

3) An elementary search help defines the standard flow of an input help.

4) A collective search help combines several elementary search helps. The user can thus choose one of several alternative search paths with collective search help.

5) A collective search help comprises several elementary search helps. It combines all the search paths that are meaningful for a field.

6) Both elementary search helps and other search helps can be included in a collective search help. If other collective search helps are contained in collective search help, they are expanded to the level of the elementary search helps when the input help is called.

Creating a secondary index

There are two types of indexes: Primary index and secondary index. Primary index is automatically created using the primary keys defined. 

Secondary index could be created as per the user requirement. This article discusses about creating a secondary index. 

Go to transaction SE11. 

Page 49: ABAP Tutorials

 

For our demo purpose, we have considered the table ZAUTHOR. 

To know if there are any secondary indexes available, click on Goto à Indexes

 

Following popup appears:

Page 50: ABAP Tutorials

 

From the above screenshot, it is evident that there are no secondary indexes already created. 

Click on Create à Create Index 

 

Enter the name of the index. 

 

Fill in the details – Short description and the fields in the index. 

Page 51: ABAP Tutorials

 

Save and activate. 

Now you can observe the index created above in the list now:

 

Page 52: ABAP Tutorials

Maximum number of secondary indexes we can have are 9.

How to make SELECT statement to make use of any particular secondary index?

Secondary Indexes

Consider the following example:SELECT * FROM SPFLI  %_HINTS ORACLE 'INDEX("SPFLI" "SPFLI~001")'.......ENDSELECT.

In the above example, 001 is the secondary index of the table SPFLI. It's a well-known fact that the efficient way of retrieving data from the database tables is by using secondary indexes. Many database vendors provide the optimizer hints for the same. From SAP® v4.5, optimizer hints can be provided by the %_HINTS parameter. This is dependent on the database systems that support optimizer hints. The point to be noted here is these optimizer hints are not standardized by the SQL standards. Each database vendor is free to provide the optimizer hints.Now to know which index to use for our table:1. Go to SE11 and there specify the table name2. Now from the menu, goto --> indexes3. select the required index.

Now suppose that the identifier 001 represents a non-unique secondary index comprising of the columns CITYFROM and CITYTO. The index name should be defined as:

 <tablename>~<Index Identifier>like SPFLI~001 in the above example.

The sequence of fields in the WHERE condition is of no relevance in using this optimizers index. If you specify hints incorrectly, ABAPTM ignores them but doesn't return a syntax error or runtime error.The code was written in R/3 4.6C.

Code

Consider the following example:

REPORT Suresh_test.

TABLES: spfli.

DATA : t_spfli LIKE spfli OCCURS 0 WITH HEADER LINE.

SELECT * FROM spfli  INTO TABLE t_spfli  %_HINTS ORACLE 'INDEX("SPFLI" "SPFLI~001")'.

LOOP AT t_spfli.  WRITE :/ t_spfli.ENDLOOP.

Working with Table Maintenance Generator

Page 53: ABAP Tutorials

Go to SE11 and enter the Z table name for which the table maintenance generator has to be generated. Click on Change. 

 

Click on Utilities à Table Maintenance Generator

 

Page 54: ABAP Tutorials

 

Enter Authorization group (For e.g. &NC&)Function group (go to SE80 for creating function group)

You can select either one step or two step. Assign Screen numbers (To assign Screen numbers click on the button 'Find Scr no'. It will propose screen no's)

Then Create. Save 

Single step: Only overview screen is created i.e. the Table Maintenance Program will have only one screen where you can add, delete or edit records. 

Two step: Two screens namely the overview screen and Single screen are created. The user can see the key fields in the first screen and can further go on to edit further details. 

You can now create TCode for the table maintenance generator. Enter the TCode to be created and click on Create.

Creation of a Logical Database

Go to transaction 'SE36' or 'SLDB'. 

Page 55: ABAP Tutorials

 

Enter the logical database name as shown above . 

 

If we are using Logical Database for HR purpose, we should check the check Box “Info types (HR only). Press CREATE Button as shown above. 

It would prompt for package name and workbench request . 

Page 56: ABAP Tutorials

 

On pressing Save button, following screen appears, prompting for the details of the root node. 

 

Click on create button. Following screen appears:

Page 57: ABAP Tutorials

Now enter the details of all the tables under LFA1 (as shown below).  

 

Click on create Button. 

Page 58: ABAP Tutorials

 

Click on create Button. 

 

 

Now create a Node with hierarchically under LFB1.

Page 59: ABAP Tutorials

 

 

The above screen displays the LDB structure as per our requirements. 

We can maintain search help for the fields for the tables defined in structure. 

Page 60: ABAP Tutorials

Select “Transaction with parameters (Parameter transaction)”

Page 61: ABAP Tutorials

 

Page 62: ABAP Tutorials

Click on save. 

Now you can create the table entries through the transaction created above.

For our demo purposes, let us provide search help for MATNR and WERKS. 

Page 63: ABAP Tutorials

 

Let us use the standard search help available for MATNR and WERKS.  

Page 64: ABAP Tutorials

The currency and quantity fields are automatically maintained here. 

Page 65: ABAP Tutorials

 

Go back to the main screen 

Page 66: ABAP Tutorials

 

Here we can design our own selection screen as per the requirements. 

 

Page 67: ABAP Tutorials

Automatically created include with naming convention. 

 

Here by using above marked statement we can create Dynamic selection screen for different tables as per the requirements.

Creation of a Logical Database

...Previous

 

Page 68: ABAP Tutorials

Database program (with some includes) are automatically created upon the creation of logical database: 

Go back to the main screen.

Here we can maintain texts for select-options and parameters. 

Page 69: ABAP Tutorials

 

Navigate to the main screen:

Page 70: ABAP Tutorials

 

Here we can maintain documentation for our created Z logical database.  

Page 71: ABAP Tutorials

 

 

Page 72: ABAP Tutorials

 

Click on Display.

Page 73: ABAP Tutorials

Creation of a View cluster

By T.N.Swapna

View Cluster

A view cluster is the set of objects, such as views, reports or tables, which belong to one business function. The data can be arranged either hierarchically or non-hierarchically in view cluster. A view-cluster transaction edits the complex cross-table data in a view cluster. The transaction navigation box shows the complex business object with its components or sub objects.

Example:

Let us create a View Cluster on Material Details. The view cluster would include three tables namely, MARA, MARC and MARD. We need to create maintenance views for each of these tables.

Maintenance view for Table MARA

To create maintenance view for the table MARA follow the procedure below. Go to transaction SE11. Give a view name say ZMM_V_MARA and click on ‘Create’. Give a short description, enter the table name as MARA and click on the tab View fields.

Page 74: ABAP Tutorials

By default all the key fields would be added. We can add more fields by clicking on the button Table fields.

Now Save and activate the view.

Maintenance view for Table MARC

Follow the same procedure as above. In the Tab View fields, give ‘S’ in the column ‘P’ for the fields MANDT and MATNR as shown in the screen shot below:

Page 75: ABAP Tutorials

This is because the fields MANDT and MATNR would be filled in the view for MARA and thus they act as subsets and appear as header data when we create entries in view cluster.

Maintenance view for Table MARD

Follow the same procedure as above. In the Tab View fields, give ‘S’ in the column ‘P’ for the fields MANDT, MATNR and WERKS as shown in the screen shot below:

This is because the fields MANDT, MATNR and WERKS would be filled in the view for MARC and thus they act as subsets and appear as header data when we create entries in view cluster.

Table Maintenance Generator for ZMM_V_MARA

Now, for each view we need to create a table maintenance generator, which has to be done as follows:

Page 76: ABAP Tutorials

The table maintenance screen appears. Here give the details as in the screen shot below. This table maintenance is for the view ZMM_V_ MARA.

Before creating a table maintenance generator, create a function group say ZFG_MATERIAL from the transaction SE80. After the function group is successfully created, enter the function group name as

Page 77: ABAP Tutorials

shown in the screen shot. Also select Maintenance type as ‘One Step’ and give the Maintenance Screen no. as ‘1’ in the Overview screen and click on the button ‘Create’.

Similarly, create the Table maintenance Generators for the views ZMM_V_MARC and ZMM_V_MARD. The screen shots for these views would be as follows:

Table Maintenance Generators for ZMM_V_MARC and ZMM_V_MARD

 

Page 78: ABAP Tutorials

Note that the Overview screen numbers would change for each view. It would be ‘2’ for the view ZMM_V_MARC and it would be ‘3’ for the view ZMM_V_MARD.

Creating view cluster

The pre-requisites for creating the View Cluster are now ready. Go to transaction SE54 and select the button ‘Edit View Cluster’. Enter the view cluster name as say ‘ZMM_VC_MATERIAL’ and click on ‘Create’.

Page 79: ABAP Tutorials

An information message would pop up saying

Continue by pressing ‘Enter’. The following screen appears. Give a short description and click on ‘Object Structure’ as shown in the screen shot below:

Page 80: ABAP Tutorials

On Clicking the ‘Object Structure’ the following screen appears. Select the ‘New Entries’ button to enter the maintenance views created to form a cluster.

Enter the values as shown below:

The entries would be entered in a hierarchical manner. The short text is the description of the view. The ‘Predecess’ column specifies the predecessor of that view. So in this case, the predecessor of ZMM_V_MARA is ZMM_V_MARA itself. The predecessor of ZMM_V_MARC is ZMM_V_MARA and the predecessor of ZMM_V_MARD is ZMM_V_MARC. The ‘DEP’ column explains whether the entry is a Header entry or a Dependent entry. It is ‘R’ for the view ZMM_V_MARA, because it is a header entry and does not depend on any other view. Whereas, it is ‘S’ for ZMM_V_MARC and ZMM_V_MARD, because ZMM_V_MARC is dependent on ZMM_V_MARA and ZMM_V_MARD is dependent on ZMM_V_MARC. The column ‘POS’ specifies the sequence of the views. In the column ‘Start’ select the radio button against the entry for ZMM_V_MARA as it comes first in the hierarchy.

After entering the above entries, press ‘Enter’. Three pop-ups for each view would appear as shown below. Proceed further by clicking on ‘Enter’ key.

Page 81: ABAP Tutorials

Now select each line and click on ‘Field-dependence’ button. A pop-up appears saying ‘Field dependencies successfully generated’.

Generate the field dependence for the views ZMM_V_MARC and ZMM_V_MARD in the same way. Now, save the entries and go back to ‘Header Entry’ folder. Activate the view cluster. A pop-up appears as shown below. Click on ‘Yes’.

Page 82: ABAP Tutorials

The view cluster is now created successfully.

Note:

1.       The view cluster can be created on the tables whose data has to be stored in a hierarchical manner.

2.       One has to check whether proper foreign key relationships are maintained between the tables appearing in the cluster. Sometimes while generating the Field-dependencies, errors may occur if the foreign keys are not maintained properly. 

Testing the View Cluster

From the initial screen of the transaction ‘SE54’ give the view cluster name and click on ‘Test’. 

 

Since we have created the view cluster on standard tables MARA, MARC and MARD we observe that all the existing entries would appear. The screen shot below shows all the existing entries of the table MARA. In order to see the corresponding Plant details for the material, just select an entry and double click on Plant details as shown below. 

Page 83: ABAP Tutorials

 

The plant details would appear. In the same way for the corresponding storage location details, select an entry and double click on Storage details as shown below. 

 

In the above screen shot the material selected in the Material details view would appear as a header entry. The storage location details are as follows: 

 

In the above screen shot the material selected in the Material details view and the plant selected in the Plant details view would appear as header entry.

Page 84: ABAP Tutorials

Row level locking of database table

By Swetabh Shukla, Infosys Technologies

Normally if a person opens table maintenance generator and tries to maintain the table, no one else can maintain the same table at the same time. This is because of table level lock by default in SAP. Only one user can maintain any table at a time through SM30 or any transaction that calls table maintenance generator. In the tutorial below we will see how to remove table level lock and apply row level lock. This way any number of users can modify the table at same time. But any particular row can be modified by only one user at a time. We will create a transaction for this purpose. The transaction will call our custom report. This custom report will call the table maintenance generator of the table after deleting table level lock. 

In current example let’s create following: 

Report: ZREP_SHUKS3

Transaction: ZTEST_SHUKS3

Table: ZTEST_SHUKS3 with table maintenance generator. 

Using transaction ZTEST_SHUKS3 we will delete the table level lock and put row level lock so that multiple users can maintain table at same time. Rows locked by one user will not be editable by other user. 

1.       Create table ZTEST_SHUKS3. 

2.       Create table maintenance generator for the table. 

Page 85: ABAP Tutorials

We will make single screen maintenance for this table. Save it. So finally we have table maintenance code automatically generated in function group ZTEST_SHUKS3. 

3.       Create lock object EYTSS_E433SH in SE11. Give it name as EZTEST_SHUKS3. 

Page 86: ABAP Tutorials

 

 

Now save and activate the Lock object. SAP creates two function modules corresponding to lock object for enqueue and dequeue of the table. 

 

4.       Now create a report ZREP_SHUKS3 and transaction code ZTEST_SHUKS3 to call this report. This tcode will call table maintenance generator of table ZTEST_SHUKS3 . 

Page 87: ABAP Tutorials

5.       Normally if a person opens table maintenance generator and tries to maintain the table, no one else can maintain table at the same time. This is because of table level lock by default in SAP. Only one user can maintain any table at a time. In report ZREP_SHUKS3 we will delete the table level lock and put row level lock so that multiple users can maintain table at same time. Rows locked by one user will not be editable by other user. Check the report and comments given below. 

*&---------------------------------------------------------------------**& Report  ZREP_SHUKS3*&*&---------------------------------------------------------------------*& Author : Swetabh Shukla*& Date : 05/22/2009*& Description : To delete table level lock from table.*&---------------------------------------------------------------------*REPORT  zrep_shuks3.

**Selection range for view maintenanceDATA:  BEGIN OF selekttab OCCURS 1.         "Selektionsbereich        INCLUDE STRUCTURE vimsellist.DATA: END OF selekttab,

**Table of inactive CUA functions for view maintenanceBEGIN OF excl_cua_funct OCCURS 1.    "inaktive CUA-Fkt bei View-Pflege        INCLUDE STRUCTURE vimexclfun.DATA: END OF excl_cua_funct.

DATA: lt_enq_del TYPE STANDARD TABLE OF seqg3,      lt_enq_read TYPE STANDARD TABLE OF seqg7,      lw_enq_read TYPE seqg7,      lw_enq_del TYPE seqg3,      lv_subrc TYPE sy-subrc.

*Read all the lock details in systemCALL FUNCTION 'ENQUE_READ2'  EXPORTING    gclient = sy-mandt    gname   = ' '    guname  = '*'  TABLES    enq     = lt_enq_read.

*We will search entry for table level lock for our tableLOOP AT lt_enq_read INTO lw_enq_read WHERE gname EQ 'RSTABLE' AND   garg CS 'ZTEST_SHUKS3'.  MOVE-CORRESPONDING lw_enq_read TO lw_enq_del.  APPEND lw_enq_del TO lt_enq_del.ENDLOOP.

*Delete table level lock entry for our tableCALL FUNCTION 'ENQUE_DELETE'  EXPORTING    check_upd_requests = 1  IMPORTING    subrc              = lv_subrc

Page 88: ABAP Tutorials

  TABLES    enq                = lt_enq_del.

*Now call the table maintenace generator.CALL FUNCTION 'VIEW_MAINTENANCE_CALL'  EXPORTING    action               = 'U'    view_name            = 'ZTEST_SHUKS3'    show_selection_popup = 'X'  TABLES    dba_sellist          = selekttab    excl_cua_funct       = excl_cua_funct.

6. Just one more change in table maintenance screen. Now open table maintenance function group(ZTEST_SHUKS3) in SE80.We know for table maintenance SAP automatically creates code in the function group. Now we will make some modification in that existing code to change the behavior. Open the screen you created through table maintenance and add one module. 

 

Open the screen 0001 and add one module in PBO of the screen as shown in figure below. 

Page 89: ABAP Tutorials

Check the code below to be added in the module m_change_locking. 

MODULE m_change_locking OUTPUT.*Call the function module corresponding to the lock object we created  CALL FUNCTION 'ENQUEUE_EZTEST_SHUKS3'    EXPORTING      matnr          = ztest_shuks3-matnr      werks          = ztest_shuks3-werks    EXCEPTIONS      foreign_lock   = 1      system_failure = 2      OTHERS         = 3.  IF sy-subrc NE 0.* row is locked..hence gray..    LOOP AT SCREEN.      screen-input = 0.      MODIFY SCREEN.    ENDLOOP.  ENDIF.ENDMODULE.                 " m_change_locking  OUTPUT 

7. Now we are ready for testing. Call the transaction once and make some entries in table. In below screenshot I have entered some random values. Since we have not maintained any check tables etc, so values may be invalid. That can be taken care in real scenario. 

Page 90: ABAP Tutorials

 

Save data. 

Let’s call two sessions of the transaction ZTEST_SHUKS3.

Session 1   

In first session we will call the transaction ZTEST_SHUKS3 and try to open some existing values for table maintenance. 

 

Let’s open an existing value material = MAT1 and Plant = 0678. 

Page 91: ABAP Tutorials

 

So the entry opens in change mode. 

Now open a second session of the transaction and see. Now the same material and plant combination can not be changed by any other user or session. 

Session 2  

Open transaction ZTEST_SHUKS3 

 

Page 92: ABAP Tutorials

So we can see that our transaction is able to achieve a row level locking and has removed table level locking.

Creation of a table pool and pool table

By Kiran Kumar Kandakatla, Intelligroup

In this Tutorial, we create a Table pool first and then create/ (add a table to Table pool) a Pooled Table.  

Step 1:

Go to transaction SE11. Go to Utilities à Other Dictionary Objects

 

Page 93: ABAP Tutorials

Step 2:

Select Radio button Table pool/Cluster Give table Pool Name: ZTBL_POOL.

Then press F5 or choose Create.  

 

Step 3:

Then Select Radio button Table Pool. Press Enter.  

Page 94: ABAP Tutorials

Step 4:

Then you go to maintain Poll Screen there give Short Description.  

 

Step 5:

Then go to Technical settings.  

Page 95: ABAP Tutorials

 

Step 6:

In the “Maintain technical Settings” screen Provide Size category.

Save and activate the table Pool. Go back to SE11.  

Step 7:

Page 96: ABAP Tutorials

Go to SE11 ABAP Dictionary: Initial Screen.

Create a Z table.  

 

Step 8:

Maintain Delivery and Maintenance attributes for the Z table.  

Page 97: ABAP Tutorials

 

Add fields to the Z table.

Maintain Technical settings and Enhancement Category.  

 

Step 9:  

Then Go to Extrasà Change table category

Page 98: ABAP Tutorials

 

Step 10:

Choose Table type.

In our Example it is Pooled table.  

 

Step 11:

Go back to Delivery and Maintenance tab and provide Pool/Cluster value.

Page 99: ABAP Tutorials

 

We have successfully created Table pool and Pooled table.

PDF Viewer

By Sai Kumar B, Enteg

This Program helps you to view any output in PDF viewer as shown below. It’s very simple to understand. Just convert OFT data into PDF as below.

*&---------------------------------------------------------------------**& Report  ZSAP_PDF_VIEWER_DEMO_2*&*&---------------------------------------------------------------------*

REPORT  ZSAP_PDF_VIEWER.

DATA: LT_PDF TYPE TABLE OF TLINE,      LS_PDF LIKE LINE OF LT_PDF,      LV_URL TYPE CHAR255,      PDF_FSIZE TYPE  I,      LV_CONTENT  TYPE XSTRING,      LT_DATA TYPE STANDARD TABLE OF X255.

DATA : L_JOB_OUTPUT_INFO TYPE SSFCRESCL.DATA : LS_CONTROL_PARAM  TYPE SSFCTRLOP.

DATA : G_HTML_CONTAINER TYPE REF TO CL_GUI_CUSTOM_CONTAINER,       G_HTML_CONTROL   TYPE REF TO CL_GUI_HTML_VIEWER.

DATA : P_VBELN TYPE  VBELN_VL.

FIELD-SYMBOLS <FS_X> TYPE X.

Page 100: ABAP Tutorials

INITIALIZATION.LS_CONTROL_PARAM-GETOTF = 'X'.LS_CONTROL_PARAM-NO_DIALOG = 'X'.

START-OF-SELECTION.

  CALL FUNCTION '/1BCDWB/SF00000034' EXPORTING*    ARCHIVE_INDEX              =*   ARCHIVE_INDEX_TAB          =*   ARCHIVE_PARAMETERS         =     CONTROL_PARAMETERS         = LS_CONTROL_PARAM     P_VBELN                    = P_VBELN*   MAIL_APPL_OBJ              =*   MAIL_RECIPIENT             =*   MAIL_SENDER                =*   OUTPUT_OPTIONS             =*   USER_SETTINGS              = 'X' IMPORTING*      DOCUMENT_OUTPUT_INFO  = L_DOCUMENT_OUTPUT_INFO       JOB_OUTPUT_INFO       = L_JOB_OUTPUT_INFO*      JOB_OUTPUT_OPTIONS    = L_JOB_ OUTPUT_OPTIONS EXCEPTIONS    FORMATTING_ERROR           = 1    INTERNAL_ERROR             = 2    SEND_ERROR                 = 3    USER_CANCELED              = 4    OTHERS                     = 5           .  IF SY-SUBRC  <> 0.* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.  ENDIF.

  CALL FUNCTION 'CONVERT_OTF'    EXPORTING      FORMAT                = 'PDF'    IMPORTING      BIN_FILESIZE          = PDF_FSIZE    TABLES      OTF                   = L_JOB_OUTPUT_INFO-OTFDATA      LINES                 = LT_PDF    EXCEPTIONS      ERR_MAX_LINEWIDTH     = 1      ERR_FORMAT            = 2      ERR_CONV_NOT_POSSIBLE = 3      OTHERS                = 4.

* convert pdf to xstring string  LOOP AT LT_PDF INTO LS_PDF.    ASSIGN LS_PDF TO <FS_X> CASTING.    CONCATENATE LV_CONTENT <FS_X> INTO LV_CONTENT IN BYTE MODE.  ENDLOOP.

  CALL SCREEN 100.

Page 101: ABAP Tutorials

*&---------------------------------------------------------------------**&      Module  STATUS_0100  OUTPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*MODULE STATUS_0100 OUTPUT.*  SET PF-STATUS 'xxxxxxxx'.*  SET TITLEBAR 'xxx'.

  CREATE OBJECT G_HTML_CONTAINER    EXPORTING      CONTAINER_NAME = 'PDF'.

  CREATE OBJECT G_HTML_CONTROL    EXPORTING      PARENT = G_HTML_CONTAINER.

* Convert xstring to binary table to pass to the LOAD_DATA method  CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'    EXPORTING      BUFFER     = LV_CONTENT    TABLES      BINARY_TAB = LT_DATA.

* Load the HTML  CALL METHOD G_HTML_CONTROL->LOAD_DATA(     EXPORTING       TYPE         = 'application'       SUBTYPE      = 'pdf'     IMPORTING       ASSIGNED_URL         = LV_URL     CHANGING       DATA_TABLE           = LT_DATA     EXCEPTIONS       DP_INVALID_PARAMETER = 1       DP_ERROR_GENERAL     = 2       CNTL_ERROR           = 3       OTHERS               = 4 ).

* Show it  CALL METHOD G_HTML_CONTROL->SHOW_URL( URL = LV_URL    IN_PLACE = 'X' ).

ENDMODULE.                 " STATUS_0100  OUTPUT*&---------------------------------------------------------------------**&      Module  USER_COMMAND_0100  INPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*MODULE USER_COMMAND_0100 INPUT.

ENDMODULE.                 " USER_COMMAND_0100  INPUT

Page 102: ABAP Tutorials

Convert internal table data into HTML format without using Function Modules

By Suman Kumar Chinnam

The output of this Tutorial is same as previous one but in this we are not using any function modules to convert internal table data to HTML table.

*&----------------------------------------------------------------**& Report YTEST_TABLE_HTML1*&

Page 103: ABAP Tutorials

*&----------------------------------------------------------------*REPORT ytest_table_html1.*----------------------------------------------------------------** D A T A D E C L A R A T I O N*----------------------------------------------------------------**-HTML TableDATA: t_html TYPE STANDARD TABLE OF w3html WITH HEADER LINE, " Html Table*- Declare Internal table and Fieldcatalog it_flight TYPE STANDARD TABLE OF sflight WITH HEADER LINE, " Flights Details it_fcat TYPE lvc_t_fcat WITH HEADER LINE. " Fieldcatalog*-VariablesDATA: v_lines TYPE i, v_field(40).*-FieldsymbolsFIELD-SYMBOLS: <fs> TYPE ANY.*----------------------------------------------------------------** S T A R T - O F - S E L E C T I O N*----------------------------------------------------------------*START-OF-SELECTION. SELECT * FROM sflight INTO TABLE it_flight UP TO 20 ROWS.*----------------------------------------------------------------** E N D - O F - S E L E C T I O N*----------------------------------------------------------------*END-OF-SELECTION.*-Fill the Column headings and Properties* Field catalog is used to populate the Headings and Values of * The table cells dynamically CALL FUNCTION 'LVC_FIELDCATALOG_MERGE' EXPORTING i_structure_name = 'SFLIGHT' CHANGING ct_fieldcat = it_fcat[] EXCEPTIONS inconsistent_interface = 1 program_error = 2. DELETE it_fcat WHERE fieldname = 'MANDT'. t_html-line = '<html>'. APPEND t_html. CLEAR t_html. t_html-line = '<thead>'. APPEND t_html. CLEAR t_html. t_html-line = '<tr>'. APPEND t_html. CLEAR t_html. t_html-line = '<td><h1>Flights Details</h1></td>'. APPEND t_html. CLEAR t_html. t_html-line = '</tr>'.

Page 104: ABAP Tutorials

APPEND t_html. CLEAR t_html. t_html-line = '</thead>'. APPEND t_html. CLEAR t_html. t_html-line = '<table border = "1">'. APPEND t_html. CLEAR t_html. t_html-line = '<tr>'. APPEND t_html. CLEAR t_html.*-Populate HTML columns from Filedcatalog LOOP AT it_fcat. CONCATENATE '<th bgcolor = "green" fgcolor = "black">' it_fcat-scrtext_l '</th>' INTO t_html-line. APPEND t_html. CLEAR t_html. ENDLOOP. t_html-line = '</tr>'. APPEND t_html. CLEAR t_html. DESCRIBE TABLE it_fcat LINES v_lines.*-Populate HTML table from Internal table data LOOP AT it_flight. t_html-line = '<tr>'. APPEND t_html. CLEAR t_html.*-Populate entire row of HTML table Dynamically*-With the Help of Fieldcatalog. DO v_lines TIMES. READ TABLE it_fcat INDEX sy-index. CONCATENATE 'IT_FLIGHT-' it_fcat-fieldname INTO v_field. ASSIGN (v_field) TO <fs>. t_html-line = '<td>'. APPEND t_html. CLEAR t_html. t_html-line = <fs>. APPEND t_html. CLEAR t_html. t_html-line = '</td>'. APPEND t_html. CLEAR t_html. CLEAR v_field. UNASSIGN <fs>. ENDDO. t_html-line = '</tr>'. APPEND t_html. CLEAR t_html. ENDLOOP. t_html-line = '</table>'. APPEND t_html. CLEAR t_html.*-Download the HTML into frontend CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = 'C:\Flights.htm'

Page 105: ABAP Tutorials

TABLES data_tab = t_html EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.*-Display the HTML file CALL METHOD cl_gui_frontend_services=>execute EXPORTING document = 'C:\Flights.htm' operation = 'OPEN' EXCEPTIONS cntl_error = 1 error_no_gui = 2 bad_parameter = 3 file_not_found = 4 path_not_found = 5 file_extension_unknown = 6 error_execute_failed = 7 synchronous_failed = 8 not_supported_by_gui = 9 OTHERS = 10. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.

Result:   

Page 106: ABAP Tutorials

Convert internal table data into HTML format using Function Modules

By Suman Kumar Chinnam

Following Function Modules are used to convert internal table data to HTML Table.

1. WWW_ITAB_TO_HTML_HEADERS is used to populate column headings. 2. WWW_ITAB_TO_HTML_LAYOUT is used to populate column cell properties.

3. WWW_ITAB_TO_HTML is used to convert internal table data to HTML.

Page 107: ABAP Tutorials

*&---------------------------------------------------------------------**& Report YTEST_TABLE_HTML*&*&---------------------------------------------------------------------*REPORT ytest_table_html.*---------------------------------------------------------------------** T Y P E S D E C L A R A T I O N*---------------------------------------------------------------------*TYPES:BEGIN OF ty_sflight, carrid TYPE s_carr_id, " Airline Code connid TYPE s_conn_id, " Connection Number fldate TYPE s_date, " Flight Date price TYPE s_price, " AirFare currency TYPE s_currcode, " Currency END OF ty_sflight.*-ALL related DeclarationsDATA: t_header TYPE STANDARD TABLE OF w3head WITH HEADER LINE, "Header t_fields TYPE STANDARD TABLE OF w3fields WITH HEADER LINE, "Fields t_html TYPE STANDARD TABLE OF w3html, "Html wa_header TYPE w3head, w_head TYPE w3head.DATA: it_sflight TYPE TABLE OF ty_sflight, " Flights Details it_fcat TYPE lvc_t_fcat WITH HEADER LINE. " Fieldcatalog*---------------------------------------------------------------------** S T A R T - O F - S E L E C T I O N*---------------------------------------------------------------------*START-OF-SELECTION. SELECT * FROM sflight INTO CORRESPONDING FIELDS OF TABLE it_sflight UP TO 20 ROWS.*---------------------------------------------------------------------** E N D - O F - S E L E C T I O N*---------------------------------------------------------------------*END-OF-SELECTION.*-Populate Fieldcatalog it_fcat-coltext = 'Airline Code'. APPEND it_fcat. it_fcat-coltext = 'Connection Number'. APPEND it_fcat. it_fcat-coltext = 'Flight date'. APPEND it_fcat. it_fcat-coltext = 'Airfare'. APPEND it_fcat. it_fcat-coltext = 'Currency'. APPEND it_fcat.*-Fill the Column headings and Properties LOOP AT it_fcat. w_head-text = it_fcat-coltext.*-Populate the Column Headings CALL FUNCTION 'WWW_ITAB_TO_HTML_HEADERS' EXPORTING field_nr = sy-tabix text = w_head-text fgcolor = 'black'

Page 108: ABAP Tutorials

bgcolor = 'green' TABLES header = t_header.*-Populate Column Properties CALL FUNCTION 'WWW_ITAB_TO_HTML_LAYOUT' EXPORTING field_nr = sy-tabix fgcolor = 'black' size = '3' TABLES fields = t_fields. ENDLOOP.*-Title of the Display wa_header-text = 'Flights Details' . wa_header-font = 'Arial'. wa_header-size = '2'.*-Preparing the HTML from Intenal Table REFRESH t_html. CALL FUNCTION 'WWW_ITAB_TO_HTML' EXPORTING table_header = wa_header TABLES html = t_html fields = t_fields row_header = t_header itable = it_sflight.*-Download the HTML into frontend CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = 'C:\Flights.htm' TABLES data_tab = t_html EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

Page 109: ABAP Tutorials

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.*-Display the HTML file CALL METHOD cl_gui_frontend_services=>execute EXPORTING document = 'C:\Flights.htm' operation = 'OPEN' EXCEPTIONS cntl_error = 1 error_no_gui = 2 bad_parameter = 3 file_not_found = 4 path_not_found = 5 file_extension_unknown = 6 error_execute_failed = 7 synchronous_failed = 8 not_supported_by_gui = 9 OTHERS = 10. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.

Result: 

Page 110: ABAP Tutorials

Adding custom context menu in classical list

By Joyjit Ghosh, IBM India

*&---------------------------------------------------------------**& Report Z_CONTEXT_MENU_DEMO*&*&---------------------------------------------------------------**& published at SAPTechnical.COM*&*&---------------------------------------------------------------*REPORT z_context_menu_demo.* Table declarationDATA: i_vbak TYPE STANDARD TABLE OF vbak INITIAL SIZE 0, i_vbap TYPE STANDARD TABLE OF vbap INITIAL SIZE 0.* Workarea declarationDATA: w_vbak TYPE vbak, w_vbap TYPE vbap.START-OF-SELECTION.* Set custom status SET PF-STATUS 'BASIC'.* Fetch header data SELECT * FROM vbak INTO TABLE i_vbak UP TO 50 ROWS. IF sy-subrc = 0.* Fetch line item data SELECT * FROM vbap INTO TABLE i_vbap FOR ALL ENTRIES IN i_vbap WHERE vbeln = i_vbap-vbeln. CHECK sy-subrc = 0.* Display basic list LOOP AT i_vbak INTO w_vbak. FORMAT COLOR COL_HEADING. WRITE : /10 w_vbak-vbeln, 20 w_vbak-erdat, 35 w_vbak-erzet, 55 w_vbak-ernam. HIDE: w_vbak-vbeln. ENDLOOP. ENDIF.AT USER-COMMAND.* Handle user command CASE sy-ucomm. WHEN 'DETAIL'. CHECK NOT w_vbak IS INITIAL.* Display detail list LOOP AT i_vbap INTO w_vbap WHERE vbeln = w_vbak-vbeln. FORMAT COLOR COL_HEADING. WRITE : /10 w_vbap-vbeln, 25 w_vbap-posnr, 35 w_vbap-matnr, 55 w_vbap-matwa. ENDLOOP.

Page 111: ABAP Tutorials

WINDOW STARTING AT 20 20 ENDING AT 120 110. ENDCASE.*&---------------------------------------------------------------**& Form on_ctmenu_request*&---------------------------------------------------------------** Creation of custom context menu- It is called dynamically* by ABAP runtime*----------------------------------------------------------------** -->L_MENU Handle for context menu*----------------------------------------------------------------*FORM on_ctmenu_request USING l_menu TYPE REF TO cl_ctmenu. DATA lin TYPE i. GET CURSOR LINE lin. IF lin > 2 AND sy-lsind = 0.* Add menu CALL METHOD l_menu->add_function EXPORTING fcode = 'DETAIL' text = text-001. ENDIF.* Add menu CALL METHOD l_menu->add_function EXPORTING fcode = 'BACK' text = text-002.ENDFORM. "on_ctmenu_request

How SAP calls the routine ON_CTMENU_REQUEST:

Whenever user presses right mouse button or shift + F10 key combinations sap triggers system event and calls the method DISPATCH_SYSTEM_EVENTS of class CL_GUI_CFW. Within it, it calls the method DISPATCH of class LCL_DYNPRO_PROXY (defined within the class pool of CL_GUI_CFW).

Page 112: ABAP Tutorials

 

 

From this method (DISPATCH) it calls the routine ON_CTMENU_REQUEST which is defined in our program.

Page 113: ABAP Tutorials
Page 114: ABAP Tutorials

 

Output:  

Basic list:

 

Page 115: ABAP Tutorials

Detail list:

Dynamic Selection Screen (Drop downs, pushbuttons, radio buttons, icons)

By Swarna S, Tata Consultancy Services

Following is the code in which the selection screen changes based on the user's click on the radio buttons. The entire selection screen is changed. The F8 button is disabled and selection screen push-button which changes dynamically based on radio button and does the functionality of the F8 button. 

*&----------------------------------------------------------------**& Report Z_sscr ** Published at SAPTechnical.COM*& **&----------------------------------------------------------------**&DYNAMIC Selection screen based on user clicks on the radiobutton**& **&----------------------------------------------------------------*REPORT zsscr.*TYPE POOLS DECLARATIONS FOR VALUE REQUEST MANAGER AND ICONSTYPE-POOLS : vrm, icon.*SELECTION SCREEN FIELDSTABLES : sscrfields.*GLOBAL DECLARATIONSDATA : flag TYPE c, tablename(10), mmtable LIKE dd02l-tabname, sdtable LIKE dd02l-tabname, hrtable LIKE dd02l-tabname.*DECLARATIONS FOR SELECTION SCREEN STATUSDATA it_ucomm TYPE TABLE OF sy-ucomm.***********SELECTION-SCREENS**********************SELECTION-SCREEN BEGIN OF BLOCK blk1 WITH FRAME.*FOR DYNAMIC DISPLAY OF MODULESPARAMETERS : pa RADIOBUTTON GROUP rad USER-COMMAND com MODIF ID mod, pb RADIOBUTTON GROUP rad MODIF ID rad, pc RADIOBUTTON GROUP rad MODIF ID cad.SELECTION-SCREEN SKIP.**TO INCLUDE DYNAMIC ICONS

Page 116: ABAP Tutorials

SELECTION-SCREEN COMMENT 2(6) text_001.*DYNAMIC LIST BOX BASED ON USER SELECTIONSPARAMETERS one AS LISTBOX VISIBLE LENGTH 20 MODIF ID mod.PARAMETERS two AS LISTBOX VISIBLE LENGTH 20 MODIF ID rad.PARAMETERS three AS LISTBOX VISIBLE LENGTH 20 MODIF ID cad.SELECTION-SCREEN END OF BLOCK blk1.*DISPLAY DYNAMIC PUSHBUTTON ON APP TOOLBAR ON USER CLICKSSELECTION-SCREEN: FUNCTION KEY 1, FUNCTION KEY 2, FUNCTION KEY 3.**EVENT ON SELECTION SCREEN FOR OUTPUT DISPLAYAT SELECTION-SCREEN OUTPUT.*CLICK OF FIRST RADIO BUTTON IF pa = 'X'. sscrfields-functxt_01 = 'Materials Management'. WRITE icon_plant AS ICON TO text_001.*CODE TO GET DYNAMICS BASED ON THE SELECTED RADIO LOOP AT SCREEN. IF screen-group1 = 'MOD'. screen-intensified = '1'. screen-active = 1. screen-display_3d = '1'. MODIFY SCREEN. ENDIF. IF screen-group1 = 'RAD'. screen-intensified = '0'. screen-active = 0. screen-display_3d = '0'. MODIFY SCREEN. ENDIF. IF screen-group1 = 'CAD'. screen-intensified = '0'. screen-active = 0. screen-display_3d = '0'. MODIFY SCREEN. ENDIF. ENDLOOP. ENDIF.*CLICK OF SECOND RADIO IF pb = 'X'. sscrfields-functxt_02 = 'Sales And Distribution'. WRITE icon_ws_ship AS ICON TO text_001. LOOP AT SCREEN. IF screen-group1 = 'RAD'. screen-intensified = '1'. screen-active = 1. screen-display_3d = '1'. MODIFY SCREEN. ENDIF. IF screen-group1 = 'MOD'. screen-intensified = '0'. screen-active = 0. screen-display_3d = '0'. MODIFY SCREEN. ENDIF. IF screen-group1 = 'CAD'. screen-intensified = '0'.

Page 117: ABAP Tutorials

screen-active = 0. screen-display_3d = '0'. MODIFY SCREEN. ENDIF. ENDLOOP. ENDIF.*CLICK OF THIRD RADIO IF pc = 'X'. sscrfields-functxt_03 = 'Human Resources'. WRITE icon_new_employee AS ICON TO text_001. LOOP AT SCREEN. IF screen-group1 = 'RAD'. screen-intensified = '0'. screen-active = 0. screen-display_3d = '0'. MODIFY SCREEN. ENDIF. IF screen-group1 = 'MOD'. screen-intensified = '0'. screen-active = 0. screen-display_3d = '0'. MODIFY SCREEN. ENDIF. IF screen-group1 = 'CAD'. screen-intensified = '1'. screen-active = 1. screen-display_3d = '1'. MODIFY SCREEN. ENDIF. ENDLOOP. ENDIF.*CUSTOMISING THE TOOLBARS OF THE SELECTION SCREEN*WITH F8 BUTTON DISABLED APPEND : 'PRIN' TO it_ucomm, 'SPOS' TO it_ucomm, 'ONLI' TO it_ucomm. CALL FUNCTION 'RS_SET_SELSCREEN_STATUS' EXPORTING p_status = sy-pfkey TABLES p_exclude = it_ucomm.**EVENT ON THE SELECTIONAT SELECTION-SCREEN.* LIST BOX ONE VALUES CASE one. WHEN '1'. mmtable = 'MARC'. WHEN '2'. mmtable = 'MARA'. WHEN '3'. mmtable = 'MARD'. WHEN '4'. mmtable = 'MARM'. ENDCASE.* LIST BOX TWO VALUES CASE two. WHEN '1'.

Page 118: ABAP Tutorials

sdtable = 'VBAK'. WHEN '2'. sdtable = 'VBAP'. WHEN '3'. sdtable = 'VBUK'. WHEN '4'. sdtable = 'VBUP'. ENDCASE.* LIST BOX THREE VALUES CASE three. WHEN '1'. hrtable = 'PA0001'. WHEN '2'. hrtable = 'PA0006'. WHEN '3'. hrtable = 'PA0022'. WHEN '4'. hrtable = 'PA0008'. ENDCASE.*VALUES FOR CLICK OF THE PUSHBUTTON ON APP TOOLBAR*AND ENABLING THE BUTTONS TO PERFORM F8 CASE sscrfields-ucomm. WHEN 'FC01'. tablename = mmtable. sscrfields-ucomm = 'ONLI'. WHEN 'FC02'. tablename = sdtable. sscrfields-ucomm = 'ONLI'. WHEN 'FC03'. tablename = hrtable. sscrfields-ucomm = 'ONLI'. ENDCASE.*INITIALIZATION EVENTINITIALIZATION.*VALUES ASSIGNED TO DROPDOWNLISTS IN THE SUBROUTINES PERFORM f4_value_request_pa. PERFORM f4_value_request_pb. PERFORM f4_value_request_pc.*START OF SELECTION EVENTSTART-OF-SELECTION.*SUBROUTINE FOR OUTPUT PERFORM output.*&----------------------------------------------------------------**& Form f4_value_request_PA*&----------------------------------------------------------------** text*-----------------------------------------------------------------**SUBROUTINE TO PROVIDE DROPDOWN VALUES TO LIST1FORM f4_value_request_pa. DATA: l_name TYPE vrm_id, li_list TYPE vrm_values, l_value LIKE LINE OF li_list. l_value-key = '1'. l_value-text = 'Plant Data for Material'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '2'.

Page 119: ABAP Tutorials

l_value-text = 'General Material Data'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '3'. l_value-text = 'Storage Location Data for Material'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '4'. l_value-text = 'Units of Measure for Material'. APPEND l_value TO li_list. CLEAR l_value. l_name = 'ONE'. CALL FUNCTION 'VRM_SET_VALUES' EXPORTING id = l_name values = li_list EXCEPTIONS id_illegal_name = 1 OTHERS = 2. 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. " f4_value_request_tabname*&----------------------------------------------------------------**& Form f4_value_request_PB*&----------------------------------------------------------------** text*-----------------------------------------------------------------**SUBROUTINE TO PROVIDE DROPDOWN VALUES TO LIST2FORM f4_value_request_pb. DATA: l_name TYPE vrm_id, li_list TYPE vrm_values, l_value LIKE LINE OF li_list. l_value-key = '1'. l_value-text = 'Sales Document: Header Data'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '2'. l_value-text = 'Sales Document: Item Data'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '3'. l_value-text = 'Sales Document:Header Status'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '4'. l_value-text = 'Sales Document: Item Status'. APPEND l_value TO li_list. CLEAR l_value. l_name = 'TWO'. CALL FUNCTION 'VRM_SET_VALUES' EXPORTING id = l_name values = li_list EXCEPTIONS id_illegal_name = 1

Page 120: ABAP Tutorials

OTHERS = 2. 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. " f4_value_request_PB*&----------------------------------------------------------------**& Form f4_value_request_PC*&----------------------------------------------------------------** text*-----------------------------------------------------------------**SUBROUTINE TO PROVIDE DROPDOWN VALUES TO LIST3FORM f4_value_request_pc. DATA: l_name TYPE vrm_id, li_list TYPE vrm_values, l_value LIKE LINE OF li_list. l_value-key = '1'. l_value-text = 'HR Master :Infotype 0001 (Org. Assignment)'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '2'. l_value-text = 'Address Infotype 0006'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '3'. l_value-text = 'Education Infotype 0022'. APPEND l_value TO li_list. CLEAR l_value. l_value-key = '4'. l_value-text = 'Basic Pay Infotype 0008'. APPEND l_value TO li_list. CLEAR l_value. l_name = 'THREE'. CALL FUNCTION 'VRM_SET_VALUES' EXPORTING id = l_name values = li_list EXCEPTIONS id_illegal_name = 1 OTHERS = 2. 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. " f4_value_request_PC*&----------------------------------------------------------------**& Form OUTPUT*&----------------------------------------------------------------** text*-----------------------------------------------------------------** -->P_TABLENAME text*-----------------------------------------------------------------**fINAL OUTPUTFORM output. DATA p_table(10). p_table = tablename.*popup to display teh selected table and

Page 121: ABAP Tutorials

*Continue button is clicked CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT' EXPORTING titel = 'User Selections ' textline1 = p_table textline2 = 'is the Selected table' start_column = 25 start_row = 6.*assigning the table value in p_table to the* Table in SE16 transaction by explicitly calling SET PARAMETER ID 'DTB' FIELD p_table. CALL TRANSACTION 'SE16'.ENDFORM. "OUTPUT

Initial screen

 

Dynamic selection screens based on selection of the radio buttons 

 

Page 122: ABAP Tutorials

 

 

On click of the Button in the Application toolbar, here ‘Sales and Distribution’, we get 

 

On clicking Continue, it proceeds to SE16.

Page 123: ABAP Tutorials

Dynamic Variant using the table TVARV

By Joyjit Ghosh, IBM India

Let us say for the given selection screen we need to create a dynamic variant.

 

Step 1. First maintain a variable with values in table TVARV. This can be done from transaction STVARV. Later this variable needs to be assigned to the variant.

Step 2. Next create the dynamic variant by pressing the SAVE button on the selection screen.

 

In the next screen (ABAP: Save as Variant) enter Variant name, description, set the ‘Selection variable’ (L) radio button and press ‘Selection variable’ push button.

Page 124: ABAP Tutorials

 

In the next screen check that green traffic light is on under column T (T: Table variable from TVARV).

Then click on the button.

 

Now from the popup select the variable name created in Step1 and save the variant.

Page 125: ABAP Tutorials

 

 

Step 3. Select the variant from Variant catalog.

Page 126: ABAP Tutorials

 

It will populate ‘Airline’ select-option with the values maintained in TVARV table against variable ZAIRLINE_CODE.

Display images (like company logo) on the selection-screen

By Gaurab Banerji, Capgemini India

Go to SMW0 and for uploading the image.

Page 127: ABAP Tutorials

 

Select Binary Data

 

Select the Find Button  

Press  

Press the Create button

 

Enter name and description

 

Select the image to upload

Page 128: ABAP Tutorials

 

Assign a package (must)

 

Press Save and OK

Page 129: ABAP Tutorials

 

Write the following report 

Code: 

REPORT zgb_prog06.* START OF DO NOT CHANGE***********************************DATA: docking TYPE REF TO cl_gui_docking_container, picture_control_1 TYPE REF TO cl_gui_picture, url(256) TYPE c .DATA: query_table LIKE w3query OCCURS 1 WITH HEADER LINE, html_table LIKE w3html OCCURS 1, return_code LIKE w3param-ret_code, content_type LIKE w3param-cont_type, content_length LIKE w3param-cont_len, pic_data LIKE w3mime OCCURS 0, pic_size TYPE i.* END OF DO NOT CHANGE*************************************DATA : sum(4) , num1(4) , num2(4).PARAMETERS: p_dummy(4) DEFAULT '4' .PARAMETERS: p_dummy1(4) DEFAULT '5' .AT SELECTION-SCREEN OUTPUT. PERFORM show_pic.START-OF-SELECTION.*&-------------------------------------------------------------------*& Form show_pic*&-------------------------------------------------------------------FORM show_pic. DATA: repid LIKE sy-repid. repid = sy-repid. CREATE OBJECT picture_control_1 EXPORTING parent = docking. CHECK sy-subrc = 0. CALL METHOD picture_control_1->set_3d_border EXPORTING border = 5. CALL METHOD picture_control_1->set_display_mode EXPORTING display_mode = cl_gui_picture=>display_mode_stretch. CALL METHOD picture_control_1->set_position EXPORTING height = 200 left = 100 top = 20 width = 400.*CHANGE POSITION AND SIZE ABOVE*************************** IF url IS INITIAL.

Page 130: ABAP Tutorials

REFRESH query_table. query_table-name = '_OBJECT_ID'.*CHANGE IMAGE NAME BELOW UPLOADED IN SWO0****************** query_table-value = 'BIKER'. APPEND query_table. CALL FUNCTION 'WWW_GET_MIME_OBJECT' TABLES query_string = query_table html = html_table mime = pic_data CHANGING return_code = return_code content_type = content_type content_length = content_length EXCEPTIONS object_not_found = 1 parameter_not_found = 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. CALL FUNCTION 'DP_CREATE_URL' EXPORTING type = 'image' subtype = cndp_sap_tab_unknown size = pic_size lifetime = cndp_lifetime_transaction TABLES data = pic_data CHANGING url = url EXCEPTIONS OTHERS = 1. ENDIF. CALL METHOD picture_control_1->load_picture_from_url EXPORTING url = url.*Syntax for URL*url = 'file://D:\corp-gbanerji\pickut\cartoon_184.gif'.*url = 'http://l.yimg.com/a/i/ww/beta/y3.gif'.ENDFORM. "show_pic

 Make changes in the report accordingly. 

Page 131: ABAP Tutorials

 

Given below is the desired output 

Custom Parameter-id Creation

By Abhijit Daptary, Capgemini India

Step1: Creation of parameter ID. 

Parameter ID can be created in the table TPARA. Just enter the name of the parameter id in the table and that parameter ID will be created. 

Page 132: ABAP Tutorials

 

Go to the table maintenance generator of the table TPARA and go to the Maintain button through the transaction SM30. 

Enter the table view name TPARA. 

 

Click on the maintain button. The following information will appear. Click on the Tick button or the ENTER button to go to the next screen. 

 

Enter the Set/Get parameter id as the parameter ID you want to create. Here, I will be creating the parameter Id as ZNAME_DATA1. Click on ENTER button. 

Page 133: ABAP Tutorials

 

It will ask for the text of the parameter Id. Enter the text of the parameter ID and click on the Save button. 

 

 

Enter the Package and the transport number. 

The parameter id can be seen in the table TPARA. 

Page 134: ABAP Tutorials

Step2: Using the parameter Id that you have created. 

Now go to the SE11 transaction for creating a data element and enter the parameter id at the Further Characteristics tab at the parameter Id section. 

 

Activate the data element and use it with the program. It will act the same good as a standard one.

 

 

Create Dynamic Patterns

By Joyjit Ghosh, IBM India

Step1. Create a pattern with only one line that contains *$&$EXIT. 

Page 135: ABAP Tutorials

 

Put this above expression and press save button.

 

Step2. Now from CMOD create a project and include enhancement SEUED001 in it.

Page 136: ABAP Tutorials

 

 

 

Now select the user exit EXIT_SAPLLOCAL_EDT1_001 and create the include program in it.

Page 137: ABAP Tutorials

 

Now insert the following code block in the include program and activate it.

*&---------------------------------------------------------------------**& Include ZXSEUU26 **&---------------------------------------------------------------------*DATA: w_buffer TYPE string.CASE keyword. WHEN 'DYNAMIC_PATTERN'. w_buffer ='*********************************************************************'. APPEND w_buffer TO buffer. w_buffer = '*& Program :'. APPEND w_buffer TO buffer. w_buffer = '*& Module :'. APPEND w_buffer TO buffer. w_buffer = '*& Sub-Module :'. APPEND w_buffer TO buffer. w_buffer = '*& Functional Contact:'. APPEND w_buffer TO buffer. w_buffer = '*& Funct. Spec. Ref. :'. APPEND w_buffer TO buffer. w_buffer = '*& Developer(Company):'. APPEND w_buffer TO buffer. w_buffer = '*& Create Date :'. APPEND w_buffer TO buffer. w_buffer = '*& Program Type :'. APPEND w_buffer TO buffer. w_buffer = '*& Project Phase :'. APPEND w_buffer TO buffer. w_buffer = '*& Description :'. APPEND w_buffer TO buffer. w_buffer ='*********************************************************************'.

Page 138: ABAP Tutorials

APPEND w_buffer TO buffer. WHEN OTHERS.* Do nothingENDCASE.

Lastly activate the project

Scheduling background jobs by triggering events

Page 139: ABAP Tutorials

Step1: Create event from transaction SM62.

 

Give event name and description and press save button

 

Step2: Create a program that triggers this event by calling the FM ‘BP_EVENT_RAISE’. 

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

Page 140: ABAP Tutorials

*& Report Z_TRIGGER_EVENT **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*REPORT Z_TRIGGER_EVENT .CALL FUNCTION 'BP_EVENT_RAISE' EXPORTING eventid = 'Z_TRIGGER_JOB' EXCEPTIONS BAD_EVENTID = 1 EVENTID_DOES_NOT_EXIST = 2 EVENTID_MISSING = 3 RAISE_FAILED = 4 OTHERS = 5 .IF sy-subrc <> 0. Write: 'Event failed to trigger'.else. Write: 'Event triggered'.ENDIF.

Step3: Configure the background job from transaction SM36. 

In the initial screen give job name and job class and press “Start condition” button.

Page 141: ABAP Tutorials

 

In the popup screen press “After event” button and give the event name and then press save button.

Page 142: ABAP Tutorials

Now go back to the initial screen and press “Step” button

Page 143: ABAP Tutorials

 Provide program and variant name and after providing all the values press save button.

Page 144: ABAP Tutorials

 

In the initial screen press save button.

Page 145: ABAP Tutorials

Step4: Now execute the program to trigger the event and as well check the background job. 

Page 146: ABAP Tutorials

 

Run transaction SM37

 

Check the status of job defined above

 

Page 147: ABAP Tutorials

Now check the spool to see the generated list

 

 

Performance Tuning using Parallel Cursor

By Suresh Kumar Parvathaneni, YASH Technologies

Nested Loops – This is one of the fear factors for all the ABAP developers as this consumes lot of program execution time. If the number of entries in the internal tables is huge, then the situation would be too worse. The solution for this is to use parallel cursor method whenever there is a need for Nested Loop.

Program using Normal Nested Loop:

REPORT  ZNORMAL_NESTEDLOOP.

TABLES:  likp,

Page 148: ABAP Tutorials

  lips.

Data:  t_likp  type table of likp,  t_lips  type TABLE OF lips.

data:  W_RUNTIME1 TYPE I,  W_RUNTIME2 TYPE I.

START-OF-SELECTION.select *  from likp  into table t_likp.

select *  from lips  into table t_lips.

get RUN TIME FIELD w_runtime1.

loop at t_likp into likp.  loop at t_lips into lips where vbeln eq likp-vbeln.  endloop.endloop.

get RUN TIME FIELD w_runtime2.

w_runtime2 = w_runtime2 - w_runtime1.

write w_runtime2.

Nested Loop using Parallel Cursor:

REPORT  zparallel_cursor2.

TABLES:  likp,  lips.

DATA:  t_likp  TYPE TABLE OF likp,  t_lips  TYPE TABLE OF lips.

DATA:  w_runtime1 TYPE i,  w_runtime2 TYPE i,  w_index LIKE sy-index.

START-OF-SELECTION.  SELECT *    FROM likp    INTO TABLE t_likp.

  SELECT *    FROM lips

Page 149: ABAP Tutorials

    INTO TABLE t_lips.

  GET RUN TIME FIELD w_runtime1.  SORT t_likp BY vbeln.  SORT t_lips BY vbeln.

  LOOP AT t_likp INTO likp.

    LOOP AT t_lips INTO lips FROM w_index.      IF likp-vbeln NE lips-vbeln.        w_index = sy-tabix.        EXIT.      ENDIF.    ENDLOOP.  ENDLOOP.

  GET RUN TIME FIELD w_runtime2.

  w_runtime2 = w_runtime2 - w_runtime1.

  WRITE w_runtime2.

Analysis report: Runtime in microseconds: 

Iteration No Normal Nested Loop Using Parallel Cursor

1 34,796,147 63,829 2 38,534,583 56,894 3 34,103,426 50,510

Creating a Transaction Variant

By Smita Singh

In this tutorial, we would discuss about creating a transaction variant for the transaction MM01. Our transaction variant should default to a value for Industry sector and material type and should not allow the end user to change those values (output only). 

Go to transaction SHD0. 

Page 150: ABAP Tutorials

 

Enter the transaction code MM01. Now click on button CREATE.

Following information message would appear:

 

Click Enter to proceed. 

Now the MM01 transaction would appear. 

Page 151: ABAP Tutorials

 

Select the required Industry sector and Material Type and press ENTER. Following popup would appear: 

 

Now make the modifications as shown below: 

Page 152: ABAP Tutorials

 

Click on “Exit and Save”. 

Following popup would appear:

 

Click Enter to proceed. Following screen would appear:

Page 153: ABAP Tutorials

 

Save your entries and go back to the main screen.

Now enter the transaction variant name and click on Change button as shown below:

 

Now click on Insert Row. 

Enter the name of the screen variant created earlier or use F4 help to select the value:

Page 154: ABAP Tutorials

 

Now click on Goto à Create Variant Transaction 

 

Enter the values as shown above. Click on Enter. The following SE93 transaction would appear: 

Page 155: ABAP Tutorials

 

The name of the Transaction Variant is automatically proposed. Save your entries. 

Now go to Transaction ZMM01 and check your transaction variant:

 

You can observe that the field Industry sector and Material type default to the value we have given earlier and are output enabled only.

E-Mailing the background jobs

By Harini

Page 156: ABAP Tutorials

This tutorial deals about the procedure in automatic e-mailing of the background jobs. The output of the background job is sent to the recipient as an email. 

Consider the following simple program: 

REPORT zbackground_test. 

WRITE: 'hello SAPTechnical.com team'. 

We would schedule the above program as a background job and send the output of the same as an email. 

Go to Transaction SM36. 

Enter the job name. 

 

Press Enter. Following popup screen appears: 

Page 157: ABAP Tutorials

 

Enter your program name as shown above and click on SAVE.  

 

Click on Back button to navigate to the main screen.  

Page 158: ABAP Tutorials

 

Click on the button “Spool list recipient” as shown above.

 

Enter the name of the recipient to which the output to be sent. 

Now come back to the main screen and click on “Start Condition”. 

 

Select Immediate and click on save.

Page 159: ABAP Tutorials

 

Save your job. Only after you save, the job would be set to status Released. 

 

You can go to transaction SM37 to monitor the background job. 

Now go to SAP inbox (transaction SBWP/SO01) to check the status of the background job:

 

In the above screenshot, you can observe an email related to the job we created earlier. Open the attachment to see the output of the background job: 

Page 160: ABAP Tutorials

ABAP Programming / Naming Standards

By Supriya Joshi

Following are the performance standards need to be following in writing ABAP programs:

For all ABAP Programs / Transaction Codes

Add the below header at the beginning of Every ABAP program ************************************************************************* OBJECT ID : * PROGRAM TITLE : * MODULE : * PROGRAM TYPE : * INPUT :* OUTPUT :* CREATED BY : * CREATION DATE : *-----------------------------------------------------------------------------------------------------------* DESCRIPTION : * * * ************************************************************************

Page 161: ABAP Tutorials

* Modification history: * ----------------------------------------------------------------------------------------------------------* DATE |User ID |TS Ver | Transport Request | Description * ----------------------------------------------------------------------------------------------------------* ************************************************************************Naming conventions to be followed:

Other Objects

Page 162: ABAP Tutorials
Page 163: ABAP Tutorials

Application area corresponds to the application area you are working like 

B - Basis       C - CO      F- FI         W -  PM    

S – SD / SAM     M – MM/Supply    

ABAP Performance Standards

By Aveek Ghose, IBM India

DescriptionResult (Y, N or N/A)

Comments

Run Extended syntax checks with character literals checkbox switched on & Code Inspector to rectify all relevant errors and

warning (e.g. Use the results of the above checks to remove all variables/constants etc that are declared but are not used)

   

Page 164: ABAP Tutorials

Transaction SE30 (ABAP Runtime Analysis) must be checked to measure/compare program performance/runtime if program has

multiple inefficient databases selects or complicated internal table operations

   

Use transaction ST05 (SQL Trace) to see what indices your database accesses are using. Check these indices against your

“where” clause to assure they are significant. Check other indices for this table and where you have to change your “where” clause to use it. Create new indices if necessary, but do not forget to check

the impact by consulting onsite coordinator.

   

TYPE (data element) command is used while declaring the fields whenever feasible instead of LIKE. Remember not always the data

element name matches with the table field name   

Internal Table is defined with “TYPE STANDARD TABLE OF” & Work-Areas is used instead of header lines

   

Global variables are minimized by declaring local variables or by passing variables through parameters & arguments while creating

internal subroutine(s)   

In SELECT statement, only the required fields are selected in the same order as they reside on the database table/structure/view

   

For selecting single row from a database table, “SELECT UP to 1 Rows” is used. “Select Single” is used only when full primary key

combination is known   

No SELECT * is used    

Use “SELECT INTO TABLE” rather than “SELECT INTO CORRESPONDING FIELDS OF TABLE”

   

Always specify as many primary keys as possible in WHERE clause to make the Select efficient

   

Always select into an internal table, except when the table will be very large (i.e., when the internal table will be greater than 500,000 records). Use “Up to N Rows” when the number of records needed

is known

   

Select statement within a GET event is not used    

Wild cards like ‘A%’ is avoided as much as possible    

Nested Select is not used instead “Inner Join” and/or “For all Entries” is used. “For all Entries” is to be used over “Loop at ITAB / Select / ENDLOOP” (FOR ALL ENTRIES retrieves a unique result

set so ensure you retrieve the full key from the database)

   

When creating joins over database tables there should be an index at least on the inner table for the fields in the join condition else

use “ FOR ALL ENTRIES” select statement   

Usage of JOIN is limited to a maximum of 2 i.e. not more than 3 database tables are joined at one time

   

CHECK that the internal table used in FOR ALL ENTRIES is NOT empty as this will retrieve all entries from the table

   

Delete adjacent duplicate entries from internal table before selection from database table using “ FOR ALL ENTRIES”

statement   

For copying internal tables use ‘=’ operator instead of Looping & Appending

   

Page 165: ABAP Tutorials

SORT inside a LOOP is not used    

Sort internal table by fields in the correct order, which are used in a READ TABLE statement using BINARY SEARCH. If the order of

sorting is invalid the BINARY SEARCH will never work   

For large internal tables where only some rows are to be processed, use SORT and then the READ TABLE command is used to set index to first relevant row before looping from that

index. Use CHECK or IF…EXIT…ENDIF as appropriate to exit from the loop

   

Sort fields and Sort Order on the SORT statement should be mentioned explicitly (e.g. SORT ITAB BY FLD1 FLD2

ASCENDING)   

Hashed table is used for processing large amount of data (provided that you access single records only, and all with a fully

specified key)   

DELETE or SORT is not used on a hashed table since it increases memory consumption

   

Sorted table is used for range accesses involving table key or index accesses

   

Fields specified in the WHERE condition with the critical operators NOT and <> (negative SQL statements) cannot be used for a

search using database indexes. Whenever possible formulate SQL statements positively

   

When coding IF or CASE, testing conditions are nested so that the most frequently true conditions are processed first. Also CASE is

used instead of IF when testing multiple fields “equal to” something   

LOOP AT ITAB INTO WORKAREA WHERE K = ‘XXX’ should be used instead of LOOP AT ITAB INTO WORKAREA / CHECK

ITAB-K = ‘XXX’.

Also READ TABLE INTO WORKAREA should be used instead of only READ TABLE.

   

After the APPEND statement inside a loop, the work area that has been appended is cleared

   

Internal tables, Work areas & Global Variables are freed when no longer needed (e.g. using the FREE / REFRESH command), especially when the tables are large or the program is a batch

program

   

Do not delete the records of internal table inside the Loop – End loop.

Do not use: LOOP AT ITAB WHERE EQUNR = ‘00001011’.

DELETE ITAB.

ENDLOOP.

Use: DELETE ITAB WHERE EQUNR = ‘00001011’. 

   

Use the MODIFY ITAB ... TRANSPORTING f1 f2 ... for single line, and MODIFY ITAB ... TRANSPORTING f1 f2 ... WHERE condition

for a set of line, to accelerate the updating of internal table   

Page 166: ABAP Tutorials

If possible, Update/Insert statement is used instead of Modify    

Is the following steps ensured during database updates?

Lock data to be edited Read current data from the database

Process data and write it to the database

Release the locks set at the beginning

   

Try to avoid logical databases. If your program uses a logical database, but does not require all fields belonging to a certain

GET event, always use the FIELDS addition to reduce the amount of data selected by the logical database

   

Avoid the aggregate (Count, Max, Min) functions in the database selection

   

Use Parallel Cursor methods for nested loop into the internal tables if second internal table contains considerable number of

records   

In Smartform/ Sapscript do not make redundant data retrieval where data is available in interface

   

Understanding SQL Trace

By Aveek Ghose, IBM India

Performing an SQL Trace:

1. Access transaction ST05. From the initial screen, click the check box for SQL trace, under the trace requests, click Trace on.

2. Run the program containing the SQL query that needs to be analyzed in the SE38 editor.

3. Come back to ST05 screen, under Trace requests, click Trace off.

4. Click List trace to view the trace of the current statement.

Screen shot of the initial ST05 screen  

Page 167: ABAP Tutorials

 

After clicking list trace

Page 168: ABAP Tutorials

 

Basic List Trace

Page 169: ABAP Tutorials

The basic list trace shows the sequence of database operations that are taking place while a query is processed, it includes prepare, fetch, open, reopen, execute. In addition the basic list trace also gives the duration execution for each of the operations with color legend.  

Summarizing the basic trace list (menu path: Goto à Summary)

A basic trace list can be summarized to see the summation of execution times of similar database operations. Use menu path: GotoàSummary. The above screen shot depicts the summed up execution time. The summary option lists the summed up execution time of all the queries that the SQL trace has captured at its runtime, but the identification of a particular query can be done using the PID – Process ID which is displayed as the first column of the above screen shot. For example, 896 is the process ID for one of the SQL statements. 

Summary of a particular trace   

Page 170: ABAP Tutorials

To get the total execution time, specifically for a particular SQL Statement, select all the PID corresponding to it and click summarize in the application toolbar. This leads to a compressed data of SQL trace as above. 

Color legends indicating the processes in a trace 1

 

Use the menu path: Goto -> Show color legend to know about the color specification in the trace.

Color legends indicating the processes in a trace 2

Page 171: ABAP Tutorials

The above screen shot indicates that the query execution time has exceeded its threshold with the link pink color. A change in object name is indicated with the change in color to yellow. These colors thereby indicate whether the query is well written and also the current status of the database server.

Extended list

 

(From basic trace list: click extended list button in application toolbar to view the extended list). The extended list shows the cursor id declared for the SQL statement, the connection type also.

Cursors: A cursor is a handle or name for an area in memory in which a parsed statement and other information for processing the statement are kept; such an area is also called a private SQL area. Although most Oracle users rely on the automatic cursor handling of the Oracle utilities, the programmatic interfaces offer application designers more control over cursors. In application development, a cursor is a

Page 172: ABAP Tutorials

named resource available to a program and can be used specifically for the parsing of SQL statements embedded within the application.

Identical select statements

 

Use the menu path: Gotoà Identical Selects to view a comprehensive list of identical select statements executed during the trace and the number of times they were executed. Identical select statements are grouped based on the where clause.

Note that identical select statements have similar execution plan used for their processing thereby saving time of execution and provide increased performance, too.

Identical select statements displayed

Page 173: ABAP Tutorials

The above screen shot shows the list of identical select statements and the number of time they got executed.

Database Operations Measured by SQL Trace

The SQL Trace analysis helps in measuring the execution time of the following data base operations that are performed when executing an SQL statement.

1) DECLARE: This operation declares a new cursor and assigns the SQL statement to that cursor created.

2) PREPARE: This operation converts the SQL statement into native SQL and frames out an execution plan for that statement.

3) OPEN: This operation opens the declared cursor and passes the parameters for database access.

4) FETCH: This operation passes one or more data records fetched to the database interface of the R/3 system.

5) REOPEN: Once a new select statement is brought in then this operation opens the cursor previously declared for previous select statement and performs new parameter passing to the database.

6) EXEC: Passes the parameters for the database statement, and executes the statements that change data in the database (such as UPDATE, DELETE, or INSERT).

 

Changing the text "Sales Order" to "Billing Request" in the transactions VA01, VA02 and VA03

By Vikram Chellappa, Mouri Tech Solutions 

Scenario:

The below steps to be followed for Changing the text Sales Order to Billing Request in VA01, VA02, VA03 Transactions. 

Go to transaction VA01

Page 174: ABAP Tutorials

 

In Menu bar Go to System > Status

 

Double click on the Screen number 101 

Page 175: ABAP Tutorials

 

Double click on MODULE CUA_SETZEN

 

Double Click on PERFORM CUA_SETZEN.

Page 176: ABAP Tutorials

 

Click on Enhance (Shift+F4)

 

Click on Edit > Enhancement Operations > Show Implicit Enhancement Options 

Page 177: ABAP Tutorials

 

Scroll down up to the line 1425. Here we need to create an Enhancement. 

 

Page 178: ABAP Tutorials

Right Click on the page Go to Enhancement Implementation > Create  

 

The below screen will appear Mark the check box

Click on create enhancement Implementation (F8)  

Page 179: ABAP Tutorials

 

Enter the Enhancement Implementation, Short text and Click on Create Composite Implementation. 

 The Below screen will appear 

Page 180: ABAP Tutorials

 

Enter the name for Composite enhancement implementation and Short Text.

Then Click on Creation of Enhancement (Enter) 

 

Page 181: ABAP Tutorials

 

Click on Save and Assign it in corresponding Package.

 By scrolling down select the already created Enhancement Implementation,

Click on continue. 

Page 182: ABAP Tutorials

 Go to SE80 create a new zprogram named ztitle. 

 

Click on Yes.

Page 183: ABAP Tutorials

 

Enter the Program name and continue. 

Enter the Title of the created program and Assign Type as Module Pool.

Click on Save.

 

Page 184: ABAP Tutorials

Save it in Package. 

 

Right Click on ztitle > Create >GUI Titles

 

Enter the Title Code And Title. 

Page 185: ABAP Tutorials

 

Click on Transfer or (Enter)

 

Create another Title code. 

 

Assign the Title code and title.

Page 186: ABAP Tutorials

 

Repeat the above same procedure.  

Right Click on Ztitle and Click on Activate.

Page 187: ABAP Tutorials

 

The created GUI title will display under GUI Title.

Page 188: ABAP Tutorials

 

Type SAPMV45A in Program > Go to Subroutines.

 

Scroll down in CUA_SETZEN.

Page 189: ABAP Tutorials

 The Below screen will display. 

 Type the Below Code  

IF sy-tcode = 'VA01'.

Page 190: ABAP Tutorials

SET TITLEBAR 'Z01' OF PROGRAM 'ZTITLE' WITH <TFS>.ELSEIF sy-tcode = 'VA02'. SET TITLEBAR 'Z02' OF PROGRAM 'ZTITLE' WITH <TFS>.ELSEIF sy-tcode = 'VA03'. SET TITLEBAR 'Z03' OF PROGRAM 'ZTITLE' WITH <TFS>.ENDIF.

 

Click on save and Click on activate Enhancements (Ctrl+F3) 

Page 191: ABAP Tutorials

 

Go to Program and Click on Generate.

 

Page 192: ABAP Tutorials

Now you can go and view the transaction screen. 

Go to VA01. 

 

Go to VA02.

 

Go to VA03.

Page 193: ABAP Tutorials

Creation of a web service in SAP

By Raghava Vakada, Mouri Tech Solutions

“In this Scenario, I would like to explain about creating a Web Service with a simple scenario.”

Creating a Web Service

In the function library (SE37), display the function module.

Open the function Module : ME_GET_CURRENT_USER_ID 

Choose Utilities -> More Utilities -> Creating a Web Service -> From Function Module. 

Page 194: ABAP Tutorials

 

In the Web Service Creation Wizard, choose Continue. 

Enter the name of the Web Service Definition

 

Page 195: ABAP Tutorials

In the following screen, enter the required data and select the checkbox Name Mapping. If the checkbox Name Mapping is ticked, the wizard accepts the existing names for the end point.

Choose Continue. 

In the following screen, enter the required data and select the checkbox Release Service for runtime. 

Page 196: ABAP Tutorials

Choose Continue.

Choose Complete.

Page 197: ABAP Tutorials

Save as local object.

Testing a Web Service.

Prerequisites

Open the transaction WSADMIN.

 

Select the Web service definition you have created under SOAP Application for RFC-Compliant FMs

Select and expand the “ZWEB_GET_CURRENT_USER” and select the Web Service as shown in screen. 

Page 198: ABAP Tutorials

 

You have entered the address of the application server on which the J2EE Engine is running in transaction WSADMIN under Goto  -> Administration Settings.  

Check the J2EE Server and check in your server.

Choose Web Service Homepage (Execute Button ). 

Page 199: ABAP Tutorials

Select the “Document Style” under Style definition in WSDL.

The Web service requires authentication. 

Enter the user and password  

Page 200: ABAP Tutorials

Click on the “Test”. 

Select the “Operations”.

Page 201: ABAP Tutorials

Fill in values for the method parameters underneath the heading Request if required. Choose Send. 

The required values are displayed under the Response heading. The Web service has not been tested successfully. 

Page 202: ABAP Tutorials

Calling a web service in ABAP that validates an email id

By Teja

In this tutorial, we would use a free web service in an ABAP program  which validates an email-id. For more details regarding this web service, click here.

Create a program and use the following code:

REPORT zvalidate_email.PARAMETERS: p_mail(100) LOWER CASE. " E-Mail id to be verifiedDATA: http_client TYPE REF TO if_http_client .DATA: w_string TYPE string , w_result TYPE string , r_str TYPE string .DATA: result_tab TYPE TABLE OF string.START-OF-SELECTION . CLEAR w_string . CONCATENATE 'http://www.webservicex.net/ValidateEmail.asmx/IsValidEmail?Email=' p_mail INTO w_string . CALL METHOD cl_http_client=>create_by_url EXPORTING url = w_string IMPORTING client = http_client

Page 203: ABAP Tutorials

EXCEPTIONS argument_not_found = 1 plugin_not_active = 2 internal_error = 3 OTHERS = 4. CALL METHOD http_client->send EXCEPTIONS http_communication_failure = 1 http_invalid_state = 2. CALL METHOD http_client->receive EXCEPTIONS http_communication_failure = 1 http_invalid_state = 2 http_processing_failed = 3. CLEAR w_result . w_result = http_client->response->get_cdata( ). REFRESH result_tab . SPLIT w_result AT cl_abap_char_utilities=>cr_lf INTO TABLE result_tab . READ TABLE result_tab INTO r_str INDEX 2. IF r_str+44(1) = 't'. WRITE:/ 'Valid email address'. ELSE. WRITE:/ 'Invalid email address'. ENDIF.

Output:

Handling favorites in ABAP Workbench

By Sunitha

Page 204: ABAP Tutorials

This document details the procedure in handling the favorites in the ABAP Workbench. I would always want to add my frequently used objects in the favorites. For our learning purpose, let us add the package SWDP_DEMO_TUTORIALS (Demo tutorials for Web Dynpro ABAP) to the favorite list. 

Go to Transaction SE80 and select “Package” from the list box. Enter the package name SWDP_DEMO_TUTORIALS as shown below: 

 

Now open the list box “Favorites” and click on Add: 

 

The following message appears: 

 

Now verify the same by opening the favorites: 

Page 205: ABAP Tutorials

 

This way, we can add the recently used objects in the favorites list. 

To download/Upload favorites from one system to another: 

In the favorites, click on Edit as shown below:

 

Following screen appears:

Page 206: ABAP Tutorials

 

Using the Download/Upload buttons, we can either download/upload the favorites from one system to another.

Events in Table Maintenance

Scenario: We have a following custom table which contains the fields “Date on which record was created” and “Name of the person who created the object”. We would like to have these to be filled up with SY-DATUM and SY-UNAME respectively.   

 

Go to Table Maintenance Generator: 

Page 207: ABAP Tutorials

 

Enter the details as shown below:

Page 208: ABAP Tutorials

 

Now click on Environment -> Modification -> Events 

 

Following screen is displayed.

Page 209: ABAP Tutorials

 

Click on F4. Following entries are displayed: 

 

Here you can observe that there are different types of events available like before saving the data, after saving the data, before deleting, after deleting and others. Let us go with “Creating a new entry”. 

Page 210: ABAP Tutorials

 

Click on the button in the Editor column and enter the following code: (Please note that you should also code FORM and ENDFORM as well).  

 

Save and activate the table. 

Testing the scenario: 

Go to SM30 and try creating new entries. Do not enter the values for “Created on” and “Created by”. 

 

Page 211: ABAP Tutorials

Check your entries in the database table. You can observe that the date and user name are automatically filled-in. See the screenshot below: 

Using Sorted table and Index while processing Internal tables

By Suresh Kumar Parvathaneni

There would have been many instances where we would have to process large entries in an internal table with a WHERE condition. This article is intended to demonstrate the comparison between three different methods in handling this situation.  

First Method: The normal method used by most of us. Standard internal table processing using WHERE condition

Second Method: Same as above, but here we would be using the Sorted table

Third Method: Sorted table and using the Index  

Following is the demo program illustrating the above three methods:

REPORT ZINTERNAL_TABLE_OPERATIONS.* Program to find the best method in reading the internal tables* Author: Suresh Kumar Parvathaneni* Type declarationTYPES: BEGIN OF TY_MARA, MATNR LIKE MARA-MATNR, MTART LIKE MARA-MTART, END OF TY_MARA.* Internal table declarationDATA: T_MARA TYPE STANDARD TABLE OF TY_MARA, T_MARA1 TYPE SORTED TABLE OF TY_MARA WITH NON-UNIQUE KEY MTART.* Variable declarationDATA: W_COUNTER TYPE I, W_RUNTIME1 TYPE I, W_RUNTIME2 TYPE I, W_TABIX LIKE SY-TABIX.* Table workarea definitionDATA: WA_MARA TYPE TY_MARA.SELECT MATNR " Material Number MTART " Material Type FROM MARA INTO TABLE T_MARA.T_MARA1[] = T_MARA[].* CASE 1: Processing internal table using LOOP..WHERE ConditionGET RUN TIME FIELD W_RUNTIME1.

Page 212: ABAP Tutorials

LOOP AT T_MARA INTO WA_MARA WHERE MTART EQ 'FHMI'. ADD 1 TO W_COUNTER.ENDLOOP.GET RUN TIME FIELD W_RUNTIME2.* Calculate RuntimeW_RUNTIME2 = W_RUNTIME2 - W_RUNTIME1.WRITE W_RUNTIME2.CLEAR W_COUNTER.* CASE 2: Using a Sorted tableGET RUN TIME FIELD W_RUNTIME1.LOOP AT T_MARA1 INTO WA_MARA WHERE MTART EQ 'FHMI'. ADD 1 TO W_COUNTER.ENDLOOP.GET RUN TIME FIELD W_RUNTIME2.* Calculate RuntimeW_RUNTIME2 = W_RUNTIME2 - W_RUNTIME1.WRITE W_RUNTIME2.CLEAR W_COUNTER.* CASE 3: Using INDEX on a sorted tableGET RUN TIME FIELD W_RUNTIME1.READ TABLE T_MARA1 INTO WA_MARA WITH KEY MTART = 'FHMI'.IF SY-SUBRC EQ 0. W_TABIX = SY-TABIX + 1. ADD 1 TO W_COUNTER. LOOP AT T_MARA1 INTO WA_MARA FROM W_TABIX. IF WA_MARA-MTART NE 'FHMI'. EXIT. ENDIF. ADD 1 TO W_COUNTER. ENDLOOP.ENDIF.GET RUN TIME FIELD W_RUNTIME2.* Calculate RuntimeW_RUNTIME2 = W_RUNTIME2 - W_RUNTIME1.WRITE W_RUNTIME2.

Following is the analysis report in microseconds, as per the data volume:  

Records: 21,390

Iteration No

Using Normal LOOP & WHERE

Using Sorted table LOOP & WHERE

Using INDEX on Sorted table

1 897 887 11 2 839 879 10 3 839 877 10 4 834 880 9 5 842 837 10

Records: 132,693

Iteration No

Using Normal LOOP & WHERE

Using Sorted table LOOP & WHERE

Using INDEX on Sorted table

1 34239  35774  3567 2 34271  38250  3592

Page 213: ABAP Tutorials

3 34492  36534  3554 4 34198  35695  3584

Sorted table might have given a better performance here if the field in the WHERE condition is the first field in the internal table. However, from the above statistics, we can say that method 3 is better than the other 2 methods. In production environment, the data would be huge and the performance could be much improved with this simple technique.

Displaying Graphics using an ABAP Program

By Raghava Vakada, Mouri Tech Solutions

“I would like to explain about a simple report program to display graphics. The SAP Graphics can be used for various business purposes”.

In this article I am explaining about a simple Sales analysis on a yearly basis.

*&---------------------------------------------------------------------**& Report ZGRAPH_TEST*&*&---------------------------------------------------------------------*REPORT ZGRAPH_TEST.DATA: BEGIN OF TAB OCCURS 5, CLASS(5) TYPE C, VAL1(2) TYPE I, VAL2(2) TYPE I, VAL3(2) TYPE I, END OF TAB.DATA: BEGIN OF OPTTAB OCCURS 1, C(20), END OF OPTTAB.MOVE: 'fan' TO TAB-CLASS, 12 TO TAB-VAL1, 8 TO TAB-VAL2, 15 TO TAB-VAL3.APPEND TAB.CLEAR TAB.MOVE: 'cool' TO TAB-CLASS, 15 TO TAB-VAL1, 10 TO TAB-VAL2, 18 TO TAB-VAL3.APPEND TAB.CLEAR TAB.MOVE: 'DA' TO TAB-CLASS, 17 TO TAB-VAL1, 11 TO TAB-VAL2, 20 TO TAB-VAL3.APPEND TAB.CLEAR TAB.OPTTAB = 'FIFRST = 3D'. APPEND OPTTAB. "// Grafik-TypOPTTAB = 'P3TYPE = TO'. APPEND OPTTAB. "// ObjektartOPTTAB = 'P3CTYP = RO'. APPEND OPTTAB. "// Farben der ObjekteOPTTAB = 'TISIZE = 2'. APPEND OPTTAB. "// HaupttitelgrößeOPTTAB = 'CLBACK = X'. APPEND OPTTAB. "// Background ColorCALL FUNCTION 'GRAPH_MATRIX_3D' EXPORTING COL1 = '1997' COL2 = '1998' COL3 = '1999' DIM2 = 'Products'

Page 214: ABAP Tutorials

DIM1 = 'Years' TITL = 'Sales In Rs. Crores' TABLES DATA = TAB OPTS = OPTTAB EXCEPTIONS OTHERS = 1.LEAVE PROGRAM. 

Results :

Execute the report program for an output shown below. 

 

Click on Overview for detailed view.

 

To display more detailed view.   

Page 215: ABAP Tutorials

The ABAPTM New Editor

By Suresh Kumar Parvathaneni

This article, the first part of a two-article series, takes you on a brief tour of the features available in the new ABAPTM editor (step by step with screenshots) 

Pre-requisites

The new ABAPTM editor is available with SAP® GUI for windows 6.40 patch level 10 or higher. However this new editor is supported from the SAP® Version SAP® Netweaver 2004s.

Shifting to ABAP TM New Editor

Start any of the following transaction codes to access the ABAPTM workbench:

SE38 SE37

SE24

SE37

We would use SE38 for our demo purposes.

Procedure to shift between Old ABAPTM Editor and New ABAPTM Editor:

Go to Utilities à Settings Click on Front-end Editor (New) as shown below

Page 216: ABAP Tutorials

Click  for changes to effect.

Features in ABAP TM New Editor

First Look:

View of the new ABAPTM Editor (from SE38):

Display Features

Following are some of the features that could be observed while writing the code:

Page 217: ABAP Tutorials

Line Numbers

As observed in the above screenshot, the new ABAPTM editor displays the line numbers for easy navigation through the code.

Changed line indicators

 The changed lines in the current session are marked with .

These indicators would vanish once you come out of the program.

Bookmarks

Bookmarks allow in navigating and code editing. There are 9 numbered bookmarks provided by SAP® and unlimited unnumbered bookmarks. Bookmarks could be accessed by the right click of the mouse in the Indicator Margin (The complete left portion of the ABAPTM editor).

To set a bookmark, right click on the Indicative Margin, click on Bookmarks --> Bookmark 0 (Bookmarks are numbered 0 to 9). A Blue flag with the bookmark number would appear on the Indicative Margin.

To navigate to any bookmark marked earlier, right click on the Indicative Margin, Go to Bookmark --> Bookmark 0.

Code Hints

Code hints appear as you type in ABAPTM editor. For example, if you start typing for Parameters, following occurs:

When typed P, nothing appears. When typed PA, code hint PACK appears.

Page 218: ABAP Tutorials

When typed PAR, code hint PARAMETERS appears.

Press TAB to choose the given code hint.

Changing the Font and Colors of coding environment

Click on , available at the right side bottom of the editor. Click on “Fonts and Colors” on the left side of the window that is appeared after clicking. From here, we can set different colors and fonts for different elements on the editor. 

Window Splitter

The window splitter allows you to work on different parts of the code simultaneously.

The window could be set to splitter mode by double clicking the splitter line above the vertical scrollbar (shown below).

The split screen is seen as below:

Page 219: ABAP Tutorials

Also visit Features of ABAP New Editor Part 2

The Features of ABAP New Editor Part 2

By Suresh Kumar Parvathaneni

Working with Colors and Fonts: 

Switch to the new editor (if the default editor shown is the old editor). 

In the New ABAP editor, click on the button “options” available at the bottom of the right hand side, as shown in the below screen shot:

Page 220: ABAP Tutorials

 

Following pop-up appears:

 

Now select “Fonts and Colors” available on the left side.

Page 221: ABAP Tutorials

 

Using this, you can design how the screen should look like, For example, you can dictate how the comments should appear (like Font, size, foreground color and background color). Let us take the same “comments” section for our scenario here. 

Comments are currently displayed as shown below:

 

Now click on the options button and select “Fonts and Colors”. Select “Comments” from the list box:

Page 222: ABAP Tutorials

 

Now change the way you would like the options to appear in this section:

 

Save and check how the way comments appear now.

Page 223: ABAP Tutorials

 

Working with Code Templates: 

To view the Code Templates currently available, Click on “Options” as shown earlier. Now click on “Code Templates” option available on the left side.

 

You would observe the code templates available for use with the editor. Click on any code template to understand further.

Page 224: ABAP Tutorials

 

Above screenshot is for “DO”. We would use this for our demo purpose to better understand the code template. 

Write some sample code in your editor.

 

Now select your program code and click the right button of the mouse. Select -> Format -> Surround by template -> Do () (as shown in the following screenshot) 

Page 225: ABAP Tutorials

 

Now observe your code:

 

Your code is now surrounded by the code template “DO”.

Creating custom code template:

Now we would work on creating our own code template for our future use. 

As observed in the earlier screenshots, there is no code template available for subroutine. Let us create a code template for the same.

Page 226: ABAP Tutorials

 

Select your code and click on right button. Select Format -> Extract template 

 

Enter the name for your code template. 

Click on OK.

Page 227: ABAP Tutorials

 

 

Now we need to define the position where the selected text (surrounded text) to appear.  

Click on the empty line between “form” and “endform” and click on “Insert tag”

 

Select Surrounded Text from the given options.

Page 228: ABAP Tutorials

 

Save and exit.

To test our code template, write a sample code in our program. 

 

Right click and select our code template.

Page 229: ABAP Tutorials

 

Our code template is displayed as below: 

 

Now just enter the form name to complete your subroutine definition. 

Setting Break-points: 

Open the new ABAP editor and write some sample code in it.

Page 230: ABAP Tutorials

 

Activate your program. 

To set the break-point, click on indicator margin, available on the left side of the line numbers. (See the screenshot below): 

 

Break-point in set now. 

Working with Menu Painter

By Raghava Vakada, Mouri Tech Solutions

For theoretical concepts on Menu Painter, please visit SAP.help.com 

Create a program in SE38 T- Code. 

Page 231: ABAP Tutorials

 

Enter the Title of the Program And Select the Type as Executable Program.

And click on save. Save it in a Relevant Package. 

 

Go to T-code SE41

Enter the Program name and Status name. 

Page 232: ABAP Tutorials

 

Click on create 

 

Enter the Short text for Status. 

Page 233: ABAP Tutorials

 

Click on Menu Bar.

Specify a Menu Name file 

 

Double click on File. 

Page 234: ABAP Tutorials

 

Enter the Code and text Values. 

 

Click on save, check and Activate.

Press Execute or F8. 

Page 235: ABAP Tutorials

 

Click on Continue and Enter. 

 

Created Menu is displayed here. 

Page 236: ABAP Tutorials

To create a Title, Click on Title List. 

Click on create. 

 

Enter the Title Code and Title. Click on continue. 

 

Page 237: ABAP Tutorials

Click on enter and Click on Test. 

 Enter the created Title Code in Title, Click on execute.

Click on Continue.

Page 238: ABAP Tutorials

 Created Title Displayed. 

 Click on Save.

*&---------------------------------------------------------------------**& Report ZMENU_PAINTER*&*&---------------------------------------------------------------------**&*&*&---------------------------------------------------------------------*REPORT ZMENU_PAINTER.TABLES: MARA.DATA: MATNR TYPE MARA-MATNR, ERSDA TYPE MARA-ERSDA, ERNAM TYPE MARA-ERNAM, DISPLAY TYPE C, SAVE TYPE C, DELETE TYPE C, CLEAR TYPE C, EXIT TYPE C, OK_CODE LIKE SY-UCOMM.CALL SCREEN 101.*&---------------------------------------------------------------------*

Page 239: ABAP Tutorials

*& Module STATUS_0101 OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*MODULE STATUS_0101 OUTPUT. SET PF-STATUS 'ZMENU'. SET TITLEBAR 'ZMENU_PAINTER'. CASE SY-UCOMM. WHEN 'EXIT'. LEAVE PROGRAM. WHEN 'BACK'. LEAVE PROGRAM. WHEN 'DISPLAY'.SELECT SINGLE ERSDA ERNAM FROM MARA INTO (MARA-ERSDA, MARA-ERNAM) WHERE MATNR = MARA-MATNR. WHEN 'CLEAR'. CLEAR MARA. ENDCASE.ENDMODULE. " STATUS_0101 OUTPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0101 INPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*MODULE USER_COMMAND_0101 INPUT.ENDMODULE. " USER_COMMAND_0101 INPUT

 Click on middle Icon .

Page 240: ABAP Tutorials

 Enter MARA in the Table/Fieldname Text Box Then click on Get From Dictionary.

Page 241: ABAP Tutorials

  Select the require fields and click on continue. 

 Insert these boxes on the screen.

Page 242: ABAP Tutorials

You can view like this after placing the boxes.

Page 243: ABAP Tutorials

 

Create require Push buttons from toolbox.

Page 244: ABAP Tutorials

 Create require check box from toolbox. 

 Give the required Name , Text and Function Code Name .

 Click on Save, Check and Activate.

Page 245: ABAP Tutorials

 Output:

 Enter the Material number and Press Display.

 

 Click on Display.

Page 246: ABAP Tutorials

 Values are displayed as shown below. 

 Similarly You Can View Clear And Exit. 

Clear – It will clear all the displayed contents.

Page 247: ABAP Tutorials

 Exit - It will return to code..

 We can Use the same operation in Function Keys. 

F5 Clear F6 Display

F7 Exit.

Page 248: ABAP Tutorials

 

 Enter the Material and Press F6 .

The same functionality F5 to Clear and F7 to Exit.

Dynamic Variant in a report

By Suraj Kumar Pabbathi, YASH Technologies

Scenario: This blog is to explain the creation of Dynamic Variant for report selection screen.

Let us understand ‘What is Dynamic Variant?’ Dynamic Variant consists of selection variable for a selection screen item where in a formula can be defined. For example: On the selection screen of a report, take a Date field, which needs to be dynamic. From Date should be ‘Current date – 15’ and To Date should be ‘Current Date’. In this way the report when run with this variant, it would be possible to retrieve all those records which are past 15 days entries from now.

Please find below the procedure to define DYNAMIC Variant. 

Page 249: ABAP Tutorials

Step 1: Go to transaction SE38 to specify the Program name and select ‘Variant’ radio button and ‘Display’.

Then it will lead you to next screen ‘ABAP:Variants –Initial Screen’ as shown below: Specify the variant which needs to be created or changed. 

 

Step2: Specify all those values which are static on the selection screen in this step. Then click ‘Variant Attributes’ to define selection variable for ‘Date Created’ on the selection screen. 

Page 250: ABAP Tutorials

 

Step 3: In this step, provide suitable meaning for the variant. As we need to define selection variable for ‘Date created’ item on selection screen, check the box under L as shown in the selection screen below:

Page 251: ABAP Tutorials

 

Step 4: In the previous step, select ‘Selection Variables’ on the menu. It leads to the next screen as shown below. As we have decided to create selection variable for ‘Date created’ item only, in this screen you get to see the variable as ‘Date created’. Here you are provided with three options.

T: Table variable from TVARV

D: Dynamic Date Calculation

B: User defined Variables. 

From the provided options as per our requirement select ‘D’ option. This can be done by clicking the Traffic lights under ‘D’as shown below to know that the particular option is selected.

Now click the black arrow as shown in the screenshot below and you will be prompted with search help of different formulas for the selection variable. 

Page 252: ABAP Tutorials

 

Step 5: Find the suitable formula as ‘Current date – xxx, current date + yyy’ and select it. This will lead you to the next screen to enter the values for xxx and yyy. So, provide values as 15 for xxx and 0 for yyy. Save the variant and this will conclude the creation of dynamic variant with the help of selection variable. This variant can also be used in the background jobs. 

 

Page 253: ABAP Tutorials

 Creating F1 helps in ease

By Gaurab Banerji

Go to SE61 and create a general text TX like the one shown below.

Select General Text from Document Class Select Language

Type Name and press create

 Type in what you want to see in output

U1 is for the Bold Text you see in the heading of the F1 Help. If you don’t want to specify a bold text you can just type it in the DOKTITLE in the function module called. 

Save the Text.

Now Displaying the F1 Help. I have modified an existing program for showing F1 help. See below

*&---------------------------------------------------------------------**& Report  ZGB_TEST_SEARCH_HELP                                        *

Page 254: ABAP Tutorials

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

REPORT ZGB_TEST_SEARCH_HELP .* INTERNAL TABLE FOR STORING NAMES IN SELECTION LISTdata: begin of t_itab occurs 0, name(10) type c, end of t_itab.*FIELDNAME AND TAB NAME FOR THE SELECTIONDATA :field_tab LIKE dfies OCCURS 0 WITH HEADER LINE.*THE TABLE FOR RETURNING THE NAME OF THE SELECTED ITEMDATA : return_tab LIKE ddshretval OCCURS 0 WITH HEADER LINE.*START THE SELECTION SCREEN BLOCKselection-screen begin of block ss1 with frame.parameters: p_name1(10) type c.selection-screen end of block ss1.*&---------------------------------------------------------------------**& **& F4 Help for p_name1 **&---------------------------------------------------------------------*at selection-screen on value-request for p_name1.*CLEAR ALL EXISTING DATA*TO BE DONE EVERYTIME F4 HELP IS REQUESTEDREFRESH t_itab.REFRESH field_tab. field_tab-fieldname = 'ERNAM'. field_tab-tabname = 'VBAK'.APPEND field_tab.t_itab-name = 'Andrews'.append t_itab.t_itab-name = 'Jennie'.append t_itab.CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST' EXPORTING* DDIC_STRUCTURE = ' ' retfield = field_tab-fieldname* PVALKEY = ' '* DYNPPROG = ' '* DYNPNR = ' '* DYNPROFIELD = ' '* STEPL = 0 WINDOW_TITLE = 'Select name'* VALUE = ' '* VALUE_ORG = 'C'* MULTIPLE_CHOICE = ' '* DISPLAY = ' '* CALLBACK_PROGRAM = ' '* CALLBACK_FORM = ' '* MARK_TAB =* IMPORTING* USER_RESET = tables value_tab = t_itab

Page 255: ABAP Tutorials

FIELD_TAB = field_tab RETURN_TAB = return_tab* DYNPFLD_MAPPING = EXCEPTIONS PARAMETER_ERROR = 1 NO_VALUES_FOUND = 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.else.p_name1 = return_tab-fieldval.ENDIF.*&---------------------------------------------------------------------**& **& F1 Help for p_name1 **&---------------------------------------------------------------------*at selection-screen on help-request for p_name1.CALL FUNCTION 'DSYS_SHOW_FOR_F1HELP' EXPORTING* APPLICATION = 'SO70' dokclass = 'TX' DOKLANGU = SY-LANGU dokname = 'Z_GAURAB_DEMO'* DOKTITLE = 'This appears as bold title'* HOMETEXT = ' '* OUTLINE = ' '* VIEWNAME = 'STANDARD'* Z_ORIGINAL_OUTLINE = ' '* CALLED_FROM_SO70 = ' '* SHORT_TEXT = ' '* APPENDIX = ' '* IMPORTING* APPL =* PF03 =* PF15 =* PF12 = EXCEPTIONS CLASS_UNKNOWN = 1 OBJECT_NOT_FOUND = 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.

Apart from the FM DSYS_SHOW_FOR_F1HELP,following FM’s can also be used:

1. HELP_OBJECT_SHOW_FOR_FIELD 2. HELP_OBJECT_SHOW

Here is the output

Page 256: ABAP Tutorials

 

 

 Object oriented programming (OOP) explained with an example

By Gaurab Banerji

Create a class that keeps track of a bank account balance. Then write a program to use this class.

Steps involved:

Run the class builder utility (SE24). Create a class called ZACCOUNTxx, where xx is the last two digits of your logon ID.

Declare a PRIVATE attribute BALANCE of type DMBTR to store the account balance.

Create the following PUBLIC methods: 

o SET_BALANCE (Sets the balance to a new value)

IMPORTING NEW_BALANCE TYPE DMBTR 

o DEPOSIT (Adds a deposit amount to the balance and returns the new balance)

IMPORTING AMOUNT TYPE DMBTR

RETURNING NEW_BALANCE TYPE DMBTR

o WITHDRAW (Subtracts a deposit amount from the balance and returns the new balance.)

IMPORTING AMOUNT TYPE DMBTR

RETURNING NEW_BALANCE TYPE DMBTR

EXCEPTIONS INSUFFICIENT_FUNDS

Page 257: ABAP Tutorials

Activate all elements of your class.

Write a program called Z_USE_ACCOUNT_xx, where xx is the last two digits of your logon ID. This program should do the following:

o Instantiate an instance of the Account class.

o Set the account balance to some initial value.

o Make several deposits and withdrawals, printing the new balance each time. Do not allow the balance to become less than zero. (Use the exception to detect this.)

Test and debug your program. 

"Extra Credit": If you have extra time, try any of the following:

Replace the SET_BALANCE method with a constructor. Pass the opening balance when you instantiate the account object.

Create a static attribute and methods to set and get the name of the bank that holds the accounts.

Step-by-step approach with screen-shots

Go to SE24 (Class builder) 

Type in ZACCOUNTAA as the name of the class and press Create. 

 

Define 3 methods DEPOSIT, SET_BALANCE and WITHDRAW. 

 

Page 258: ABAP Tutorials

Place the mouse cursor in DEPOSIT and hit the Parameters button. 

 

Write the parameters imported / exported for DEPOSIT method. 

Similarly for SET_BALANCE 

 

And WITHDRAW 

 

For withdraw we define an exception. 

 

We can see the attributes and methods by pressing “Display object list” button on top. 

Page 259: ABAP Tutorials

 

Now we IMPLEMENT the 3 methods. Double click the method DEPOSIT. 

Write the required code. Similarly for SET_BALANCE 

 

Similarly for WITHDRAW. 

Page 260: ABAP Tutorials

 

Now we are almost done creating the object. Press CTRL + F3 to activate or hit the Matchstick.  

We will see this in the status  

Now we are done building the global class we can test it. Press F8. 

 

Click SET_BALANCE. Write the NEW_BALANCE and press ENTER. 

Page 261: ABAP Tutorials

 

We come back to Initial Screen. Now click DEPOSIT.

 

We see the return Values now. 

 

Now let’s WITHDRAW 4000

 

 

Now the BALANCE is 2000 

Lets try withdrawing 3000 now. 

Page 262: ABAP Tutorials

We get an exception. 

Given below is an example code for using the global class we defined.

REPORT  ZGB_OOPS_BANK                                               .

DATA: acct1 type ref to zaccountaa.

DATA: bal type i.

create object: acct1.

selection-screen begin of block a.parameters: p_amnt type dmbtr,            p_dpst type dmbtr,            p_wdrw type dmbtr.selection-screen end of block a.

start-of-selection.

call method acct1->set_balance( p_amnt ).write:/ 'Set balance to ', p_amnt.

bal = acct1->deposit( p_dpst ).write:/ 'Deposited ', p_dpst ,' bucks making balance to ', bal.

bal = acct1->withdraw( p_wdrw ).write:/ 'Withdrew ', p_wdrw ,' bucks making balance to ', bal.

This is the output. 

Page 263: ABAP Tutorials

 Calling an RFC function module from one system to another

By Gaurab Banerji

Following are the participant system for our demo purpose:

D05 – System where RFC function module exists

DS3 – Calling system (an RFC call is made from this system to D05)  

Scenario:

We would develop a small RFC function module in D05 system, which would add two variables. We would pass two variables from DS3 to D05 and get back the sum of those two variables back to DS3.  

Activities to be performed in the system D05 

Go to SE37.

Under Utilities > Create Function Group (say ZGB_FUNC), if doesn’t exists. 

Now create a New Function Module ZGB_FUNC01  

 

Page 264: ABAP Tutorials

Under IMPORT Tab, define the following variables

Under EXPORT Tab  

 

In the Source Code

Now set the function module as “Remote-enabled module” in the attributes tab.  

Page 265: ABAP Tutorials

 

Activities to be performed in the System DS3 

Create an RFC destination from DS3 to D05.

Go to SM59, Press Create.

Enter the RFC Destination name: D05-205-TEST

Connection Type: 3

In Description: Test Connection to D05  

In The Technical Settings Tab, enter the system details

Page 266: ABAP Tutorials

In The Logon/Security Tab, enter the logon details.

Click on Save. A Popup will imply that connection has been created  

Now Press the TEST CONNECTION to check the connection.  

This means the connection to the remote system was successful.

If the connection fails we get an error like this

However establishing a connection will not ensure logging on to the target system. For that we have to test REMOTE LOGON. 

Press the REMOTE LOGON button 

If we can see this

And this

 

Then our connection was successful. 

Page 267: ABAP Tutorials

However if we see the screen as shown below then there is an authentication failure (user-id or password is wrong). 

 

The new connection will become visible in the SM59 list like this.

 

After establishing the connection, let us create a program, which would trigger the RFC in D05 system. 

Go to SE38 and create a program ZGB_RFC 

Write the following code

Page 268: ABAP Tutorials

 

Activate (Ctrl+F3) and Execute (F8) 

Type any two numbers. 

 

Press (F8) Again. We have the desired output. 

 

Page 269: ABAP Tutorials

Uploading Material Master Long Text (Basic data text, Inspection text, Internal comment)

By Teja

This program could be used to upload the material master long text (Basic data text, inspection text, internal comment). Following is the screenshot from the transaction MM02.

 

We can achieve this functionality by using the Function Module ‘CREATE_TEXT’. 

Please note that if the long text already exists, then it is overwritten in this case. 

REPORT ZMM_INSERT_LONGTEXT.*Internal table to hold long text...DATA: BEGIN OF T_UPLOAD OCCURS 0, MATNR LIKE MARA-MATNR, " Material number ID(2) TYPE C, " Identification LTEXT LIKE TLINE-TDLINE, " Long text END OF T_UPLOAD,*Internal table to hold long text.... T_LINE LIKE TLINE OCCURS 0 WITH HEADER LINE.DATA:

Page 270: ABAP Tutorials

W_GRUN LIKE THEAD-TDID , " To hold id W_OBJECT LIKE THEAD-TDOBJECT VALUE 'MATERIAL', " To hold object id LV_VALUE(70). " Value to hold material numberSTART-OF-SELECTION.* This perform is used to upload the file PERFORM UPLOAD_FILE.* This perform is used to place the text in MM02 transaction PERFORM PLACE_LONGTEXT.*&---------------------------------------------------------------------**& Form create_text*&---------------------------------------------------------------------** This routine used to create text in MM02 transaction*----------------------------------------------------------------------** Passed the parameter w_grun to P_C_GRUN* and lv_value to P_LV_VALUE*----------------------------------------------------------------------*FORM CREATE_TEXT USING P_C_GRUN P_LV_VALUE. DATA: L_ID LIKE THEAD-TDID, L_NAME(70). MOVE : P_C_GRUN TO L_ID, P_LV_VALUE TO L_NAME. CALL FUNCTION 'CREATE_TEXT' EXPORTING FID = L_ID FLANGUAGE = SY-LANGU FNAME = L_NAME FOBJECT = W_OBJECT* SAVE_DIRECT = 'X'* FFORMAT = '*' TABLES FLINES = T_LINE EXCEPTIONS NO_INIT = 1 NO_SAVE = 2 OTHERS = 3 . IF SY-SUBRC <> 0. CLEAR LV_VALUE. ELSE. DELETE T_LINE INDEX 1. ENDIF.ENDFORM. " create_text*&---------------------------------------------------------------------**& Form upload_file*&---------------------------------------------------------------------** This routine is used to upload file*----------------------------------------------------------------------** No interface parameters are passed*----------------------------------------------------------------------*FORM UPLOAD_FILE . CALL FUNCTION 'UPLOAD' EXPORTING* CODEPAGE = ' '* FILENAME = ' '

Page 271: ABAP Tutorials

FILETYPE = 'DAT'* ITEM = ' '* FILEMASK_MASK = ' '* FILEMASK_TEXT = ' '* FILETYPE_NO_CHANGE = ' '* FILEMASK_ALL = ' '* FILETYPE_NO_SHOW = ' '* LINE_EXIT = ' '* USER_FORM = ' '* USER_PROG = ' '* SILENT = 'S'* IMPORTING* FILESIZE =* CANCEL =* ACT_FILENAME =* ACT_FILETYPE = TABLES DATA_TAB = T_UPLOAD EXCEPTIONS CONVERSION_ERROR = 1 INVALID_TABLE_WIDTH = 2 INVALID_TYPE = 3 NO_BATCH = 4 UNKNOWN_ERROR = 5 GUI_REFUSE_FILETRANSFER = 6 OTHERS = 7 . IF SY-SUBRC <> 0.* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. SORT T_UPLOAD BY MATNR ID.ENDFORM. " upload_file*&---------------------------------------------------------------------**& Form place_longtext*&---------------------------------------------------------------------** This routine places the text in MM02 transaction*----------------------------------------------------------------------** No interface parameters are passed*----------------------------------------------------------------------*FORM PLACE_LONGTEXT . LOOP AT T_UPLOAD. T_LINE-TDFORMAT = 'ST'. T_LINE-TDLINE = T_UPLOAD-LTEXT. APPEND T_LINE. IF T_UPLOAD-ID EQ 'BT'. MOVE T_UPLOAD-MATNR TO LV_VALUE. MOVE 'GRUN' TO W_GRUN. "Test ID for Basic data text PERFORM CREATE_TEXT USING W_GRUN LV_VALUE. ENDIF. IF T_UPLOAD-ID EQ 'IT'. CLEAR W_GRUN. MOVE T_UPLOAD-MATNR TO LV_VALUE. MOVE 'PRUE' TO W_GRUN. "Test ID for Inspection text PERFORM CREATE_TEXT USING W_GRUN LV_VALUE. ENDIF. IF T_UPLOAD-ID EQ 'IC'.

Page 272: ABAP Tutorials

CLEAR W_GRUN. MOVE : T_UPLOAD-MATNR TO LV_VALUE, 'IVER' TO W_GRUN. "Test ID for Internal comment PERFORM CREATE_TEXT USING W_GRUN LV_VALUE. ENDIF. ENDLOOP.ENDFORM. " place_longtext

System Debugging

By Selvamani

Consider the following program, which contains a simple call to the function module ICON_SHOW. 

 

Set a breakpoint at the CALL FUNCTION statement and now execute the program.

Page 273: ABAP Tutorials

Ensure that the system debugging is switched off, by selecting Settings à system debugging.

On pressing F5, instead of going into the code of the function module, the function module is executed and the following pop-up is shown: 

 

Page 274: ABAP Tutorials

Select a record and press CONTINUE, the program is executed without going into the debug mode of the function module. Reason? 

Now go to the function module ICON_SHOW. Select Goto à Main Program.

Now again select Goto à Attributes

Page 275: ABAP Tutorials

 

 

From the above screenshot, it is understood that the program status is ‘S’ (System program). In order to debug the system program, we need to set the system debugging ON. Now repeat the above debugging by setting system debugging ON. This time, we should be able to debug the function module. 

Page 276: ABAP Tutorials

Can we set the custom programs as system programs? 

Go to our program which has a call to the function module ICON_SHOW. Set the debug point at the CALL FUNCTION statement. 

 

Go to program attributes and set the status to System Program.

 

Now try debugging the program with system debugging off. This time, the debug point will not even reach the CALL FUNCTION statement. Once you turn the system debugging ON, both our program and the standard function module could be debugged.

MESSAGE xxxx RAISING xxxx

Page 277: ABAP Tutorials

By Suresh Kumar Parvathaneni

In general, exceptions in a function module are handled by means of RAISE EXCEPTION. This sets a return code which is passed back to the calling program. 

For eg., let us consider an example of a function module SXXXX, which would create a purchase order with reference to a Purchase Requisition. The import parameter for this function module is Purchase Requisition number and the export parameter is the Purchase Order number created here. Assume that after a PR is created, a material is moved from one plant to another. Now during the PO creation, because of this mismatch the PO would not be created.  

In a normal case, if there is any mismatch, we generally use RAISE EXCEPTION XXXX. This would stop the function module from further processing and returns to the calling program with just the return code. But the calling program would never know the material number that caused this error.  

Now, instead of raising the exception using RAISE EXCEPTION, we would use the following statement:  

MESSAGE E309(06) with ‘xxx’ Raising XXXX.  

Using the above statement is similar to the usage of RAISE EXCEPTION, except for:

If the call to the function module does not handle EXCEPTIONS, then the message is issued (in this case the error message is issued)

If the calling program handles the exception, then no message is issued. The calling program would have the message details in the standard message variables SY-MSGID, SY-MSGV1 and others. So in our case, the calling program would have the information about the material and plant combination that triggered the exception.

Page 278: ABAP Tutorials

Differences between LSMW and BDC

Batch Data Communication (BDC) is the oldest batch interfacing technique that SAP provided since the early versions of R/3. BDC is not atypical integration tool, in the sense that, it can be only be used for uploading data into R/3 and so it is not bi-directional.BDC works on the principle of simulating user input for transactional screen, via an ABAP program. Typically the input comes in the formof a flat file. The ABAP program reads this file and formats the input data screen by screen into an internal table (BDCDATA). Thetransaction is then started using this internal table as the input and executed in the background.

In Call Transaction, the transactions are triggered at the time of processing itself and so the ABAP program must do the error handling.It can also be used for real-time interfaces and custom error handling & logging features. Whereas in Batch Input Sessions, the ABAPprogram creates a session with all the transactional data, and this session can be viewed, scheduled and processed (usingTransaction SM35) at a later time. The latter technique has a built-in error processing mechanism too.

Batch Input (BI) programs still use the classical BDC approach but doesnt require an ABAP program to be written to format theBDCDATA. The user has to format the data using predefined structures and store it in a flat file. The BI program then reads this andinvokes the transaction mentioned in the header record of the file.

Direct Input (DI) programs work exactly similar to BI programs. But the only difference is, instead of processing screens they validatefields and directly load the data into tables using standard function modules. For this reason, DI programs are much faster (RMDATIND - Material Master DI program works at least 5 times faster) than the BDC counterpart and so ideally suited for loading large volume data. DI programs arenot available for all application areas.

LSMW is an encapsulated data transfer tool. It can provide the same functionality as BDC infact much more but when coming to techinical perspective most the parameters are encapulated. To listout some of the differences :

LSMW is basicaly designed for a fuctional consultant who do not do much coding but need to explore the fuctionality while BDC is designed for a technical consultant.

LSMW offers different techinque for migrating data: Direct input ,BAPI,Idoc,Batch input recording. While bdc basically uses recording.

Page 279: ABAP Tutorials

LSMW mapping is done by SAP while in BDC we have to do it explicitly .

LSMW is basically for standard SAP application while bdc basically for customized application.

Coding can be done flexibly in BDC when compared to LSMW

ABAP Performance Standards

Following are the performance standards need to be following in writing ABAP programs:

1. Unused/Dead code

Avoid leaving unused code in the program. Either comment out or delete the unused situation. Use program --> check --> extended program to check for the variables, which are not used statically.

2. Subroutine Usage

For good modularization, the decision of whether or not to execute a subroutine should be made before the subroutine is called. For example:  

This is better:IF f1 NE 0.

PERFORM sub1.

ENDIF.

FORM sub1. ... ENDFORM.

Than this:

PERFORM sub1.

FORM sub1. IF f1 NE 0. ... ENDIF.

ENDFORM.

Page 280: ABAP Tutorials

3. Usage of IF statements

When coding IF tests, nest the testing conditions so that the outer conditions are those which are most likely to fail. For logical expressions with AND , place the mostly likely false first and for the OR, place the mostly likely true first.

Example - nested IF's:

IF (least likely to be true).

IF (less likely to be true).

IF (most likely to be true). ENDIF. ENDIF. ENDIF.

Example - IF...ELSEIF...ENDIF :

IF (most likely to be true).

ELSEIF (less likely to be true).

ELSEIF (least likely to be true).

ENDIF.

Example - AND:

IF (least likely to be true) AND (most likely to be true).

ENDIF.

Example - OR:

IF (most likely to be true) OR (least likely to be true).

4. CASE vs. nested Ifs

When testing fields "equal to" something, one can use either the nested IF or the CASE statement. The CASE is better for two reasons. It is easier to read and after about five nested IFs the performance of the CASE is more efficient. 

Page 281: ABAP Tutorials

5. MOVE statements

When records a and b have the exact same structure, it is more efficient to MOVE a TO b than to  MOVE-CORRESPONDING a TO b.

 MOVE BSEG TO *BSEG.

is better than

MOVE-CORRESPONDING BSEG TO *BSEG.

6. SELECT and SELECT SINGLE

When using the SELECT statement, study the key and always provide as much of the left-most part of the key as possible. If the entire key can be qualified, code a SELECT SINGLE not just a SELECT.   If you are only interested in the first row or there is only one row to be returned, using SELECT SINGLE can increase performance by up to three times. 

7. Small internal tables vs. complete internal tables

In general it is better to minimize the number of fields declared in an internal table.  While it may be convenient to declare an internal table using the LIKE command, in most cases, programs will not use all fields in the SAP standard table. 

For example:

Instead of this:

data:  t_mara like mara occurs 0 with header line.

Use this:

data: begin of t_mara occurs 0,

        matnr like mara-matnr,        ...        end of t_mara. 

8. Row-level processing and SELECT SINGLE

Similar to the processing of a SELECT-ENDSELECT loop, when calling multiple SELECT-SINGLE commands on a non-buffered table (check Data Dictionary -> Technical Info), you should do the following to improve performance: 

o Use the SELECT into <itab> to buffer the necessary rows in an internal table, then

o sort the rows by the key fields, then 

o use a READ TABLE WITH KEY ... BINARY SEARCH in place of the SELECT SINGLE command. Note that this only make sense when the table you are buffering is not too large (this decision must be made on a case by case basis).

9. READing single records of internal tables

Page 282: ABAP Tutorials

When reading a single record in an internal table, the READ TABLE WITH KEY is not a direct READ.  This means that if the data is not sorted according to the key, the system must sequentially read the table.   Therefore, you should:

o SORT the table

o use READ TABLE WITH KEY BINARY SEARCH for better performance. 

10. SORTing internal tables

When SORTing internal tables, specify the fields to SORTed.

SORT ITAB BY FLD1 FLD2.

 is more efficient than

SORT ITAB.  

11. Number of entries in an internal table

To find out how many entries are in an internal table use DESCRIBE.

DESCRIBE TABLE ITAB LINES CNTLNS.

 is more efficient than

LOOP AT ITAB.

  CNTLNS = CNTLNS + 1.

ENDLOOP. 

12. Performance diagnosis

To diagnose performance problems, it is recommended to use the SAP transaction SE30, ABAP/4 Runtime Analysis. The utility allows statistical analysis of transactions and programs. 

13. Nested SELECTs versus table views

Since releASE 4.0, OPEN SQL allows both inner and outer table joins.  A nested SELECT loop may be used to accomplish the same concept.  However, the performance of nested SELECT loops is very poor in comparison to a join.  Hence, to improve performance by a factor of 25x and reduce network load, you should either create a view in the data dictionary then use this view to select data, or code the select using a join. 

14. If nested SELECTs must be used

As mentioned previously, performance can be dramatically improved by using views instead of nested SELECTs, however, if this is not possible, then the following example of using an internal table in a nested SELECT can also improve performance by a factor of 5x:

Use this:form select_good.

  data: t_vbak like vbak occurs 0 with header line.  data: t_vbap like vbap occurs 0 with header line.

  select * from vbak into table t_vbak up to 200 rows.

Page 283: ABAP Tutorials

  select * from vbap           for all entries in t_vbak          where vbeln = t_vbak-vbeln.    ...  endselect.

endform.

Instead of this:form select_bad.

 select * from vbak up to 200 rows.

  select * from vbap where vbeln = vbak-vbeln.      ...  endselect.

 endselect.

endform.

Although using "SELECT...FOR ALL ENTRIES IN..." is generally very fast, you should be aware of the three pitfalls of using it:

Firstly, SAP automatically removes any duplicates from the rest of the retrieved records.  Therefore, if you wish to ensure that no qualifying records are discarded, the field list of the inner SELECT must be designed to ensure the retrieved records will contain no duplicates (normally, this would mean including in the list of retrieved fields all of those fields that comprise that table's primary key).

Secondly,  if you were able to code "SELECT ... FROM <database table> FOR ALL ENTRIES IN TABLE <itab>" and the internal table <itab> is empty, then all rows from <database table> will be retrieved.

Thirdly, if the internal table supplying the selection criteria (i.e. internal table <itab> in the example "...FOR ALL ENTRIES IN TABLE <itab> ") contains a large number of entries, performance degradation may occur. 

15. SELECT * versus SELECTing individual fields

In general, use a SELECT statement specifying a list of fields instead of a SELECT * to reduce network traffic and improve performance.  For tables with only a few fields the improvements may be minor, but many SAP tables contain more than 50 fields when the program needs only a few.  In the latter case, the performace gains can be substantial.  For example:

Use:

select vbeln auart vbtyp from table vbak

  into (vbak-vbeln, vbak-auart, vbak-vbtyp)

  where ...

Instead of using:

select * from vbak where ... 

16. Avoid unnecessary statements

There are a few cases where one command is better than two.  For example:

Use:

Page 284: ABAP Tutorials

append <tab_wa> to <tab>.

Instead of:

<tab> = <tab_wa>.

append <tab> (modify <tab>).

And also, use:

if not <tab>[] is initial.

Instead of:

describe table <tab> lines <line_counter>.

if <line_counter> > 0. 

17. Copying or appending internal tables

Use this: 

<tab2>[] = <tab1>[].  (if <tab2> is empty)

Instead of this:

loop at <tab1>.

  append <tab1> to <tab2>.

endloop.

However, if <tab2> is not empty and should not be overwritten, then use:

append lines of <tab1> [from index1] [to index2] to <tab2>.

Create/Modify/Delete records in any table from CSV file

By Pavan

Allows to create, modify or delete records based on data coming from a CSV file. No other format than CSV is allowed. A check is done on field names to be sure every key field is present in source file. This file must contain header with fields names corresponding to the DDIC (fields names must be comma separated too). Some system fields can be updated too. Test run uses a true MODIFY / DELETE statement but is followed by a Rollback.

REPORT csv_upload LINE-SIZE 255.

* DataDATA: it_dd03p TYPE TABLE OF dd03p,            is_dd03p TYPE dd03p.

DATA: it_rdata TYPE TABLE OF text1024,            is_rdata TYPE text1024.

DATA: it_fields TYPE TABLE OF fieldname.

DATA: it_file TYPE REF TO data,             is_file TYPE REF TO data.

Page 285: ABAP Tutorials

DATA: w_error TYPE text132.

* MacrosDEFINE write_error.   concatenate 'Error: table'                           p_table                           &1                           &2                    into w_error     separated by space.   condense w_error.    write: / w_error.    stop.END-OF-DEFINITION.

* Field symbolsFIELD-SYMBOLS: <table> TYPE STANDARD TABLE,                                 <data> TYPE ANY,                                  <fs> TYPE ANY.

* Selection screenSELECTION-SCREEN: BEGIN OF BLOCK b01 WITH FRAME TITLE text-b01.PARAMETERS: p_file TYPE localfile DEFAULT 'C:\temp\' OBLIGATORY,p_separ TYPE c DEFAULT ';' OBLIGATORY.SELECTION-SCREEN: END OF BLOCK b01.

SELECTION-SCREEN: BEGIN OF BLOCK b02 WITH FRAME TITLE text-b02.PARAMETERS: p_table TYPE tabname OBLIGATORYMEMORY ID dtbMATCHCODE OBJECT dd_dbtb_16.SELECTION-SCREEN: END OF BLOCK b02.

SELECTION-SCREEN: BEGIN OF BLOCK b03 WITH FRAME TITLE text-b03.PARAMETERS: p_create TYPE c AS CHECKBOX.SELECTION-SCREEN: END OF BLOCK b03,SKIP.

SELECTION-SCREEN: BEGIN OF BLOCK b04 WITH FRAME TITLE text-b04.PARAMETERS: p_nodb RADIOBUTTON GROUP g1 DEFAULT 'X'USER-COMMAND rg1,p_save RADIOBUTTON GROUP g1,p_dele RADIOBUTTON GROUP g1.SELECTION-SCREEN: SKIP.PARAMETERS: p_test TYPE c AS CHECKBOX,p_list TYPE c AS CHECKBOX DEFAULT 'X'.SELECTION-SCREEN: END OF BLOCK b04.

* At selection screenAT SELECTION-SCREEN.IF sy-ucomm = 'RG1'.IF p_nodb IS INITIAL.p_test = 'X'.ENDIF.

Page 286: ABAP Tutorials

ENDIF.

* At selection screenAT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.CALL FUNCTION 'F4_FILENAME'EXPORTINGfield_name = 'P_FILE'IMPORTINGfile_name = p_file.

* Start of selectionSTART-OF-SELECTION.

PERFORM f_table_definition USING p_table.

PERFORM f_upload_data USING p_file.

PERFORM f_prepare_table USING p_table.

PERFORM f_process_data.

IF p_nodb IS INITIAL.PERFORM f_modify_table.ENDIF.

IF p_list = 'X'.PERFORM f_list_records.ENDIF.

* End of selectionEND-OF-SELECTION.

*---------------------------------------------------------------------** FORM f_table_definition **---------------------------------------------------------------------** --> VALUE(IN_TABLE) **---------------------------------------------------------------------*FORM f_table_definition USING value(in_table).DATA: l_tname TYPE tabname,l_state TYPE ddgotstate,l_dd02v TYPE dd02v.

l_tname = in_table.CALL FUNCTION 'DDIF_TABL_GET'EXPORTINGname = l_tnameIMPORTINGgotstate = l_statedd02v_wa = l_dd02vTABLESdd03p_tab = it_dd03pEXCEPTIONSillegal_input = 1

Page 287: ABAP Tutorials

OTHERS = 2.IF l_state NE 'A'.write_error 'does not exist or is not active' space.ENDIF.IF l_dd02v-tabclass NE 'TRANSP' ANDl_dd02v-tabclass NE 'CLUSTER'.write_error 'is type' l_dd02v-tabclass.ENDIF.ENDFORM.

*---------------------------------------------------------------------** FORM f_prepare_table **---------------------------------------------------------------------** --> VALUE(IN_TABLE) **---------------------------------------------------------------------*FORM f_prepare_table USING value(in_table).DATA: l_tname TYPE tabname,lt_ftab TYPE lvc_t_fcat.

l_tname = in_table.CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'EXPORTINGi_structure_name = l_tnameCHANGINGct_fieldcat = lt_ftabEXCEPTIONSOTHERS = 1.IF sy-subrc NE 0.WRITE: / 'Error while building field catalog'.STOP.ENDIF.

CALL METHOD cl_alv_table_create=>create_dynamic_tableEXPORTINGit_fieldcatalog = lt_ftabIMPORTINGep_table = it_file.

ASSIGN it_file->* TO <table>.CREATE DATA is_file LIKE LINE OF <table>.ASSIGN is_file->* TO <data>.

ENDFORM.

*---------------------------------------------------------------------** FORM f_upload_data **---------------------------------------------------------------------** --> VALUE(IN_FILE) **---------------------------------------------------------------------*FORM f_upload_data USING value(in_file).DATA: l_file TYPE string,l_ltext TYPE string.

DATA: l_lengt TYPE i,

Page 288: ABAP Tutorials

l_field TYPE fieldname.

DATA: l_missk TYPE c.

l_file = in_file.l_lengt = strlen( in_file ).

FORMAT INTENSIFIED ON.WRITE: / 'Reading file', in_file(l_lengt).CALL FUNCTION 'GUI_UPLOAD'EXPORTINGfilename = l_filefiletype = 'ASC'TABLESdata_tab = it_rdataEXCEPTIONSOTHERS = 1.IF sy-subrc <> 0.WRITE: /3 'Error uploading', l_file.STOP.ENDIF.

* File not emptyDESCRIBE TABLE it_rdata LINES sy-tmaxl.IF sy-tmaxl = 0.WRITE: /3 'File', l_file, 'is empty'.STOP.ELSE.WRITE: '-', sy-tmaxl, 'rows read'.ENDIF.

* File header on first rowREAD TABLE it_rdata INTO is_rdata INDEX 1.l_ltext = is_rdata.WHILE l_ltext CS p_separ.SPLIT l_ltext AT p_separ INTO l_field l_ltext.APPEND l_field TO it_fields.ENDWHILE.IF sy-subrc = 0.l_field = l_ltext.APPEND l_field TO it_fields.ENDIF.

* Check all key fields are presentSKIP.FORMAT RESET.FORMAT COLOR COL_HEADING.WRITE: /3 'Key fields'.FORMAT RESET.LOOP AT it_dd03p INTO is_dd03p WHERE NOT keyflag IS initial.WRITE: /3 is_dd03p-fieldname.READ TABLE it_fields WITH KEY table_line = is_dd03p-fieldnameTRANSPORTING NO FIELDS.IF sy-subrc = 0.FORMAT COLOR COL_POSITIVE.WRITE: 'ok'.

Page 289: ABAP Tutorials

FORMAT RESET.ELSEIF is_dd03p-datatype NE 'CLNT'.FORMAT COLOR COL_NEGATIVE.WRITE: 'error'.FORMAT RESET.l_missk = 'X'.ENDIF.ENDLOOP.

* Log other fieldsSKIP.FORMAT COLOR COL_HEADING.WRITE: /3 'Other fields'.FORMAT RESET.LOOP AT it_dd03p INTO is_dd03p WHERE keyflag IS initial.WRITE: /3 is_dd03p-fieldname.READ TABLE it_fields WITH KEY table_line = is_dd03p-fieldnameTRANSPORTING NO FIELDS.IF sy-subrc = 0.WRITE: 'X'.ENDIF.ENDLOOP.

* Missing key fieldIF l_missk = 'X'.SKIP.WRITE: /3 'Missing key fields - no further processing'.STOP.ENDIF.

ENDFORM.

*---------------------------------------------------------------------** FORM f_process_data **---------------------------------------------------------------------*FORM f_process_data.DATA: l_ltext TYPE string,l_stext TYPE text40,l_field TYPE fieldname,l_datat TYPE c.

LOOP AT it_rdata INTO is_rdata FROM 2.l_ltext = is_rdata.LOOP AT it_fields INTO l_field.ASSIGN COMPONENT l_field OF STRUCTURE <data> TO <fs>.IF sy-subrc = 0.* Field value comes from file, determine conversionDESCRIBE FIELD <fs> TYPE l_datat.CASE l_datat.WHEN 'N'.SPLIT l_ltext AT p_separ INTO l_stext l_ltext.WRITE l_stext TO <fs> RIGHT-JUSTIFIED.OVERLAY <fs> WITH '0000000000000000'. "max 16WHEN 'P'.SPLIT l_ltext AT p_separ INTO l_stext l_ltext.

Page 290: ABAP Tutorials

TRANSLATE l_stext USING ',.'.<fs> = l_stext.WHEN 'F'.SPLIT l_ltext AT p_separ INTO l_stext l_ltext.TRANSLATE l_stext USING ',.'.<fs> = l_stext.WHEN 'D'.SPLIT l_ltext AT p_separ INTO l_stext l_ltext.TRANSLATE l_stext USING '/.-.'.CALL FUNCTION 'CONVERT_DATE_TO_INTERNAL'EXPORTINGdate_external = l_stextIMPORTINGdate_internal = <fs>EXCEPTIONSOTHERS = 1.WHEN 'T'.CALL FUNCTION 'CONVERT_TIME_INPUT'EXPORTINGinput = l_stextIMPORTINGoutput = <fs>EXCEPTIONSOTHERS = 1.WHEN OTHERS.SPLIT l_ltext AT p_separ INTO <fs> l_ltext.ENDCASE.ELSE.SHIFT l_ltext UP TO p_separ.SHIFT l_ltext.ENDIF.ENDLOOP.IF NOT <data> IS INITIAL.LOOP AT it_dd03p INTO is_dd03p WHERE datatype = 'CLNT'.* This field is mandantASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data>TO <fs>.<fs> = sy-mandt.ENDLOOP.IF p_create = 'X'.IF is_dd03p-rollname = 'ERDAT'.ASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data>TO <fs>.<fs> = sy-datum.ENDIF.IF is_dd03p-rollname = 'ERZET'.ASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data>TO <fs>.<fs> = sy-uzeit.ENDIF.IF is_dd03p-rollname = 'ERNAM'.ASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data>TO <fs>.<fs> = sy-uname.ENDIF.ENDIF.

Page 291: ABAP Tutorials

IF is_dd03p-rollname = 'AEDAT'.ASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data>TO <fs>.<fs> = sy-datum.ENDIF.IF is_dd03p-rollname = 'AETIM'.ASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data>TO <fs>.<fs> = sy-uzeit.ENDIF.IF is_dd03p-rollname = 'AENAM'.ASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data>TO <fs>.<fs> = sy-uname.ENDIF.APPEND <data> TO <table>.ENDIF.ENDLOOP.ENDFORM.

*---------------------------------------------------------------------** FORM f_modify_table **---------------------------------------------------------------------*FORM f_modify_table.SKIP.IF p_save = 'X'.MODIFY (p_table) FROM TABLE <table>.ELSEIF p_dele = 'X'.DELETE (p_table) FROM TABLE <table>.ELSE.EXIT.ENDIF.

IF sy-subrc EQ 0.FORMAT COLOR COL_POSITIVE.IF p_save = 'X'.WRITE: /3 'Modify table OK'.ELSE.WRITE: /3 'Delete table OK'.ENDIF.FORMAT RESET.IF p_test IS INITIAL.COMMIT WORK.ELSE.ROLLBACK WORK.WRITE: '- test only, no update'.ENDIF.ELSE.FORMAT COLOR COL_NEGATIVE.WRITE: /3 'Error while modifying table'.FORMAT RESET.ENDIF.ENDFORM.

Page 292: ABAP Tutorials

*---------------------------------------------------------------------** FORM f_list_records **---------------------------------------------------------------------*FORM f_list_records.DATA: l_tleng TYPE i,l_lasti TYPE i,l_offst TYPE i.

* Output widthl_tleng = 1.LOOP AT it_dd03p INTO is_dd03p.l_tleng = l_tleng + is_dd03p-outputlen.IF l_tleng LT sy-linsz.l_lasti = sy-tabix.l_tleng = l_tleng + 1.ELSE.l_tleng = l_tleng - is_dd03p-outputlen.EXIT.ENDIF.ENDLOOP.

* Output headerSKIP.FORMAT COLOR COL_HEADING.WRITE: /3 'Contents'.FORMAT RESET.ULINE AT /3(l_tleng).

* Output recordsLOOP AT <table> ASSIGNING <data>.LOOP AT it_dd03p INTO is_dd03p FROM 1 TO l_lasti.IF is_dd03p-position = 1.WRITE: /3 sy-vline.l_offst = 3.ENDIF.ASSIGN COMPONENT is_dd03p-fieldname OF STRUCTURE <data> TO <fs>.l_offst = l_offst + 1.IF is_dd03p-decimals LE 2.WRITE: AT l_offst <fs>.ELSE.WRITE: AT l_offst <fs> DECIMALS 3.ENDIF.l_offst = l_offst + is_dd03p-outputlen.WRITE: AT l_offst sy-vline.ENDLOOP.ENDLOOP.

* Output endULINE AT /3(l_tleng).

ENDFORM.

Number Range Object

Page 293: ABAP Tutorials

By Suresh Kumar Parvathaneni

 Creation of a Number range object:

1. Go to transaction SNRO (Simple way to remember is SapNumberRangeObject).

2. Enter the number range object name and press CREATE.

3. Enter the description, Long text and Number Length domain andWarning % as shown below:

Page 294: ABAP Tutorials

Warning% à Assume that an interval is defined from 1 to 1000. If you want to issue a warning at the number 900, enter 10 (%) here.

4. Press SAVE. You would get a prompt as shown below:

Page 295: ABAP Tutorials

 

5. Press YES and assign the object to a local class.

6. Now click on “Number Ranges” button on the application toolbar.

 

7. Click on “Change Intervals”.

Page 296: ABAP Tutorials

 

8. Click on “Insert Interval”.

9. Enter the values as shown below:

Page 297: ABAP Tutorials

 

10. Click “Insert” and then SAVE. The number range object is generated. 

Testing the Number Range Object: 

We can use the function module, NUMBER_GET_NEXT, to get the next number of any number range object. 

Following is a test program to get the next available number of the object created above:  

REPORT zsnro_test.

DATA:NUMBER TYPE I.

CALL FUNCTION 'NUMBER_GET_NEXT'EXPORTING nr_range_nr = '01' object = 'ZDEMO'IMPORTING NUMBER = NUMBEREXCEPTIONS INTERVAL_NOT_FOUND = 1 NUMBER_RANGE_NOT_INTERN = 2 OBJECT_NOT_FOUND = 3 QUANTITY_IS_0 = 4 QUANTITY_IS_NOT_1 = 5 INTERVAL_OVERFLOW = 6 BUFFER_OVERFLOW = 7 OTHERS = 8.IF sy-subrc <> 0.

Page 298: ABAP Tutorials

MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.ENDIF.

Write :/ 'Next available number is: ', Number.

Dynamic Internal Table

By Vijayanand Poreddy

This Tutorial details about creation of dynamic internal table with different scenarios

Internal Tables are local tables within a program containing a series of lines having same data type. ABAPTM Open SQL allows single field, range of fields, entire database table or view into an internal table.  

In technical terms Internal table is a dynamic sequential dataset in which all records have the same data structure and a key.  

A static internal table can be declared in an ABAPTM program initially, when the structure of the internal table is fixed and known to the user. 

Dynamic internal table is an extension to internal table concept, used when the number of fields is not known at the design time or until the compile time.

Scenario 1:

Display the table of contents in grid format using the dynamic internal table. 

Creating Dynamic internal table 

PARAMETERS : p_table(10) TYPE C.

  DATA: w_tabname TYPE w_tabname,            

        w_dref TYPE REF TO data,             

        w_grid TYPE REF TO cl_gui_alv_grid. 

  FIELD-SYMBOLS: <t_itab> TYPE ANY TABLE. 

  w_tabname = p_table. 

  CREATE DATA w_dref TYPE TABLE OF (w_tabname).

Page 299: ABAP Tutorials

  ASSIGN w_dref->* TO <t_itab>.

 Populating Dynamic internal table 

  SELECT *

    FROM (w_tabname) UP TO 20 ROWS

    INTO TABLE <t_itab>.

 Displaying dynamic internal table using Grid. 

  CREATE OBJECT w_grid

    EXPORTING i_parent = cl_gui_container=>screen0. 

  CALL METHOD w_grid->set_table_for_first_display

    EXPORTING

      i_structure_name = w_tabname

    CHANGING

      it_outtab        = <t_itab>. 

  CALL SCREEN 100.

 Scenario 2: 

Create a dynamic internal table with the specified number of columns. 

Creating Dynamic internal table

TYPE-POOLS: slis.

 FIELD-SYMBOLS: <t_dyntable> TYPE STANDARD TABLE,  “ Dynamic internal table name

               <fs_dyntable>,                     “ Field symbol to create work area

               <fs_fldval> type any.              “ Field symbol to assign values 

PARAMETERS: p_cols(5) TYPE c.                     “ Input number of columns

Page 300: ABAP Tutorials

DATA:   t_newtable TYPE REF TO data,

        t_newline  TYPE REF TO data,

        t_fldcat   TYPE slis_t_fldcat_alv,

        t_fldcat   TYPE lvc_t_fcat,

        wa_it_fldcat TYPE lvc_s_fcat,

        wa_colno(2) TYPE n,

        wa_flname(5) TYPE c. 

* Create fields .

  DO p_cols TIMES.

    CLEAR wa_it_fldcat.

    move sy-index to wa_colno.

    concatenate 'COL'

                wa_colno

           into wa_flname.

    wa_it_fldcat-fieldname = wa_flname.

    wa_it_fldcat-datatype = 'CHAR'.

    wa_it_fldcat-intlen = 10.

    APPEND wa_it_fldcat TO t_fldcat.

  ENDDO. 

* Create dynamic internal table and assign to FS

  CALL METHOD cl_alv_table_create=>create_dynamic_table

    EXPORTING

      it_fieldcatalog = t_fldcat

Page 301: ABAP Tutorials

    IMPORTING

      ep_table        = t_newtable. 

  ASSIGN t_newtable->* TO <t_dyntable>. 

* Create dynamic work area and assign to FS

  CREATE DATA t_newline LIKE LINE OF <t_dyntable>.

  ASSIGN t_newline->* TO <fs_dyntable>.

Populating Dynamic internal table 

DATA: fieldname(20) TYPE c.

  DATA: fieldvalue(10) TYPE c.

  DATA: index(3) TYPE c. 

  DO p_cols TIMES. 

    index = sy-index.

    MOVE sy-index TO wa_colno.

    CONCATENATE 'COL'

                wa_colno

           INTO wa_flname. 

* Set up fieldvalue

    CONCATENATE 'VALUE' index INTO

                fieldvalue.

    CONDENSE    fieldvalue NO-GAPS. 

    ASSIGN COMPONENT  wa_flname

        OF STRUCTURE <fs_dyntable> TO <fs_fldval>.

<fs_fldval> =  fieldvalue. 

Page 302: ABAP Tutorials

  ENDDO. 

* Append to the dynamic internal table

  APPEND <fs_dyntable> TO <t_dyntable>.

 Displaying dynamic internal table using Grid. 

DATA: wa_cat LIKE LINE OF fs_fldcat. 

  DO p_cols TIMES.

    CLEAR wa_cat.

    MOVE sy-index TO wa_colno.

    CONCATENATE 'COL'

                wa_colno

           INTO wa_flname. 

    wa_cat-fieldname = wa_flname.

    wa_cat-seltext_s = wa_flname.

    wa_cat-outputlen = '10'.

    APPEND wa_cat TO fs_fldcat.

  ENDDO. 

* Call ABAP List Viewer (ALV)

  CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'

    EXPORTING

      it_fieldcat = fs_fldcat

    TABLES

      t_outtab    = <t_dyntable>.

Infotype creation

Page 303: ABAP Tutorials

Custom Infotype can be created by following these steps:1. Go to transaction PM01.2. Provide the Infotype number. The number should be from 9000 to 9999. Avoid providing the Infotypenumber that already exists.3. See to it that the Employee Infotype and PS structure radio buttons have been selected.All Push button4. Select the ‘All’ Push button as shown in above figure. The following below shown screen isdisplayed.5. Maintain the structure (Provide fields) which will be included in our current custom Infotype. ThePAKEY/PBKEY and PSHD1 structures are not required to be provided while creating the customInfotype. They are included in the custom Infotype by default.6. Save and activate the structure. Go to the initial screen of PM01 transaction.Infotype characteristicsPush buttonTechnical AttributesPush button7. Select the ‘Infotype characteristics’ push button shown in the above figure. The below screen isdisplayed.New Entries Push button8. Select the ‘New Entries’ push button shown in the above figure. The below shown screen isdisplayed.9. Provide the Current custom Infotype number (9002) and description for the Infotype. Also provide theTime constraint based on the requirement, 2000 as the single screen and 3000 as the list screen.10. The ‘Subtype Obligatory’ check box needs to be selected if we intend to make the subtype as mandatoryfield. This step is useful when we come through the step 11 (Subtype maintenance).This step can beskipped if we don’t want the subtype for an Infotype.11. Save the Infotype details and go back to the initial screen of PM01 transaction.Additional stepsIf a subtype needs to be maintained for the Infotype then some additional steps also needs to be performedbefore providing Infotype characteristics (step number 7).12. Select the Technical attributes (Figure shown in step 6) from the initial screen of PM01 transaction .The

Page 304: ABAP Tutorials

below shown figure is displayed.13. Select the change button on application tool bar. The dialog module in the above screen then becomeseditable.14. Select the Infotype 9002 and select the details button as shown in the above figure (In change mode).The below shown figure is displayed.Display/Change button Details15. Provide the Subtype field of the Infotype, Subtype table as T591A and Subty.text table as T591S.16. Save and go back to the initial PM01 screen.17. The subtypes for an Infotype can be entered via the maintenance view V_T591A.

18. Continue with step 7 as required.

Automatic Vendor Debit Posting

Submitted by Vikram

Please note that there are some custom fields added in the VBAP table, custom message class and custom include program used in this program. Unfortunately, the contributor couldn't provide us with the functional/technical specifications for this program.

REPORT ZAUTO_DEBIT_VENDOR NO STANDARD PAGE HEADING LINE-SIZE 250 LINE-COUNT 65(2) MESSAGE-ID ZSCM. ************************************************************************* Program name : ZAUTO_DEBIT_VENDOR* Type : Report* Description : Automatic Vendor Dedit Postings************************************************************************

*---------------------------------------------------------------------** TABLES*---------------------------------------------------------------------*TABLES: VBAK, ADR6, TRDYSE01CM. *---------------------------------------------------------------------** INCLUDE*---------------------------------------------------------------------*INCLUDE ZZUTI_STD_HEADER_FOOTER. "Standard header and footer *----------------------------------------------------------------------** TYPES DECLARATION*----------------------------------------------------------------------*

Page 305: ABAP Tutorials

TYPES: BEGIN OF T_CRMEMO, VBELN TYPE VBAK-VBELN, POSNR TYPE VBAP-POSNR, ERDAT TYPE VBAK-ERDAT, AUART TYPE VBAK-AUART, AUGRU TYPE VBAK-AUGRU, WAERK TYPE VBAK-WAERK, VKORG TYPE VBAK-VKORG, VTWEG TYPE VBAK-VTWEG, SPART TYPE VBAK-SPART, VDATU TYPE VBAK-VDATU, BSTNK TYPE VBAK-BSTNK, BSARK TYPE VBAK-BSARK, BSTDK TYPE VBAK-BSTDK, AEDAT TYPE VBAK-AEDAT, BUKRS_VF TYPE VBAK-BUKRS_VF, MATNR TYPE VBAP-MATNR, ZMENG TYPE VBAP-ZMENG, ZIEME TYPE VBAP-ZIEME, END OF T_CRMEMO,  BEGIN OF T_CRMEMO_CHANGE, VBELN(90) TYPE C, POSNR TYPE VBAP-POSNR, ERDAT TYPE VBAK-ERDAT, AUART TYPE VBAK-AUART, AUGRU TYPE VBAK-AUGRU, WAERK TYPE VBAK-WAERK, VKORG TYPE VBAK-VKORG, VTWEG TYPE VBAK-VTWEG, SPART TYPE VBAK-SPART, VDATU TYPE VBAK-VDATU, BSTNK TYPE VBAK-BSTNK, BSARK TYPE VBAK-BSARK, BSTDK TYPE VBAK-BSTDK, AEDAT TYPE VBAK-AEDAT, BUKRS_VF TYPE VBAK-BUKRS_VF, MATNR TYPE VBAP-MATNR, ZMENG TYPE VBAP-ZMENG, ZIEME TYPE VBAP-ZIEME, END OF T_CRMEMO_CHANGE,  BEGIN OF T_MVKE, MATNR TYPE MVKE-MATNR, VKORG TYPE MVKE-VKORG, VTWEG TYPE MVKE-VTWEG, MTPOS TYPE MVKE-MTPOS, END OF T_MVKE,  BEGIN OF T_ORDERS, VBELV TYPE VBFA-VBELV, POSNV TYPE VBFA-POSNV, VBELN TYPE VBFA-VBELN, POSNN TYPE VBFA-POSNN, VBTYP_N TYPE VBFA-VBTYP_N, END OF T_ORDERS,

Page 306: ABAP Tutorials

  BEGIN OF T_EKPO, EBELN TYPE EKKO-EBELN, EBELP TYPE EKPO-EBELP, WAERS TYPE EKKO-WAERS, MENGE TYPE EKPO-MENGE, MEINS TYPE EKPO-MEINS, NETPR TYPE EKPO-NETPR, PEINH TYPE EKPO-PEINH, mwskz TYPE EKPO-mwskz, TXJCD TYPE EKPO-TXJCD, END OF T_EKPO,  BEGIN OF T_EKBE, EBELN TYPE EKBE-EBELN, EBELP TYPE EKBE-EBELP, ZEKKN TYPE EKBE-ZEKKN, VGABE TYPE EKBE-VGABE, GJAHR TYPE EKBE-GJAHR, BELNR TYPE EKBE-BELNR, BUZEI TYPE EKBE-BUZEI, END OF T_EKBE,  BEGIN OF T_RBKP, BELNR TYPE RBKP-BELNR, GJAHR TYPE RBKP-GJAHR, BLDAT TYPE RBKP-BLDAT, BUDAT TYPE RBKP-BUDAT, XBLNR TYPE RBKP-XBLNR, LIFNR TYPE RBKP-LIFNR, RMWWR TYPE RBKP-RMWWR, WMWST1 TYPE RBKP-WMWST1, XRECH TYPE RBKP-XRECH, STBLG TYPE RBKP-STBLG, END OF T_RBKP,  BEGIN OF T_CDHDR, OBJECTCLAS TYPE CDHDR-OBJECTCLAS, OBJECTID TYPE CDHDR-OBJECTID, CHANGENR TYPE CDHDR-CHANGENR, UDATE TYPE CDHDR-UDATE, UTIME TYPE CDHDR-UTIME, END OF T_CDHDR,  BEGIN OF T_CDPOS, OBJECTCLAS TYPE CDHDR-OBJECTCLAS, OBJECTID TYPE CDHDR-OBJECTID, CHANGENR TYPE CDHDR-CHANGENR, TABNAME TYPE CDPOS-TABNAME, TABKEY TYPE CDPOS-TABKEY, FNAME TYPE CDPOS-FNAME, CHNGIND TYPE CDPOS-CHNGIND, VALUE_NEW TYPE CDPOS-VALUE_NEW, VALUE_OLD TYPE CDPOS-VALUE_OLD, END OF T_CDPOS,  BEGIN OF T_CHANGE_DOCS,

Page 307: ABAP Tutorials

OBJECTCLAS TYPE CDHDR-OBJECTCLAS, OBJECTID TYPE CDHDR-OBJECTID, CHANGENR TYPE CDHDR-CHANGENR, UDATE TYPE CDHDR-UDATE, UTIME TYPE CDHDR-UTIME, TABNAME TYPE CDPOS-TABNAME, TABKEY TYPE CDPOS-TABKEY, FNAME TYPE CDPOS-FNAME, CHNGIND TYPE CDPOS-CHNGIND, VALUE_NEW TYPE CDPOS-VALUE_NEW, VALUE_OLD TYPE CDPOS-VALUE_OLD, END OF T_CHANGE_DOCS,  BEGIN OF T_SUCCESS, crmemo TYPE VBAK-vbeln, cmemo TYPE VBAK-vbeln, orders TYPE VBAK-vbeln, po TYPE VBAK-vbeln, miro_no TYPE VBAK-vbeln, text(20) TYPE C, END OF T_SUCCESS,  BEGIN OF T_ERROR, crmemo TYPE VBAK-vbeln, cmemo TYPE VBAK-vbeln, orders TYPE VBAK-vbeln, po TYPE VBAK-vbeln, miro_no TYPE VBAK-vbeln, text(100) TYPE C, END OF T_ERROR. *----------------------------------------------------------------------** WORKAREA DECLARATION*----------------------------------------------------------------------*DATA: WA_CRMEMO TYPE T_CRMEMO, WA_CRMEMO_CHANGE TYPE T_CRMEMO_CHANGE, WA_MVKE TYPE T_MVKE, WA_ORDERS TYPE T_ORDERS, WA_CMEMO TYPE T_ORDERS, WA_PO TYPE T_ORDERS, WA_EKPO TYPE T_EKPO, WA_EKBE TYPE T_EKBE, WA_EKBE_TEMP TYPE T_EKBE, WA_RBKP TYPE T_RBKP, WA_RBKP_TMP TYPE T_RBKP, WA_CDHDR TYPE T_CDHDR, WA_CDPOS TYPE T_CDPOS, WA_CHANGE_DOCS TYPE T_CHANGE_DOCS, WA_CRMEMO_MR8M TYPE T_CRMEMO, WA_SUCCESS TYPE T_SUCCESS, WA_ERROR TYPE T_ERROR, WA_SUCCESS_MR8M TYPE T_SUCCESS, WA_ERROR_MR8M TYPE T_ERROR. *--Work area for all the internal tables used for Sending MailDATA :

Page 308: ABAP Tutorials

WA_OBJPACK TYPE SOPCKLSTI1, WA_OBJHEAD TYPE SOLISTI1, WA_OBJBIN TYPE SOLISTI1, WA_OBJTXT TYPE SOLISTI1, WA_RECLIST TYPE SOMLRECI1 . DATA:*-- Structure to hold Invoice Header Data x_docheader LIKE bapi_incinv_create_header,*-- Structure to hold Reversal Posting Data x_rev_post LIKE BAPI_INCINV_FLD. *----------------------------------------------------------------------** INTERNAL TAABLE DECLARATION*----------------------------------------------------------------------*DATA: IT_CRMEMO TYPE STANDARD TABLE OF T_CRMEMO WITH HEADER LINE, IT_CRMEMO_CHANGE TYPE STANDARD TABLE OF T_CRMEMO_CHANGE WITH HEADER LINE, IT_MVKE TYPE STANDARD TABLE OF T_MVKE WITH HEADER LINE, IT_CRMEMO_MIRO TYPE STANDARD TABLE OF T_CRMEMO WITH HEADER LINE, IT_CRMEMO_MR8M TYPE STANDARD TABLE OF T_CRMEMO WITH HEADER LINE, IT_ORDERS TYPE STANDARD TABLE OF T_ORDERS WITH HEADER LINE, IT_CMEMO TYPE STANDARD TABLE OF T_ORDERS WITH HEADER LINE, IT_PO TYPE STANDARD TABLE OF T_ORDERS WITH HEADER LINE, IT_EKPO TYPE STANDARD TABLE OF T_EKPO WITH HEADER LINE, IT_EKBE TYPE STANDARD TABLE OF T_EKBE WITH HEADER LINE, IT_EKBE_TEMP TYPE STANDARD TABLE OF T_EKBE WITH HEADER LINE, IT_RBKP TYPE STANDARD TABLE OF T_RBKP WITH HEADER LINE, IT_CDHDR TYPE STANDARD TABLE OF T_CDHDR WITH HEADER LINE, IT_CDPOS TYPE STANDARD TABLE OF T_CDPOS WITH HEADER LINE, IT_CHANGE_DOCS TYPE STANDARD TABLE OF T_CHANGE_DOCS WITH HEADER LINE, IT_SUCCESS TYPE STANDARD TABLE OF T_SUCCESS WITH HEADER LINE, IT_ERROR TYPE STANDARD TABLE OF T_ERROR WITH HEADER LINE, IT_SUCCESS_MR8M TYPE STANDARD TABLE OF T_SUCCESS WITH HEADER LINE, IT_ERROR_MR8M TYPE STANDARD TABLE OF T_ERROR WITH HEADER LINE.  *-- Internal table to hold Invoice Item DataDATA:BEGIN OF it_itemdata OCCURS 0. INCLUDE STRUCTURE bapi_incinv_create_item.DATA:END OF it_itemdata. *-- Internal table to hold Invoice Acct Assignment DataDATA:BEGIN OF it_ACCOUNTingdata OCCURS 0. INCLUDE STRUCTURE BAPI_INCINV_CREATE_ACCOUNT.DATA:END OF it_accountingdata. *-- Internal table to hold BAPI return dataDATA: BEGIN OF it_return OCCURS 0. INCLUDE STRUCTURE bapiret2. "Return Parameter.DATA: END OF it_return. *-- Internal table to hold BAPI return dataDATA: BEGIN OF it_return_mr8m OCCURS 0. INCLUDE STRUCTURE bapiret2. "Return Parameter.DATA: END OF it_return_mr8m. 

Page 309: ABAP Tutorials

*--MAIL related Internal tablesDATA: X_DOC_CHNG TYPE SODOCCHGI1, " document attributes IT_OBJPACK TYPE STANDARD TABLE OF SOPCKLSTI1, " attachment table IT_OBJHEAD TYPE STANDARD TABLE OF SOLISTI1, " object header table IT_OBJBIN TYPE STANDARD TABLE OF SOLISTI1, " binary table IT_OBJTXT TYPE STANDARD TABLE OF SOLISTI1, " object text IT_RECLIST TYPE STANDARD TABLE OF SOMLRECI1, " mail recipients it_compressed_list TYPE STANDARD TABLE OF SOLI, it_pdf_list TYPE STANDARD TABLE OF TLINE, it_pdf TYPE tline OCCURS 10 WITH HEADER LINE, it_html TYPE solisti1 OCCURS 10 WITH HEADER LINE,*-- Internal table for MIME data (in CHAR format) it_temp TYPE bapiqcmime OCCURS 10 WITH HEADER LINE,*-- Internal table for storing data it_mime(255) TYPE c OCCURS 10 WITH HEADER LINE. *----------------------------------------------------------------------** GLOBAL VARIABLES **----------------------------------------------------------------------*DATA: V_PGM_ID TYPE SY-REPID, " Program id v_zterm TYPE lfb1-zterm, " Payment Terms v_text(75) TYPE c, " To store error or success text v_itemno(6) TYPE n, " To Increment Item No. for BAPI v_docnr LIKE bapi_incinv_fld-inv_doc_no, " For MIRO document number v_year1 LIKE bapi_incinv_fld-fisc_year, " For MIRO Fiscal year v_spono type TSP01-RQIDENT, " For Spool No. v_type type SOODK-OBJTP, " For Spool Type V_CRMEMO_QTY TYPE VBAP-ZMENG, " For CR Memo Qty. V_LINE_AMOUNT TYPE EKPO-NETPR, " For CR Memo Item Qty. V_GROSSAMT TYPE EKPO-NETPR, " For CR Memo Grand Qty. v_tax_per(3) type n, " For CR Memo Tax amount % v_tax_amt TYPE EKPO-NETPR, " For CR Memo Tax amount v_flag(1) type c, " Flag to process fruther v_tot_s_mr8m TYPE i, " For MR8M Success Records v_tot_e_mr8m TYPE i, " For MR8M Error Records V_DATE TYPE SY-DATUM, " For Sel. Screen Date V_DATE2(10) TYPE C, " For EMail Date V_TIME(10) TYPE C, " For EMail Time V_TIME2(10) TYPE C, " For EMail Time V_INFO(100) TYPE C, " For EMail Body Text V_TABLE_LINES TYPE SY-TABIX, " To Increment Email Count V_TEXT2 TYPE STRING , " For EMail Id text v_lines TYPE i, " To Store PDF Lines v_temp(500) TYPE c, " To Convert to 255 char format v_offset TYPE p, " To Convert to 255 char format v_lineslen TYPE i, " To Convert to 255 char format

Page 310: ABAP Tutorials

v_mimelen TYPE i, " To Convert to 255 char format v_tabix type sy-tabix. " To Convert to 255 char format *----------------------------------------------------------------------** CONSTANTS **----------------------------------------------------------------------*CONSTANTS: C_X(1) TYPE C VALUE 'X', " Constant X or Flag C_E(1) TYPE C VALUE 'E', " For Error check c_v(1) TYPE C VALUE 'V', " For PO Docs c_o(1) TYPE C VALUE 'O', " For Order Docs c_c(1) TYPE C VALUE 'C', " For Credit Memo Docs c_k(1) TYPE C VALUE 'K', " For CR Memo Docs c_u(1) TYPE C VALUE 'U', " For Change tables Update c_ali(3) TYPE C VALUE 'ALI', " For ALI Format c_vbak(4) TYPE C VALUE 'VBAK', " For Change docs table C_01(2) TYPE C VALUE '01', " For Serial No. & Reversal Reason C_02(2) TYPE C VALUE '02', " For Reversal Reason c_blart TYPE bkpf-blart VALUE 'RE', " Document type C_MTPOS TYPE MVKE-MTPOS VALUE 'BANS', " Item Category group C_AUGRU(5) TYPE C VALUE 'AUGRU', " Reason Code C_0000500205(10) TYPE C VALUE '0000500205', " GL Account # C_VERKBELEG(9) TYPE C VALUE 'VERKBELEG'. " For Object Class *-- Horizontal tab & line feed constantsCLASS CL_ABAP_CHAR_UTILITIES DEFINITION LOAD.CONSTANTS: C_TAB TYPE C VALUE CL_ABAP_CHAR_UTILITIES=>HORIZONTAL_TAB, C_CR_LF TYPE C VALUE CL_ABAP_CHAR_UTILITIES=>CR_LF . *----------------------------------------------------------------------** SELECTION SCREEN*----------------------------------------------------------------------**-- Select OptonsSELECTION-SCREEN: BEGIN OF BLOCK B01 WITH FRAME TITLE TEXT-001. SELECT-OPTIONS: S_AUART FOR VBAK-AUART OBLIGATORY NO INTERVALS, " Sales Document Type S_AUGRU FOR VBAK-AUGRU OBLIGATORY NO INTERVALS, " Order reason S_ERDAT FOR VBAK-ERDAT OBLIGATORY. " Date on which the record was createdSELECTION-SCREEN: END OF BLOCK B01. *-- Mail Sending OptionsSELECTION-SCREEN BEGIN OF BLOCK B2 WITH FRAME TITLE TEXT-004. PARAMETERS:P_EMAIL AS CHECKBOX DEFAULT SPACE USER-COMMAND V_COM . PARAMETERS : P_MODE TYPE SO_ESCAPE default 'U' MODIF ID US1. SELECT-OPTIONS: S_EMAIL FOR ADR6-SMTP_ADDR NO INTERVALS MODIF ID US2.* SELECT-OPTIONS: S_EMAIL FOR TRDYSE01CM-USERNAME* NO INTERVALS MODIF ID US2.  SELECTION-SCREEN: BEGIN OF LINE.

Page 311: ABAP Tutorials

SELECTION-SCREEN: COMMENT 55(40) TEXT-019 MODIF ID US2. SELECTION-SCREEN: END OF LINE. SELECTION-SCREEN END OF BLOCK B2. *----------------------------------------------------------------------** WORK AREA for SELECT-OPTIONS*----------------------------------------------------------------------*DATA : X_EMAIL LIKE S_EMAIL. "Work area for EMAIL select-options *----------------------------------------------------------------------** INITIALIZATION*----------------------------------------------------------------------*INITIALIZATION.*-- Default values for Sales Document Type CLEAR S_AUART[]. S_AUART-SIGN = 'I'. S_AUART-OPTION = 'EQ'. S_AUART-LOW = 'CR'. APPEND S_AUART. CLEAR S_AUART. *-- Default values for Date on which the record was created V_DATE = ( SY-DATUM - 1 ). CLEAR S_ERDAT[]. S_ERDAT-SIGN = 'I'. S_ERDAT-OPTION = 'EQ'. S_ERDAT-LOW = SY-DATUM. S_ERDAT-HIGH = SY-DATUM. APPEND S_ERDAT. CLEAR S_ERDAT. *----------------------------------------------------------------------** TOP OF PAGE **----------------------------------------------------------------------*TOP-OF-PAGE.*-- Displaying standard header. PERFORM std_top_of_page USING sy-title. *----------------------------------------------------------------------** A T S E L E C T I O N S C R E E N O U T P U T*----------------------------------------------------------------------**-- For modifying the selection screen layoutAT SELECTION-SCREEN OUTPUT. PERFORM F_MODIFY_SCREEN. *----------------------------------------------------------------------** AT SELECTION SCREEN. **----------------------------------------------------------------------*AT SELECTION-SCREEN.*-- Subroutine to Validate selection screen fields PERFORM f_validate. *----------------------------------------------------------------------** START-OF-SELECTION **----------------------------------------------------------------------*START-OF-SELECTION.

Page 312: ABAP Tutorials

*-- Fetch the Credit Memo Requests documents PERFORM F_GET_CREDIT_MEMO_REQUEST.  IF NOT IT_CRMEMO[] IS INITIAL.*-- Fetch Item Category Group PERFORM F_GET_MVKE_DOCS. *-- Fetch Sales Order documents, PO Documents and Credit Memos PERFORM F_GET_SO_PO_DOCS. ENDIF. *-- If Credit memo request internal table have an change records then* fetch the change documents from CDHDR and CDPOS IF NOT IT_CRMEMO_CHANGE[] IS INITIAL.*-- Fetch Change Documents for CR Memos from CDHDR and CDPOS tables PERFORM F_GET_CHANGED_DOCS. ENDIF. *-- Fetch Purchasing Document Item Details IF NOT IT_PO[] IS INITIAL. PERFORM F_GET_EKPO. ENDIF. *-- Fetch MIRO Vendor based on the PO Details IF NOT IT_EKPO[] IS INITIAL. PERFORM F_GET_VENDOR. ENDIF. *----------------------------------------------------------------------** END-OF-SELECTION **----------------------------------------------------------------------* if v_flag is initial.*-- Process Vendor Debit Postings PERFORM F_PROCESS_MIRO. *-- Process Reversal Postings of Vendor Automatic Debits using TCODE MR8M PERFORM F_PROCESS_MR8M. *-- Send mail,if user enters Email id's and Email Mode is not initial IF P_EMAIL = C_X AND P_MODE IS NOT INITIAL AND S_EMAIL[] IS NOT INITIAL. *-- Get spool id perform f_spool_id. *-- EMail Logic PERFORM F_MAIL_LOGIC. ENDIF. *-- display the EMail RSCONN01 and Sussess and Error records of MIRO and MR8M perform f_display_report.  else.*-- Else exit the process exit. endif. *&---------------------------------------------------------------------*

Page 313: ABAP Tutorials

*& Form F_MODIFY_SCREEN*&---------------------------------------------------------------------** A Form routine to modify the screen*----------------------------------------------------------------------*FORM F_MODIFY_SCREEN . *-- To Modify Mail Sending Options LOOP AT SCREEN. IF P_EMAIL = C_X. IF SCREEN-GROUP1 = 'US1' . SCREEN-INVISIBLE = 0. SCREEN-ACTIVE = 1. SCREEN-INPUT = 0. MODIFY SCREEN. ENDIF. IF SCREEN-GROUP2 = 'US2' . SCREEN-INVISIBLE = 0. SCREEN-ACTIVE = 1. MODIFY SCREEN. ENDIF. ELSEIF P_EMAIL = SPACE. IF SCREEN-GROUP1 = 'US1' . SCREEN-INVISIBLE = 1. SCREEN-ACTIVE = 0. MODIFY SCREEN. ENDIF. IF SCREEN-GROUP1 = 'US2' . SCREEN-INVISIBLE = 1. SCREEN-ACTIVE = 0. MODIFY SCREEN. ENDIF. ENDIF. ENDLOOP. ENDFORM. " F_MODIFY_SCREEN *&---------------------------------------------------------------------**& Form f_validate*&---------------------------------------------------------------------** Validation of Selection-Screen Inputs*----------------------------------------------------------------------*FORM f_validate . *-- Validate Sales Document Type if not s_AUART[] is initial. select AUART into s_AUART-low from TVAK up to 1 rows where AUART in s_AUART. endselect. if sy-subrc <> 0. message E000 with 'Invalid Sales Document Type'(e01) . endif. ENDIF. *-- Validate Order reason (reason for the business transaction) if not s_AUGRU[] is initial.

Page 314: ABAP Tutorials

select AUGRU into s_AUGRU-low from TVAU up to 1 rows where AUGRU in s_AUGRU. endselect. if sy-subrc <> 0. message E000 with 'Invalid Order reason'(e02) . endif. endif.ENDFORM. " f_validate *&---------------------------------------------------------------------**& Form F_GET_CREDIT_MEMO_REQUEST*&---------------------------------------------------------------------** Fetch Credit memo requests from VBAK & VBAP*----------------------------------------------------------------------*FORM F_GET_CREDIT_MEMO_REQUEST .  SELECT A~VBELN B~POSNR A~ERDAT A~AUART A~AUGRU A~WAERK A~VKORG A~VTWEG A~SPART A~VDATU A~BSTNK A~BSARK A~BSTDK A~AEDAT A~BUKRS_VF B~MATNR B~ZMENG B~ZIEME INTO TABLE IT_CRMEMO FROM ( VBAK AS A INNER JOIN VBAP AS B ON A~VBELN = B~VBELN ) WHERE ( A~ERDAT IN S_ERDAT OR A~AEDAT IN S_ERDAT ) AND A~AUART IN S_AUART. IF SY-SUBRC = 0. SORT IT_CRMEMO BY VBELN POSNR. ELSE. MESSAGE I000 WITH 'No Credit Memo Request selected'(002). v_flag = C_X. stop. ENDIF. ENDFORM. " F_GET_CREDIT_MEMO_REQUEST *&---------------------------------------------------------------------**& Form F_GET_MVKE_DOCS*&---------------------------------------------------------------------** Fetch Sales Data for Material*----------------------------------------------------------------------*

Page 315: ABAP Tutorials

FORM F_GET_MVKE_DOCS .  DATA: LV_TABIX TYPE SY-TABIX. *-- Fetch Sales Data for Material SELECT MATNR " Material Number VKORG " Sales Organization VTWEG " Distribution Channel MTPOS " Item category group from material master FROM MVKE " Sales Data for Material INTO TABLE IT_MVKE FOR ALL ENTRIES IN IT_CRMEMO WHERE MATNR = IT_CRMEMO-MATNR AND VKORG = IT_CRMEMO-VKORG AND VTWEG = IT_CRMEMO-VTWEG. IF SY-SUBRC = 0. SORT IT_MVKE BY MATNR VKORG VTWEG MTPOS. ENDIF. *-- Validate Item category group if MVKE-MTOPS <> 'BANS' then ignore CM Request line item LOOP AT IT_CRMEMO INTO WA_CRMEMO. LV_TABIX = SY-TABIX. READ TABLE IT_MVKE INTO WA_MVKE WITH KEY MATNR = WA_CRMEMO-MATNR VKORG = WA_CRMEMO-VKORG VTWEG = WA_CRMEMO-VTWEG MTPOS = C_MTPOS BINARY SEARCH. IF SY-SUBRC <> 0. DELETE IT_CRMEMO INDEX LV_TABIX. " Delete CR memo records ELSE.*-- Else check for credit memo request change date is not initial, and* append those records to IT_CRMEMO_CHANGE internal table to retrive* change documents IF NOT WA_CRMEMO-AEDAT IS INITIAL. WA_CRMEMO_CHANGE-VBELN = WA_CRMEMO-VBELN. WA_CRMEMO_CHANGE-POSNR = WA_CRMEMO-POSNR. WA_CRMEMO_CHANGE-ERDAT = WA_CRMEMO-ERDAT. WA_CRMEMO_CHANGE-AUART = WA_CRMEMO-AUART. WA_CRMEMO_CHANGE-AUGRU = WA_CRMEMO-AUGRU. WA_CRMEMO_CHANGE-WAERK = WA_CRMEMO-WAERK. WA_CRMEMO_CHANGE-VKORG = WA_CRMEMO-VKORG. WA_CRMEMO_CHANGE-VTWEG = WA_CRMEMO-VTWEG. WA_CRMEMO_CHANGE-SPART = WA_CRMEMO-SPART. WA_CRMEMO_CHANGE-VDATU = WA_CRMEMO-VDATU. WA_CRMEMO_CHANGE-BSTNK = WA_CRMEMO-BSTNK. WA_CRMEMO_CHANGE-BSARK = WA_CRMEMO-BSARK. WA_CRMEMO_CHANGE-BSTDK = WA_CRMEMO-BSTDK. WA_CRMEMO_CHANGE-AEDAT = WA_CRMEMO-AEDAT. WA_CRMEMO_CHANGE-BUKRS_VF = WA_CRMEMO-BUKRS_VF. WA_CRMEMO_CHANGE-MATNR = WA_CRMEMO-MATNR. WA_CRMEMO_CHANGE-ZMENG = WA_CRMEMO-ZMENG. WA_CRMEMO_CHANGE-ZIEME = WA_CRMEMO-ZIEME. APPEND WA_CRMEMO_CHANGE TO IT_CRMEMO_CHANGE. CLEAR WA_CRMEMO_CHANGE. ENDIF. ENDIF.

Page 316: ABAP Tutorials

ENDLOOP. ENDFORM. " F_GET_MVKE_DOCS *&---------------------------------------------------------------------**& Form F_GET_SO_PO_DOCS*&---------------------------------------------------------------------** Fetch the Sales Order documents, PO documents, & Credit Memo*----------------------------------------------------------------------*FORM F_GET_SO_PO_DOCS. *-- Fetch Preceding sales orders based on the credit memo request SELECT VBELV POSNV VBELN POSNN VBTYP_N FROM VBFA INTO TABLE IT_ORDERS FOR ALL ENTRIES IN IT_CRMEMO WHERE VBELN = IT_CRMEMO-VBELN AND POSNN = IT_CRMEMO-POSNR AND VBTYP_N = C_K AND VBTYP_V = C_C. IF SY-SUBRC = 0. SORT IT_ORDERS BY VBELV POSNV. *-- Fetch Subsequent PO documents & Credit Memo based on the sales orders SELECT VBELV POSNV VBELN POSNN VBTYP_N FROM VBFA INTO TABLE IT_PO FOR ALL ENTRIES IN IT_ORDERS WHERE VBELV = IT_ORDERS-VBELV AND POSNV = IT_ORDERS-POSNV AND VBTYP_N IN (C_V,C_O) AND VBTYP_V = C_C. IF SY-SUBRC = 0. SORT IT_PO BY VBTYP_N. *-- Copy the IT_PO internal table contents to IT_CMEMO internal table IT_CMEMO[] = IT_PO[]. *-- Delete PO documents from IT_CMEMO internal table DELETE IT_CMEMO WHERE VBTYP_N = C_V. SORT IT_CMEMO BY VBELN POSNN. IF IT_CMEMO[] IS INITIAL. MESSAGE I000 WITH 'No Credit Memo are available for CM Request'(003).* v_flag = c_x.* stop. ENDIF. *-- Delete Credit Memo documents from IT_PO internal table DELETE IT_PO WHERE VBTYP_N = C_O.

Page 317: ABAP Tutorials

SORT IT_PO BY VBELN POSNN.  ENDIF. ENDIF. ENDFORM. " F_GET_SO_PO_DOCS *&---------------------------------------------------------------------**& Form F_GET_CHANGED_DOCS*&---------------------------------------------------------------------** Fetch Change Documents for CR Memos from CDHDR and CDPOS tables*----------------------------------------------------------------------*FORM F_GET_CHANGED_DOCS . *-- Fetch Change Documents for CR Memos from CDHDR SELECT OBJECTCLAS OBJECTID CHANGENR UDATE UTIME FROM CDHDR INTO TABLE IT_CDHDR FOR ALL ENTRIES IN IT_CRMEMO_CHANGE WHERE OBJECTCLAS = C_VERKBELEG AND OBJECTID = IT_CRMEMO_CHANGE-VBELN* AND UDATE = IT_CRMEMO_CHANGE-AEDAT . IF SY-SUBRC = 0. SORT IT_CDHDR BY OBJECTCLAS OBJECTID CHANGENR. *-- Fetch Change Documents for CR Memos from CDPOS SELECT OBJECTCLAS OBJECTID CHANGENR TABNAME TABKEY FNAME CHNGIND VALUE_NEW VALUE_OLD FROM CDPOS INTO TABLE IT_CDPOS FOR ALL ENTRIES IN IT_CDHDR WHERE OBJECTCLAS = C_VERKBELEG AND OBJECTID = IT_CDHDR-OBJECTID AND CHANGENR = IT_CDHDR-CHANGENR AND TABNAME = C_VBAK AND FNAME = C_AUGRU AND CHNGIND = C_U. IF SY-SUBRC = 0. SORT IT_CDPOS BY OBJECTCLAS OBJECTID CHANGENR. ENDIF. ENDIF. ENDFORM. " F_GET_CHANGED_DOCS *&---------------------------------------------------------------------*

Page 318: ABAP Tutorials

*& Form F_GET_EKPO*&---------------------------------------------------------------------** Fetch Purchasing Document Item Details*----------------------------------------------------------------------*FORM F_GET_EKPO . *-- Fetch Purchasing Document Item Details SELECT A~EBELN B~EBELP A~WAERS B~MENGE B~MEINS B~NETPR B~PEINH B~mwskz B~TXJCD INTO TABLE IT_EKPO FROM ( EKKO AS A INNER JOIN EKPO AS B ON A~EBELN = B~EBELN ) FOR ALL ENTRIES IN IT_PO WHERE A~EBELN = IT_PO-VBELN AND B~EBELP = IT_PO-POSNN+1(5). IF SY-SUBRC = 0. SORT IT_EKPO BY EBELN EBELP. ENDIF. ENDFORM. " F_GET_EKPO *&---------------------------------------------------------------------**& Form F_GET_VENDOR*&---------------------------------------------------------------------** Fetch MIRO Vendor details based on the PO Details*----------------------------------------------------------------------*FORM F_GET_VENDOR . DATA: LV_TABIX TYPE SY-TABIX. *-- Fetch History per Purchasing Document records for all the PO records SELECT EBELN EBELP ZEKKN VGABE GJAHR BELNR BUZEI FROM EKBE INTO TABLE IT_EKBE FOR ALL ENTRIES IN IT_EKPO WHERE EBELN = IT_EKPO-EBELN AND EBELP = IT_EKPO-EBELP AND VGABE = '2'.* and STBLG = space. IF SY-SUBRC = 0. SORT IT_EKBE BY BELNR GJAHR. *-- Fetch the vendor details based on table IT_EKBE internal table SELECT BELNR

Page 319: ABAP Tutorials

GJAHR BLDAT BUDAT XBLNR LIFNR RMWWR WMWST1 XRECH STBLG FROM RBKP INTO TABLE IT_RBKP FOR ALL ENTRIES IN IT_EKBE WHERE BELNR = IT_EKBE-BELNR AND GJAHR = IT_EKBE-GJAHR. IF SY-SUBRC = 0. SORT IT_RBKP BY BELNR GJAHR. ENDIF. ENDIF. *-- Sort PO History documents based on PO # and PO Item SORT IT_EKBE BY EBELN EBELP. *-- Copy the PO History documents into IT_EKBE_TEMP internal table IT_EKBE_TEMP[] = IT_EKBE[]. *-- Delete PO History documents from IT_EKBE_TEMP internal table* comparing with IT_RBKP where (STBLG) Reversal document number* is initial LOOP AT IT_EKBE_TEMP INTO WA_EKBE_TEMP. LV_TABIX = SY-TABIX. READ TABLE IT_RBKP INTO WA_RBKP WITH KEY BELNR = WA_EKBE_TEMP-BELNR GJAHR = WA_EKBE_TEMP-GJAHR* XRECH = SPACE STBLG = SPACE. IF SY-SUBRC <> 0. DELETE IT_EKBE_TEMP INDEX LV_TABIX. ENDIF. CLEAR: WA_EKBE_TEMP, WA_RBKP. ENDLOOP. ENDFORM. " F_GET_VENDOR *&---------------------------------------------------------------------**& Form F_PROCESS_MIRO*&---------------------------------------------------------------------** Process MIRO*----------------------------------------------------------------------*FORM F_PROCESS_MIRO . DATA: lv_itemno TYPE i, lv_tabix type sy-index, lc_check(1) TYPE c VALUE 'X', V_FILL_ITEM, lv_rbkp_bldat type sy-datum.   clear : it_itemdata, it_accountingdata, IT_CRMEMO_MIRO, IT_CRMEMO_MR8M.

Page 320: ABAP Tutorials

refresh : it_itemdata, it_accountingdata, IT_CRMEMO_MIRO, IT_CRMEMO_MR8M. *-- Copy all the CR Memo Docs and delete order reason not in S_AUGRU IT_CRMEMO_MR8M[] = IT_CRMEMO[]. *-- Delete Reversal postings which are not in S_AUGRU DELETE IT_CRMEMO_MR8M WHERE AUGRU IN S_AUGRU. *-- Delete Reversal postings where AEDAT is initial DELETE IT_CRMEMO_MR8M where aedat is initial. *-- Delete order reason which are not in S_AUGRU DELETE IT_CRMEMO WHERE AUGRU NOT IN S_AUGRU. *-- Loop through the credit memo request records LOOP AT IT_CRMEMO INTO WA_CRMEMO. lv_tabix = sy-tabix. *-- If credit memo request change date is not initial then* send change date (AEDAT) to lv_rbkp_bldat if not WA_CRMEMO-aedat is initial. lv_rbkp_bldat = WA_CRMEMO-aedat. else.*-- If credit memo request change date is initial then* send create date (ERDAT) to lv_rbkp_bldat lv_rbkp_bldat = WA_CRMEMO-erdat. endif.  READ TABLE IT_ORDERS INTO WA_ORDERS WITH KEY VBELN = WA_CRMEMO-VBELN POSNN = WA_CRMEMO-POSNR. IF SY-SUBRC = 0. READ TABLE IT_PO INTO WA_PO WITH KEY VBELV = WA_ORDERS-VBELV POSNV = WA_ORDERS-POSNV. IF SY-SUBRC = 0. READ TABLE IT_EKPO INTO WA_EKPO WITH KEY EBELN = WA_PO-VBELN EBELP = WA_PO-POSNN. IF SY-SUBRC = 0.*-- Read IT_EKBE_TEMP internal table which contains records which are not reversed READ TABLE IT_EKBE_TEMP INTO WA_EKBE_TEMP WITH KEY EBELN = WA_EKPO-EBELN EBELP = WA_EKPO-EBELP. IF SY-SUBRC = 0.*-- Read IT_RBKP internal table with XRECH (Indicator: post invoice) = 'X' ,* check for invoice records for the correspnding CR Memo records READ TABLE IT_RBKP INTO WA_RBKP WITH KEY BELNR = WA_EKBE_TEMP-BELNR GJAHR = WA_EKBE_TEMP-GJAHR XRECH = C_X. IF SY-SUBRC = 0.*-- Read IT_RBKP internal table with XRECH (Indicator: post invoice) = SPACE,* and document date = CR Memo creation date* and reference document number = PO number READ TABLE IT_RBKP INTO WA_RBKP_TMP WITH KEY BELNR = WA_EKBE_TEMP-BELNR

Page 321: ABAP Tutorials

GJAHR = WA_EKBE_TEMP-GJAHR BLDAT = WA_CRMEMO-ERDAT XRECH = ' ' XBLNR+0(10) = WA_EKBE_TEMP-ebeln.* STBLG = SPACE. IF SY-SUBRC = 0. CONTINUE. ELSE.*-- Quantity Conversion (Get the Credit Memo Quantity by passing CMR unit per one PO unit) perform f_quantity_conv. *-- Filling the Line items data *-- Incrementing the item no lv_itemno = lv_itemno + 1. v_itemno = lv_itemno.  it_itemdata-invoice_doc_item = v_itemno. it_itemdata-po_number = WA_ekPO-ebeln. it_itemdata-po_item = WA_EKPO-EBELP. it_itemdata-tax_code = WA_ekpo-mwskz. it_itemdata-TAXJURCODE = WA_ekpo-TXJCD. *-- Converting SAP amount to BAPI format by passing line item amount and currency PERFORM f_currency_amount_sap_to_bapi USING WA_EKPO-waers V_LINE_AMOUNT CHANGING it_itemdata-item_amount .  it_itemdata-quantity = ( WA_CRMEMO-ZMENG * V_CRMEMO_QTY ). it_itemdata-po_unit = WA_EKPO-MEINS. APPEND it_itemdata. *-- Populate Account Assignment data IT_ACCOUNTINGDATA-INVOICE_DOC_ITEM = v_itemno. IT_ACCOUNTINGDATA-XUNPL = space. IT_ACCOUNTINGDATA-SERIAL_NO = C_01. IT_ACCOUNTINGDATA-TAX_CODE = it_itemdata-tax_code. IT_ACCOUNTINGDATA-TAXJURCODE = it_itemdata-TAXJURCODE. IT_ACCOUNTINGDATA-ITEM_AMOUNT = it_itemdata-item_amount. IT_ACCOUNTINGDATA-QUANTITY = it_itemdata-quantity. IT_ACCOUNTINGDATA-PO_UNIT = it_itemdata-po_unit. IT_ACCOUNTINGDATA-GL_ACCOUNT = C_0000500205. append IT_ACCOUNTINGDATA. clear IT_ACCOUNTINGDATA.  CLEAR it_itemdata. endif. endif. ENDIF. ENDIF.

Page 322: ABAP Tutorials

ENDIF. ENDIF.*-- At end of each credit memo request fill the header details of BAPI FM and*-- post the BAPI AT END OF VBELN. read table it_crmemo into wa_crmemo index lv_tabix. *-- Populate the document Header*-- Getting the header data for invoice x_docheader-invoice_ind = space. x_docheader-doc_type = c_blart. x_docheader-doc_date = lv_rbkp_bldat. x_docheader-pstng_date = lv_rbkp_bldat. x_docheader-ref_doc_no = WA_RBKP-XBLNR. x_docheader-comp_code = WA_CRMEMO-BUKRS_VF. x_docheader-CURRENCY = WA_CRMEMO-WAERK. x_docheader-calc_tax_ind = lc_check. *-- Logic to find the Tax % v_tax_per = ( WA_RBKP-WMWST1 / ( WA_RBKP-RMWWR - WA_RBKP-WMWST1 ) ) * 100. v_tax_amt = ( V_GROSSAMT * v_tax_per ) / 100. V_GROSSAMT = ( V_GROSSAMT + v_tax_amt ). x_docheader-gross_amount = V_GROSSAMT.  CLEAR:v_docnr, v_year1. *-- Calling BAPI to create PO invoice document CHECK NOT IT_ITEMDATA[] IS INITIAL. CALL FUNCTION 'BAPI_INCOMINGINVOICE_CREATE' EXPORTING headerdata = x_docheader IMPORTING invoicedocnumber = v_docnr fiscalyear = v_year1 TABLES itemdata = it_itemdata[] ACCOUNTingDATA = it_ACCOUNTingDATA[]* GLACCOUNTDATA =* taxdata = return = it_return. *-- Commit work IF NOT v_docnr IS INITIAL. CALL FUNCTION 'BAPI_TRANSACTION_COMMIT' EXPORTING wait = 'X'.*-- Move the data to Success Internal Table wa_success-crmemo = wa_crmemo-vbeln. wa_success-cmemo = wa_cmemo-vbeln. wa_success-orders = wa_orders-vbelv. wa_success-po = wa_po-vbeln. wa_success-miro_no = v_docnr. wa_success-text = 'MIRO is Posted'. append wa_success TO it_success. clear wa_success. 

Page 323: ABAP Tutorials

ENDIF.*-- Read the values in the table IT_RETURN. CLEAR it_return. READ TABLE it_return INDEX 1.* If message type is error then roll back the work IF it_return-type = C_E.*-- Roll back CALL FUNCTION 'BAPI_TRANSACTION_ROLLBACK'. *-- Move the data to Error Internal Table wa_error-crmemo = wa_crmemo-vbeln. wa_error-cmemo = wa_cmemo-vbeln. wa_error-orders = wa_orders-vbelv. wa_error-po = wa_po-vbeln. wa_error-text = it_return-MESSAGE. append wa_error TO it_error. clear wa_error.  ENDIF.  refresh: it_return, it_itemdata, it_accountingdata. clear: V_GROSSAMT, it_return, it_itemdata, wa_crmemo, wa_orders, wa_po, wa_ekpo, WA_EKBE_TEMP, wa_rbkp, wa_rbkp_tmp, v_docnr, v_year1, WA_SUCCESS, WA_ERROR, it_accountingdata, v_tax_per, v_tax_amt, V_FILL_ITEM, lv_rbkp_bldat. ENDAT. ENDLOOP. ENDFORM. " F_PROCESS_MIRO *&---------------------------------------------------------------------**& Form f_quantity_conv*&---------------------------------------------------------------------** Quantity Conversion*----------------------------------------------------------------------*FORM f_quantity_conv . *-- Quantity Conversion (Get the Credit Memo Quantity by passing CMR unit per one PO unit) CLEAR: V_LINE_AMOUNT, V_CRMEMO_QTY.  call function 'MC_UNIT_CONVERSION' EXPORTING MATNR = WA_CRMEMO-MATNR nach_meins = WA_EKPO-MEINS von_meins = WA_CRMEMO-ZIEME IMPORTING UMREF = V_CRMEMO_QTY EXCEPTIONS CONVERSION_NOT_FOUND = 1 MATERIAL_NOT_FOUND = 2 NACH_MEINS_MISSING = 3 OVERFLOW = 4 VON_MEINS_MISSING = 5 OTHERS = 6. if sy-subrc <> 0.

Page 324: ABAP Tutorials

MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ELSE. V_LINE_AMOUNT = ( V_CRMEMO_QTY * WA_CRMEMO-ZMENG * WA_EKPO-peinh * WA_EKPO-NETPR ). V_GROSSAMT = V_GROSSAMT + V_LINE_AMOUNT. ENDIF. ENDFORM. " f_quantity_conv *&---------------------------------------------------------------------**& Form f_currency_amount_sap_to_bapi*&---------------------------------------------------------------------** SAP Amount to BAPI Amount*----------------------------------------------------------------------*FORM f_currency_amount_sap_to_bapi USING p_waers p_kbetr CHANGING p_amt_doccur.  DATA : lv_waers LIKE tcurc-waers, lv_sapamount LIKE bapicurr-bapicurr, lv_bapi_amount LIKE bapicurr-bapicurr.  lv_waers = p_waers. lv_sapamount = p_kbetr.   CALL FUNCTION 'CURRENCY_AMOUNT_SAP_TO_BAPI' EXPORTING currency = lv_waers sap_amount = lv_sapamount IMPORTING bapi_amount = lv_bapi_amount.  p_amt_doccur = lv_bapi_amount. ENDFORM. " f_currency_amount_sap_to_bapi *&---------------------------------------------------------------------**& Form f_display_report*&---------------------------------------------------------------------** Display Report*----------------------------------------------------------------------*FORM f_display_report . *-- Success Report IF NOT IT_SUCCESS[] IS INITIAL. ULINE AT /1(129). WRITE:/1 sy-vline, 'CR Memo', 19 sy-vline, 'Credit Memo', 39 sy-vline, 'Sales Order', 59 sy-vline, 'Purchase Order', 79 sy-vline, 'MIRO Number', 99 sy-vline, 'Text', 129 sy-vline. ULINE AT /1(129). 

Page 325: ABAP Tutorials

LOOP AT it_success into wa_success. WRITE:/1 sy-vline, wa_success-crmemo, 19 sy-vline, wa_success-cmemo, 39 sy-vline, wa_success-orders, 59 sy-vline, wa_success-po, 79 sy-vline, wa_success-miro_no, 99 sy-vline, wa_success-text, 129 sy-vline.  ENDLOOP. ULINE AT /1(129). SKIP 2.  ENDIF. *-- Error Report IF NOT IT_ERROR[] IS INITIAL.  ULINE AT /1(179). WRITE:/1 sy-vline, 'CR Memo', 19 sy-vline, 'Credit Memo', 39 sy-vline, 'Sales Order', 59 sy-vline, 'Purchase Order', 79 sy-vline, 'Error Text', 179 sy-vline. ULINE AT /1(179).  LOOP AT IT_ERROR into WA_ERROR. WRITE:/1 sy-vline, WA_ERROR-crmemo, 19 sy-vline, WA_ERROR-cmemo, 39 sy-vline, WA_ERROR-orders, 59 sy-vline, WA_ERROR-po, 79 sy-vline, WA_ERROR-text, 179 sy-vline. ENDLOOP. ULINE AT /1(179).  ENDIF.   IF NOT IT_SUCCESS_MR8M[] IS INITIAL. ULINE AT /1(129). WRITE:/1 sy-vline, 'CR Memo', 19 sy-vline, 'Credit Memo', 39 sy-vline, 'Sales Order', 59 sy-vline, 'Purchase Order', 79 sy-vline, 'Reversal Posting No.', 99 sy-vline, 'Text', 129 sy-vline. ULINE AT /1(129).  LOOP AT it_success_mr8m into wa_success_mr8m. WRITE:/1 sy-vline, wa_success_mr8m-crmemo, 19 sy-vline, wa_success_mr8m-cmemo, 39 sy-vline, wa_success_mr8m-orders, 59 sy-vline, wa_success_mr8m-po, 79 sy-vline, wa_success_mr8m-miro_no,

Page 326: ABAP Tutorials

99 sy-vline, wa_success_mr8m-text, 129 sy-vline.  ENDLOOP. ULINE AT /1(129). SKIP 2.  ENDIF. *-- Error Report IF NOT IT_ERROR_MR8M[] IS INITIAL.  ULINE AT /1(179). WRITE:/1 sy-vline, 'CR Memo', 19 sy-vline, 'Credit Memo', 39 sy-vline, 'Sales Order', 59 sy-vline, 'Purchase Order', 79 sy-vline, 'Error Text', 179 sy-vline. ULINE AT /1(179).  LOOP AT IT_ERROR_MR8M into WA_ERROR_MR8M. WRITE:/1 sy-vline, WA_ERROR_MR8M-crmemo, 19 sy-vline, WA_ERROR_MR8M-cmemo, 39 sy-vline, WA_ERROR_MR8M-orders, 59 sy-vline, WA_ERROR_MR8M-po, 79 sy-vline, WA_ERROR_MR8M-text, 179 sy-vline. ENDLOOP. ULINE AT /1(179).  ENDIF. ENDFORM. " f_display_report *&---------------------------------------------------------------------**& Form F_PROCESS_MR8M*&---------------------------------------------------------------------** Process Reversal postings*----------------------------------------------------------------------*FORM F_PROCESS_MR8M .  clear: wa_CRMEMO_MR8M.  LOOP AT IT_CRMEMO_MR8M into WA_CRMEMO_MR8M. read table it_cdpos into wa_cdpos with key OBJECTID = WA_CRMEMO_MR8M-VBELN. if sy-subrc <> 0. CONTINUE. ELSE. if wa_cdpos-value_old in s_augru. READ TABLE IT_ORDERS INTO WA_ORDERS WITH KEY VBELN = wa_CRMEMO_MR8M-VBELN POSNN = wa_CRMEMO_MR8M-POSNR. IF SY-SUBRC = 0.* READ TABLE IT_CMEMO INTO WA_CMEMO WITH KEY VBELV = WA_ORDERS-VBELV* POSNV = WA_ORDERS-POSNV.* IF SY-SUBRC = 0. READ TABLE IT_PO INTO WA_PO WITH KEY VBELV = WA_ORDERS-VBELV

Page 327: ABAP Tutorials

POSNV = WA_ORDERS-POSNV. IF SY-SUBRC = 0. READ TABLE IT_EKPO INTO WA_EKPO WITH KEY EBELN = WA_PO-VBELN EBELP = WA_PO-POSNN. IF SY-SUBRC = 0.* READ TABLE IT_EKBE INTO WA_EKBE WITH KEY EBELN = WA_EKPO-EBELN* EBELP = WA_EKPO-EBELP.* IF SY-SUBRC = 0. LOOP AT IT_EKBE into WA_EKBE WHERE EBELN = WA_EKPO-EBELN AND EBELP = WA_EKPO-EBELP. READ TABLE IT_RBKP INTO WA_RBKP WITH KEY BELNR = WA_EKBE-BELNR GJAHR = WA_EKBE-GJAHR* BLDAT = WA_CRMEMO_MR8M-AEDAT XBLNR+0(10) = WA_EKBE-EBELN XRECH = SPACE STBLG = SPACE.  IF SY-SUBRC = 0. move: WA_RBKP-BELNR TO X_REV_POST-INV_DOC_NO, WA_RBKP-GJAHR TO X_REV_POST-FISC_YEAR, WA_RBKP-BUDAT TO X_REV_POST-PSTNG_DATE. IF WA_RBKP-BUDAT+4(2) = SY-DATUM+4(2). X_REV_POST-REASON_REV = C_01. ELSE. X_REV_POST-REASON_REV = C_02. ENDIF. ENDIF. ENDLOOP.*-- Call the FM for MIRO reversal CALL FUNCTION 'BAPI_INCOMINGINVOICE_CANCEL' EXPORTING INVOICEDOCNUMBER = X_REV_POST-INV_DOC_NO FISCALYEAR = X_REV_POST-FISC_YEAR REASONREVERSAL = X_REV_POST-REASON_REV POSTINGDATE = X_REV_POST-PSTNG_DATE IMPORTING INVOICEDOCNUMBER_REVERSAL = X_REV_POST-INV_DOC_NO FISCALYEAR_REVERSAL = X_REV_POST-FISC_YEAR TABLES RETURN = it_return_mr8m.*-- Commit work IF NOT X_REV_POST-INV_DOC_NO IS INITIAL. CALL FUNCTION 'BAPI_TRANSACTION_COMMIT' EXPORTING wait = 'X'.*-- Move the data to Success Internal Table wa_success_mr8m-crmemo = wa_crmemo-vbeln. wa_success_mr8m-cmemo = wa_cmemo-vbeln. wa_success_mr8m-orders = wa_orders-vbelv. wa_success_mr8m-po = wa_po-vbeln. wa_success_mr8m-text = 'MR8M Done'. append wa_success_mr8m TO it_success_mr8m. clear wa_success_mr8m. ENDIF.*-- Read the values in the table IT_RETURN.

Page 328: ABAP Tutorials

CLEAR it_return_mr8m. READ TABLE it_return_mr8m INDEX 1.*-- If message type is error then roll back the work IF it_return_mr8m-type = 'E' .*-- Roll back CALL FUNCTION 'BAPI_TRANSACTION_ROLLBACK'.*-- Move the data to Error Internal Table wa_error_mr8m-crmemo = wa_crmemo-vbeln. wa_error_mr8m-cmemo = wa_cmemo-vbeln. wa_error_mr8m-orders = wa_orders-vbelv. wa_error_mr8m-po = wa_po-vbeln. wa_error_mr8m-text = it_return_mr8m-MESSAGE. append wa_error_mr8m TO it_error_mr8m. clear wa_error_mr8m.  ENDIF.* ENDIF.* ENDIF. ENDIF. ENDIF.* ENDIF. ENDIF. ENDIF. ENDIF. CLEAR: wa_error_mr8m, wa_SUCCESS_mr8m, X_REV_POST, wa_CRMEMO_MR8M, wa_orders, wa_po, wa_ekpo, wa_ekbe, wa_rbkp, wa_cmemo. REFRESH: IT_RETURN_MR8M.  endloop. ENDFORM. " F_PROCESS_MR8M *&---------------------------------------------------------------------**& Form F_spool_id*&---------------------------------------------------------------------** Create a new spool ID*----------------------------------------------------------------------*FORM F_spool_id . *-- Create a new spool from the data in data_tab*-- new-page line-size sy-linsz print on new-page line-size 255 print on destination 'LOCL'(p19) "<<== my printer*-- receiver 'TJOSVOB' cover text 'Spool title'(p20) " <<== Title or Spool req. name list name 'List name'(p21) list dataset 'List Dataset'(p22) immediately ' ' " X means print now keep in spool c_x " X means keep spool new list identification c_x no dialog . *-- Writing Report*-- In this perform you will write the code for displaying the list perform f_display_report. *-- new-page print off

Page 329: ABAP Tutorials

new-page print off. ENDFORM. " F_spool_id *&---------------------------------------------------------------------**& Form F_MAIL_LOGIC*&---------------------------------------------------------------------** Logic to send a mail for the given Email ID's*----------------------------------------------------------------------*FORM F_MAIL_LOGIC .  data : wa_tsp01sys type tsp01sys. clear v_spono.  v_spono = sy-spono.* v_attach_desc = sy-title.*-- Convert the Spool ID into PDF format perform f_pdf_conversion tables it_compressed_list it_pdf_list using v_spono. *-- Send the Mail in PDF Format perform f_send_mail. ENDFORM. " F_MAIL_LOGIC *&---------------------------------------------------------------------**& Form f_pdf_conversion*&---------------------------------------------------------------------** Read the spool and convert into PDF format*----------------------------------------------------------------------** -->P_ITAB_COMPRESSED_LIST text* -->P_ITAB_PDF_LIST text* -->P_V_SPONO text*----------------------------------------------------------------------*FORM f_pdf_conversion TABLES it_compressed_list structure soli it_pdf_list structure tline using lv_spooln type tsp01-rqident. clear: it_compressed_list, it_pdf_list.refresh: it_compressed_list, it_pdf_list. *-- Call the FM "RSPO_RETURN_SPOOLJOB" to read the spool by passing the spool number call function 'RSPO_RETURN_SPOOLJOB' exporting rqident = lv_spooln desired_type = v_type importing real_type = v_type tables buffer = it_compressed_list buffer_pdf = it_pdf_list exceptions no_such_job = 1 job_contains_no_data = 2 selection_empty = 3

Page 330: ABAP Tutorials

no_permission = 4 can_not_access = 5 read_error = 6 type_no_match = 7 others = 8. if sy-subrc <> 0. message I000 with 'Error in spool reading'(017). endif. *-- If the List type is ALI call the FM "CONVERT_ABAPSPOOLJOB_2_PDF"* to convert list into PDF Format if v_type = c_ali. " for List it is ALI call function 'CONVERT_ABAPSPOOLJOB_2_PDF' exporting src_spoolid = lv_spooln tables pdf = it_pdf exceptions err_no_abap_spooljob = 1 err_no_spooljob = 2 err_no_permission = 3 err_conv_not_possible = 4 err_bad_destdevice = 5 user_cancelled = 6 err_spoolerror = 7 err_temseerror = 8 err_btcjob_open_failed = 9 err_btcjob_submit_failed = 10 err_btcjob_close_failed = 11 others = 12. if sy-subrc <> 0. message e000 with'Error in convertion of list into PDF format'(018). endif. *-- Logic to convert the given format into 255 character format in IT_PDF describe table it_pdf lines v_lines. describe field it_pdf length v_lineslen IN character MODE. describe field it_temp length v_mimelen IN character MODE. LOOP AT it_pdf. v_tabix = sy-tabix. MOVE it_pdf TO v_temp+v_offset. IF v_tabix = v_lines. v_lineslen = strlen( it_pdf ). ENDIF.  v_offset = v_offset + v_lineslen. IF v_offset GE v_mimelen. CLEAR it_temp. it_temp = v_temp(v_mimelen). APPEND it_temp. SHIFT v_temp BY v_mimelen PLACES. v_offset = v_offset - v_mimelen. ENDIF.  IF v_tabix = v_lines. IF v_offset GT 0.

Page 331: ABAP Tutorials

CLEAR it_temp. it_temp = v_temp(v_offset). APPEND it_temp. ENDIF. ENDIF. ENDLOOP.   LOOP AT it_temp. it_mime(255) = it_temp-line. APPEND it_mime. ENDLOOP. *-- Final Data to send to EMail it_html[] = it_mime[]. endif. ENDFORM. " f_pdf_conversion *&---------------------------------------------------------------------**& Form f_send_mail*&---------------------------------------------------------------------** Send EMail Logic*----------------------------------------------------------------------*FORM f_send_mail . data : wa_tsp01sys type tsp01sys. *-- Populate Mail Id's WA_RECLIST-REC_TYPE = P_MODE. WA_RECLIST-EXPRESS = C_X. *-- Loop through the Emial select options LOOP AT S_EMAIL INTO X_EMAIL. WA_RECLIST-RECEIVER = X_EMAIL-LOW.*-- append receiver table APPEND WA_RECLIST TO IT_RECLIST. ENDLOOP. *-- If receiver table is not initial CHECK IT_RECLIST[] IS NOT INITIAL.*--To check Mail ID's internal table should not be Empty.*--populate document attributes *-- Mail subject line CLEAR: X_DOC_CHNG. X_DOC_CHNG-OBJ_NAME = 'HEADING'. CONCATENATE 'Automatic Vendor Dedit Postings'(005) SY-DATUM INTO X_DOC_CHNG-OBJ_DESCR SEPARATED BY SPACE. *-- Mail body CONCATENATE 'Automatic Vendor Dedit Postings'(005) ' is attached.'(006) INTO WA_OBJTXT SEPARATED BY SPACE. APPEND WA_OBJTXT TO IT_OBJTXT. 

Page 332: ABAP Tutorials

*-- Append Date and Time into Body of email. MOVE 'File is generated on'(007) TO V_INFO. V_TIME = SY-UZEIT. CONCATENATE V_TIME+0(2) V_TIME+2(2) V_TIME+4(2) INTO V_TIME2 SEPARATED BY ':'. CONCATENATE SY-DATUM+4(2) '/' SY-DATUM+6(2) '/' SY-DATUM+0(4) INTO V_DATE2. CONCATENATE V_INFO V_DATE2 'At' V_TIME2 INTO V_INFO SEPARATED BY SPACE. WA_OBJTXT = V_INFO. APPEND WA_OBJTXT TO IT_OBJTXT. *-- Document size CLEAR : V_TABLE_LINES. DESCRIBE TABLE IT_OBJTXT LINES V_TABLE_LINES. READ TABLE IT_OBJTXT INTO WA_OBJTXT INDEX V_TABLE_LINES . X_DOC_CHNG-DOC_SIZE = ( V_TABLE_LINES - 1 ) * 255 + STRLEN( WA_OBJTXT ). *-- Populate packing list for body text WA_OBJPACK-HEAD_START = 1. WA_OBJPACK-HEAD_NUM = 0. WA_OBJPACK-BODY_START = 1. WA_OBJPACK-BODY_NUM = V_TABLE_LINES. WA_OBJPACK-DOC_TYPE = 'RAW'. APPEND WA_OBJPACK TO IT_OBJPACK. CLEAR WA_OBJPACK.  if v_type = c_ali. loop at it_html. wa_objbin-line = it_html-line. APPEND WA_OBJBIN TO IT_OBJBIN. CLEAR WA_OBJBIN. endloop. v_type = 'PDF'. endif. *-- Get total no.of lines of Object table(attachment) CLEAR : V_TABLE_LINES. DESCRIBE TABLE IT_OBJBIN LINES V_TABLE_LINES. *-- Populate object header(attachment name) WA_OBJHEAD = 'Automatic Vendor Dedit Postings log'(014). APPEND WA_OBJHEAD TO IT_OBJHEAD. CLEAR WA_OBJHEAD.

Page 333: ABAP Tutorials

 *-- Packing list for attachment WA_OBJPACK-TRANSF_BIN = C_X. WA_OBJPACK-HEAD_START = 1. WA_OBJPACK-HEAD_NUM = 1. WA_OBJPACK-BODY_START = 1. WA_OBJPACK-BODY_NUM = V_TABLE_LINES . WA_OBJPACK-DOC_TYPE = v_type .  WA_OBJPACK-OBJ_NAME = 'Auto_Debit'. WA_OBJPACK-OBJ_DESCR = 'attachment'. WA_OBJPACK-DOC_SIZE = V_TABLE_LINES * 255. APPEND WA_OBJPACK TO IT_OBJPACK. CLEAR WA_OBJPACK. *-- Sending the EMail document in given format CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1' EXPORTING DOCUMENT_DATA = X_DOC_CHNG PUT_IN_OUTBOX = C_X COMMIT_WORK = C_X TABLES PACKING_LIST = IT_OBJPACK OBJECT_HEADER = IT_OBJHEAD CONTENTS_BIN = IT_OBJBIN CONTENTS_TXT = IT_OBJTXT RECEIVERS = IT_RECLIST EXCEPTIONS TOO_MANY_RECEIVERS = 1 DOCUMENT_NOT_SENT = 2 DOCUMENT_TYPE_NOT_EXIST = 3 OPERATION_NO_AUTHORIZATION = 4 PARAMETER_ERROR = 5 X_ERROR = 6 ENQUEUE_ERROR = 7 OTHERS = 8.  IF SY-SUBRC <> 0. MESSAGE E000 WITH 'Error occurred in sending mail'(015). ELSE.*-- Wait upto 2 secounds wait up to 2 seconds. *-- Call the RSCONN01 (SAPconnect: Start Send Process) SUBMIT RSCONN01 WITH MODE = 'INT'* WITH output = 'X' AND RETURN.  PERFORM F_DISPLAY_SENT_MAIL_STATUS. ENDIF. * To delete the spool request wa_tsp01sys-rqident = sy-spono. call function 'RSPO_IDELETE_SPOOLREQ' exporting spoolreq = wa_tsp01sys. if sy-subrc <> 0.

Page 334: ABAP Tutorials

endif. ENDFORM. " f_send_mail *&---------------------------------------------------------------------**& Form F_DISPLAY_SENT_MAIL_STATUS*&---------------------------------------------------------------------** Display Mail Sent status to the user*----------------------------------------------------------------------*FORM F_DISPLAY_SENT_MAIL_STATUS .  ULINE AT /1(60). WRITE :/ SY-VLINE, 'Mail sent Successfully to'(016) COLOR 5 INTENSIFIED ON, 60 SY-VLINE.  LOOP AT S_EMAIL INTO X_EMAIL. V_TABLE_LINES = STRLEN( X_EMAIL-LOW ). MOVE X_EMAIL-LOW+0(V_TABLE_LINES) TO V_TEXT2.  WRITE :/ SY-VLINE, 2 SY-TABIX LEFT-JUSTIFIED, 5 ')', V_TEXT2, 60 SY-VLINE. ENDLOOP.  ULINE AT /1(60). ENDFORM. " F_DISPLAY_SENT_MAIL_STATUS

 

Developing simple interactive report

By Vakada Raghava, Mouri Tech Solutions

“In this scenario, we would take an example of a material and develop an interactive report. Once you click on require “material no” on the basic list, the corresponding material information on the secondary list.”

Following is a sample interactive report developed for our demo purpose:

 REPORT  zintractive                             .

TYPES : BEGIN OF str_mard, matnr TYPE mard-matnr, lgort TYPE mard-lgort, werks TYPE mard-werks, END OF str_mard.DATA : wa_mard TYPE str_mard, it_mard TYPE TABLE OF str_mard.TYPES : BEGIN OF str_makt,

Page 335: ABAP Tutorials

matnr TYPE makt-matnr, maktg TYPE makt-maktg, END OF str_makt.DATA : wa_makt TYPE str_makt, it_makt TYPE TABLE OF str_makt.TYPES : BEGIN OF str_mara, matnr TYPE mara-matnr, ersda TYPE mara-ersda, ernam TYPE mara-ernam, laeda TYPE mara-laeda, mtart TYPE mara-mtart, matkl TYPE mara-matkl, meins TYPE mara-meins, END OF str_mara.DATA : wa_mara TYPE str_mara, it_mara TYPE TABLE OF str_mara.TYPES : BEGIN OF str_final, matnr TYPE mara-matnr, ersda TYPE mara-ersda, ernam TYPE mara-ernam, laeda TYPE mara-laeda, mtart TYPE mara-mtart, matkl TYPE mara-matkl, meins TYPE mara-meins, lgort TYPE mard-lgort, werks TYPE mard-werks, END OF str_final.DATA: wa_final TYPE str_final, it_final TYPE TABLE OF str_final.PARAMETERS : plant TYPE mard-werks, stor LIKE mard-lgort.SELECT matnr lgort werksFROM mardINTO TABLE it_mardWHERE lgort = stor AND werks = plant..SELECT matnr maktgFROM maktINTO TABLE it_makt FOR ALL ENTRIES IN it_mardWHERE matnr = it_mard-matnr AND spras = 'E'.SELECT matnr ersda ernam laeda mtart matkl meinsFROM maraINTO TABLE it_mara FOR ALL ENTRIES IN it_maktWHERE matnr = it_makt-matnr.LOOP AT it_makt INTO wa_makt. WRITE : /1 wa_makt-matnr COLOR 1, 40 wa_makt-maktg COLOR 2. HIDE wa_makt-matnr.ENDLOOP.CLEAR wa_mard-matnr.AT LINE-SELECTION. REFRESH it_final. CLEAR wa_final. ULINE. IF sy-lsind = 1. WRITE : /1 'MATERIAL NO' COLOR 2, 20 'CREATION DATE' COLOR 3,

Page 336: ABAP Tutorials

32 'PERSON CREATED', 50 'DATE OF LIST' , 65 'MATERIALTYPE', 80 'MATGROUP' , 90 'UNITOFMEASURE', 110 'STORLOCATION' COLOR 4, 130 'PLANT' COLOR 5. ULINE. ENDIF. LOOP AT it_mara INTO wa_mara WHERE matnr = wa_makt-matnr. wa_final-matnr = wa_mara-matnr. wa_final-ersda = wa_mara-ersda. wa_final-ernam = wa_mara-ernam. wa_final-laeda = wa_mara-laeda. wa_final-mtart = wa_mara-mtart. wa_final-matkl = wa_mara-matkl. wa_final-meins = wa_mara-meins. READ TABLE it_mard INTO wa_mard WITH KEY matnr = wa_makt-matnr. wa_final-lgort = wa_mard-lgort. wa_final-werks = wa_mard-werks. APPEND wa_final TO it_final. ENDLOOP. LOOP AT it_final INTO wa_final. WRITE : /1 wa_final-matnr COLOR 2, 20 wa_final-ersda COLOR 3, 37 wa_final-ernam, 50 wa_final-laeda , 70 wa_final-mtart , 85 wa_final-matkl , 95 wa_final-meins, 115 wa_final-lgort COLOR 4, 130 wa_final-werks COLOR 5. ENDLOOP.TOP-OF-PAGE. WRITE : /1 'MATERIAL NO' COLOR 1, 40 'DISCRIPTION' COLOR 2. ULINE .

Result  

Enter the “Plant” and “Storage Location”

Page 337: ABAP Tutorials

Press the Execute Button. 

 

Double Click on require “Material No” which displays secondary list to corresponding material information. 

The result shown below 

Developing simple interactive report

By Vikram Chellappa, Mouri Tech Solutions

REQUIREMENT: - 

Get the Plant and storage location from the user and to get the available materials in the particular storage location and display in a report.

When the material number in the report is selected the material description and other complete details are displayed in a new screen using interactive report.

STEPS FOLLOWED TO ACHIEVE THE GOAL: 

Go to SE38 ABAP Editor create a new program.  

Page 338: ABAP Tutorials

 

Code the logic in the ABAP Editor.

Check –Activate- and Execute the code.

 

Type in the Required Parameters or select a value from F4 Help Screen.

Page 339: ABAP Tutorials

Execute the project

 

The Report is displayed in the output Screen.

Page 340: ABAP Tutorials

Select a record using the mouse double click.

A new screen shows the output based on the selected record achieving the interactive reporting.

*&----------------------------------------------------------------**& Report ZVikram_interactive **& **&----------------------------------------------------------------**& Published at SAPTechnical.COM **& **&----------------------------------------------------------------*REPORT ZVikram_interactive NO STANDARD PAGE HEADING LINE-SIZE 255.********** THE INITIALIZATION PART CREATING STRUCTURES*************INITIALIZATION.TYPES : BEGIN OF TY_MARD, MATNR TYPE MARD-MATNR, WERKS TYPE MARD-WERKS,

Page 341: ABAP Tutorials

LGORT TYPE MARD-LGORT, END OF TY_MARD, BEGIN OF TY_MARA, MATNR TYPE MARA-MATNR, ERSDA TYPE MARA-ERSDA, ERNAM TYPE MARA-ERNAM, MTART TYPE MARA-MTART, MATKL TYPE MARA-MATKL, END OF TY_MARA, BEGIN OF TY_MAKT, MATNR TYPE MAKT-MATNR, SPRAS TYPE MAKT-SPRAS, MAKTX TYPE MAKT-MAKTX, END OF TY_MAKT, BEGIN OF TY_FINAL, MATNR TYPE MARA-MATNR, ERSDA TYPE MARA-ERSDA, ERNAM TYPE MARA-ERNAM, MTART TYPE MARA-MTART, MATKL TYPE MARA-MATKL, WERKS TYPE MARD-WERKS, LGORT TYPE MARD-LGORT, SPRAS TYPE MAKT-SPRAS, MAKTX TYPE MAKT-MAKTX, END OF TY_FINAL.***** THE INITIALIZATION PART CREATING WORKAREA AND INTERNAL TABLE*****DATA : W_MARD TYPE TY_MARD, I_MARD TYPE TABLE OF TY_MARD, W_MARA TYPE TY_MARA, I_MARA TYPE TABLE OF TY_MARA, W_MAKT TYPE TY_MAKT, I_MAKT TYPE TABLE OF TY_MAKT, W_FINAL TYPE TY_FINAL, I_FINAL TYPE TABLE OF TY_FINAL.**************************START-OF-SELECTION.**************************START-OF-SELECTION.*************************GET INPUT FROM USER***************************PARAMETER : PLANT TYPE MARD-WERKS, STLOC TYPE MARD-LGORT.****SELECT DATA FROM DATABASE INTO INTERNAL TABLES***********************SELECT FROM MARD THE REQUIRED FIELDS FOR THE GIVEN INPUT*************SELECT MATNR WERKS LGORTFROM MARDINTO TABLE I_MARDWHERE WERKS = PLANT AND LGORT = STLOC.*****CHECK IF RECORDS ARE FETCHED IF NO EXIT OUT OF THE PROGRAM********IF SY-SUBRC <> 0. WRITE 'NO RECORDS'. EXIT.ELSE.***IF RECORDS ARE FETCHED FROM FRIST TABLE*********************************FETCH RELATED RECORDS FROM NEXT TABLE****************************** SELECT MATNR ERSDA ERNAM MTART MATKL FROM MARA INTO TABLE I_MARA FOR ALL ENTRIES IN I_MARD WHERE MATNR = I_MARD-MATNR.

Page 342: ABAP Tutorials

IF SY-SUBRC <> 0. WRITE 'NO MASTER DATA'. STOP. ELSE. SELECT MATNR SPRAS MAKTX FROM MAKT INTO TABLE I_MAKT FOR ALL ENTRIES IN I_MARA WHERE MATNR = I_MARA-MATNR AND SPRAS = 'E'. ENDIF.ENDIF.*****READ FROM INTERNAL TABLE FOR OUTPUT ******************************LOOP AT I_MARA INTO W_MARA.AT FIRST.WRITE : SY-ULINE(100), /1 SY-VLINE, 25 'EXAMPLE INTERACTIVE REPORT', 100 SY-VLINE, / SY-ULINE(100), /1 SY-VLINE, 2 'MATERIAL NUMBER' , 20 SY-VLINE, 22 'CREATION DATE', 40 SY-VLINE, 42 'USER NAME', 60 SY-VLINE, 62 'MATERIAL TYPE', 80 SY-VLINE, 82 'MATERIAL GROUP', 100 SY-VLINE, / SY-ULINE(100).ENDAT.ON CHANGE OF W_MARA-MATNR.READ TABLE I_MARD INTO W_MARD WITH KEY MATNR = W_MARA-MATNR.ENDON.WRITE :/1 SY-VLINE, 2 W_MARA-MATNR , 20 SY-VLINE, 22 W_MARA-ERSDA, 40 SY-VLINE, 42 W_MARA-ERNAM, 60 SY-VLINE, 62 W_MARA-MTART, 80 SY-VLINE, 82 W_MARA-MATKL, 100 SY-VLINE.HIDE W_MARA-MATNR.CLEAR W_MARA-MATNR.WRITE: / SY-ULINE(100).ENDLOOP.*****************END-OF-SELECTION.*************************************END-OF-SELECTION.****MOVING VALUES IN TO FINAL INTERNAL TABLE **************************LOOP AT I_MARA INTO W_MARA.ON CHANGE OF W_MARA-MATNR.READ TABLE I_MAKT INTO W_MAKT WITH KEY MATNR = W_MARA-MATNR.READ TABLE I_MARD INTO W_MARD WITH KEY MATNR = W_MARA-MATNR.

Page 343: ABAP Tutorials

ENDON. W_FINAL-MATNR = W_MARA-MATNR. W_FINAL-ERSDA = W_MARA-ERSDA. W_FINAL-ERNAM = W_MARA-ERNAM. W_FINAL-MTART = W_MARA-MTART. W_FINAL-MATKL = W_MARA-MATKL. W_FINAL-WERKS = W_MARD-WERKS. W_FINAL-LGORT = W_MARD-LGORT. W_FINAL-SPRAS = W_MAKT-SPRAS. W_FINAL-MAKTX = W_MAKT-MAKTX. APPEND W_FINAL TO I_FINAL.ENDLOOP.********AT LINE-SELECTION EVENT TRIGERING INTERACTIVE REPORTING.*******AT LINE-SELECTION.CASE SY-LSIND.WHEN 1.**DISPLAY OUTPUT IN NEW SCREEN AT LINE SELECTION BY USER MOUSE CLICK **WRITE: / W_MARA-MATNR COLOR 2.READ TABLE I_FINAL INTO W_FINAL WITH KEY MATNR = W_MARA-MATNR SPRAS = 'EN'.ULINE 1(200).WRITE : /1 SY-VLINE, 75 'EXAMPLE INTERACTIVE REPORT', 200 SY-VLINE, SY-ULINE(200), /1 SY-VLINE, 2 'MATERIAL NUMBER' , 20 SY-VLINE, 22 'CREATION DATE', 40 SY-VLINE, 42 'USER NAME', 60 SY-VLINE, 62 'MATERIAL TYPE', 80 SY-VLINE, 82 'MATERIAL GROUP', 100 SY-VLINE, 102 'PLANT NUMBER', 120 SY-VLINE, 122 'STORAG LOCATION', 140 SY-VLINE, 142 'LANGUAGE', 160 SY-VLINE, 162 'DESCRIPTION', 200 SY-VLINE, / SY-ULINE(200).WRITE :/1 SY-VLINE, 2 W_FINAL-MATNR , 20 SY-VLINE, 22 W_FINAL-ERSDA, 40 SY-VLINE, 42 W_FINAL-ERNAM, 60 SY-VLINE, 62 W_FINAL-MTART, 80 SY-VLINE, 82 W_FINAL-MATKL, 100 SY-VLINE, 102 W_FINAL-WERKS, 120 SY-VLINE,

Page 344: ABAP Tutorials

122 W_FINAL-LGORT, 140 SY-VLINE, 142 W_FINAL-SPRAS, 160 SY-VLINE, 162 W_FINAL-MAKTX, 200 SY-VLINE, / SY-ULINE(200).CLEAR W_MARA-MATNR.ENDCASE.

Downloading files onto the Application Server

By Vikram Chellappa, Mouri Tech Solutions

Description 

This is a demo application to download the data from the internal table of the application to a file in the application server. 

Step by Step Guidance. 

Go to transaction SE38 to open ABAP editor and Type in the program name click the create button. Here we have used “ZDOWNLOAD_APPL_DEMO” as the program name. 

 

Enter the Short Description for the program

Select the Program type to be “Executable program”

Page 345: ABAP Tutorials

 

Click on SAVE CHECK and ACTIVATE.

 

Page 346: ABAP Tutorials

Give the path of the file which has to be uploaded

Here we have the file in location “\USR\SAP\SRI\SYS\SRC\DOWN.TXT”

The drive name is taken as the default SAP installation drive.

 

OUTPUT LIST SCREEN

The data from the internal table is moved in to DOWN.TXT file in the Presentation server and out put displayed on the list screen shows the data in the internal table.

 

Output File in the Application server.  

Go to Transaction AL11 to see the SAP installation directories

Find our directory double click

Page 347: ABAP Tutorials

 

Find our downloaded file in the directory and double click it

Page 348: ABAP Tutorials

 

The Downloaded data is displayed 

 

SOURCE CODE REPORT ZDOWNLOAD_APPL_DEMO.TYPES : BEGIN OF ST_DEMO, REG_NO(10) TYPE C, NAME(20) TYPE C, ADDR(20) TYPE C, END OF ST_DEMO.DATA : WA_DEMO TYPE ST_DEMO, IT_DEMO TYPE TABLE OF ST_DEMO, L_FNAME TYPE STRING .PARAMETERS: P_FNAME(128) TYPE C DEFAULT '\usr\sap\SRI\SYS\src\DOWN.TXT' OBLIGATORY.L_FNAME = P_FNAME.WA_DEMO-REG_NO = '100001'.WA_DEMO-NAME = 'ANAND'.

Page 349: ABAP Tutorials

WA_DEMO-ADDR = 'NAGARKOVIL'. APPEND WA_DEMO TO IT_DEMO.WA_DEMO-REG_NO = '100002'.WA_DEMO-NAME = 'VIKRAM'.WA_DEMO-ADDR = 'CHENNAI'.APPEND WA_DEMO TO IT_DEMO. OPEN DATASET L_FNAME FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. WRITE :5 'REG NUM',16 'NAME',37 'ADDRESS' . LOOP AT IT_DEMO INTO WA_DEMO. IF SY-SUBRC = 0. TRANSFER WA_DEMO TO L_FNAME. WRITE :/5 WA_DEMO-REG_NO,16 WA_DEMO-NAME,37 WA_DEMO-ADDR. ENDIF. ENDLOOP.

Step-by-Step approach in creating a Function Module

By Sasidhar Reddy Matli, ROBERT BOSCH

1.       Open SE37 transaction.

Go to Goto à Function groups à Create group. 

 

2.       Give the function group name and short text. And click on Save. 

 

3.       Save this function group as local object. 

Page 350: ABAP Tutorials

 

4.       Then open the transaction se80 and select the ‘Function group’ from the drop down list. Enter the function group name. Press Enter. 

 

5.       Right click on ZSSR and press activate. 

Page 351: ABAP Tutorials

 

6.       Then you will get the following screen. Press Enter. 

 

7.       Go to the transaction se37 again and click on create. 

Page 352: ABAP Tutorials

 

8.       Now it will ask for the function group. Enter the function group and give the short text. Press Save. 

 

9.       Click on the Attributes tab and give the short text. 

 

10.   Click on the Import tab and enter the Parameter name, Type and Reference type of variables A and B. 

Page 353: ABAP Tutorials

 

11.   Click on Export tab and enter the Parameter name, Type and reference type of RES. 

12.     Click on Exceptions tab and enter the Exception and short text for that exception. 

Page 354: ABAP Tutorials

 

13.     Now click on the Source code tab and write the following lines as shown bellow. 

 

14.     Press syntax check button or Ctrl+F2. 

Page 355: ABAP Tutorials

 

15.     Now press on Activate button or press Ctrl+F3. 

 

16.     Press Enter. 

Page 356: ABAP Tutorials

 

17.     Now Press on Test button or Press F8. 

18.     Enter values for A and B. And press Execute or F8. 

Page 357: ABAP Tutorials

19.     The following screen will be displayed with result. 

 

20.     If you enter A value as 5. it will throw exception.

Page 358: ABAP Tutorials

21.     Output with Exception. 

 

22.     Now create and enjoy more Function Modules.

Displaying 3D Graphs in ABAP

By Swarna S, Tata Consultancy Services

*Simple report to create graph in ABAP*using GRAPH_MATRIX_3D function module*The graph shows the performance of 3 companies for the Four*quarters of a single year*AUTHOR : Swarna.S.REPORT Z_3DGRAPH.*structure declaration for performance measurement

Page 359: ABAP Tutorials

TYPES: BEGIN OF ty_performance, company(15) TYPE c, q1 TYPE i, q2 TYPE i, q3 type i, q4 type i, END OF ty_performance.*structure declaration for options tabletypes : BEGIN OF ty_opttable, options(30) TYPE c, END OF ty_opttable.*Internal table and work area declarationsDATA: it_performance TYPE STANDARD TABLE OF ty_performance, wa_performance TYPE ty_performance.DATA : it_opttable type standard table of ty_opttable, wa_opttable type ty_opttable.*initialization eventINITIALIZATION.*start of selection eventSTART-OF-SELECTION.*clearing the work areasCLEAR WA_PERFORMANCE.CLEAR wa_opttable.*appending values into the performance internal tablewa_performance-company = 'Company A'.wa_performance-q1 = 78.wa_performance-q2 = 68.wa_performance-q3 = 79.wa_performance-q4 = 80.append wa_performance to it_performance.wa_performance-company = 'Company B'.wa_performance-q1 = 48.wa_performance-q2 = 68.wa_performance-q3 = 69.wa_performance-q4 = 70.append wa_performance to it_performance.wa_performance-company = 'Company C'.wa_performance-q1 = 78.wa_performance-q2 = 48.wa_performance-q3 = 79.wa_performance-q4 = 85.append wa_performance to it_performance.*appending values into the options internal tablewa_opttable-options = 'P3TYPE = TO'.APPEND wa_opttable TO it_opttable.wa_opttable-options = 'P2TYPE = VB'.APPEND wa_opttable TO it_opttable.wa_opttable-options = 'TISIZE = 1'.APPEND wa_opttable TO it_opttable.*calling the graph function module CALL FUNCTION 'GRAPH_MATRIX_3D' EXPORTING col1 = 'Quarter 1' col2 = 'Quarter 2' col3 = 'Quarter 3' col4 = 'Quarter 4' dim1 = 'In Percentage%'

Page 360: ABAP Tutorials

set_focus = 'X' titl = 'Company Performances' TABLES data = it_performance opts = it_opttable EXCEPTIONS others = 1.

Tabstrips on the Selection Screen

By Sandipan Ghosh, Capgemini

Report ZTEST.DATA flag(1) TYPE c.* SUBSCREEN 1SELECTION-SCREEN BEGIN OF SCREEN 100 AS SUBSCREEN.SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME.PARAMETERS: Field1(20) TYPE c, Field2(20) TYPE c, Field3(20) TYPE c.SELECTION-SCREEN END OF BLOCK b1.SELECTION-SCREEN END OF SCREEN 100.* SUBSCREEN 2SELECTION-SCREEN BEGIN OF SCREEN 200 AS SUBSCREEN.SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME.PARAMETERS: q1(20) TYPE c , q2(20) TYPE c ,

Page 361: ABAP Tutorials

q3(20) TYPE c .SELECTION-SCREEN END OF BLOCK b2.SELECTION-SCREEN END OF SCREEN 200.* STANDARD SELECTION SCREENSELECTION-SCREEN: BEGIN OF TABBED BLOCK mytab FOR 10 LINES, TAB (20) button1 USER-COMMAND push1, TAB (20) button2 USER-COMMAND push2, END OF BLOCK mytab.INITIALIZATION. button1 = 'TAB1'. button2 = 'TAB2'. mytab-prog = sy-repid. mytab-dynnr = 100. mytab-activetab = 'BUTTON1'.AT SELECTION-SCREEN. CASE sy-dynnr. WHEN 1000. CASE sy-ucomm. WHEN 'PUSH1'. mytab-dynnr = 100. mytab-activetab = 'BUTTON1'. WHEN 'PUSH2'. mytab-dynnr = 200. mytab-activetab = 'BUTTON2'. ENDCASE. WHEN 100. MESSAGE s888(sabapdocu) WITH text-040 sy-dynnr. WHEN 200. MESSAGE s888(sabapdocu) WITH text-050 sy-dynnr. ENDCASE.MODULE init_0100 OUTPUT. LOOP AT SCREEN. IF screen-group1 = 'MOD'. CASE flag. WHEN 'X'. screen-input = '1'. WHEN ' '. screen-input = '0'. ENDCASE. MODIFY SCREEN. ENDIF. ENDLOOP.ENDMODULE.MODULE user_command_0100 INPUT. MESSAGE s888(sabapdocu) WITH text-050 sy-dynnr. CASE sy-ucomm. WHEN 'TOGGLE'. IF flag = ' '. flag = 'X'. ELSEIF flag = 'X'. flag = ' '. ENDIF. ENDCASE.ENDMODULE.START-OF-SELECTION. WRITE: / 'Field1:', Field1,'Q1:', q1, / 'Field2:', Field2,'Q2:', q2,

Page 362: ABAP Tutorials

/ 'Field3:', Field3,'Q3:', q3.

Output:

TAB1

TAB2

Page 363: ABAP Tutorials

Dynamic SELECT Statement (Enhanced functionality of Transaction SE16 and Index Identifier)

By Arnab Ganguly, Capgemini

Introduction:

The purpose of this document is to briefly describe a development, which will dynamically retrieve data from database tables, based upon user input. Here, table name can be specified by the use or which field needs to be displayed can be put into selection screen, even which will be the restricting criteria, also can be specified. The output will be displayed in simple report format.  

Along with the report, it will also notify the user whether Primary / Secondary index is being used or not during data selection.

In production system, there can be two ways of checking data from standard table / Custom table.

Conventional Method (Using transaction SE16). Dynamitic select statements (Describe in this document).

Conventional Method:

The following section will briefly describe what are the steps followed to check data using Conventional method:

Step1: 

Run transaction SE16 & put table name as selection criteria. 

 

Step2:

Choose the fields which will be the selection criteria for data selection from settings > Fields for selection

Page 364: ABAP Tutorials

Put the selection criteria: 

Step3: 

Report will be displayed in the following format: 

 

Page 365: ABAP Tutorials

Choose the desired output fields from Settings > Format list > Choose Fields. 

 

 

Page 366: ABAP Tutorials

 

The final report will be displayed: 

Step4:

Number of entries in the table can also be checked using SE16 Transaction.  

 

Step5: 

Page 367: ABAP Tutorials

Whether the data selection is done using primary / secondary index can also be checked using transaction SE11 / ST05. 

 

Dynamitic select statements

In this method we have written a program, which will take selection criteria dynamically (Table name, filter criteria, display fields) and produce a report with single user intervention. It will also display whether primary / secondary index is being used or not during data selection.  

Run the report ZDYN_ALV (for source code, click here). 

Page 368: ABAP Tutorials

 

Provide the field names for the selection criteria.  

 

Provide the selection criteria as below. 

Page 369: ABAP Tutorials

 

The output will be shown in the below format.

This program will display data in a single step execution. When we are trying to access live system from remote location each step execution (Dialog step) is very time expensive. This program will reduce the steps taken to display desired data. Also it will analyze the particular select statement is optimized or not by specifying the Index.

Downloading report output to Excel using OLE

By Lokesh Tripathi, Infosys

Introduction

In the following document we will be discussing how to download our report output into excel in the same format as in the SAP report output by using OLE concept.

To address an OLE Automation Server (e.g. EXCEL) from ABAP, the server must be registered with SAP.

ABAP keywords  

Page 370: ABAP Tutorials

ABAP keywords allow us to control the applications in the form of an OLE2 Automation Server from an ABAP program:  

The following ABAP key words control the applications: 1)       CREATE OBJECT

This command generates an object of the class “class”.

Basic form: CREATE OBJECT obj class.

Addition: LANGUAGE langu - determines the language chosen for method and attribute names of the object class. If no specification is made, English is the default.

This creates the instance for the automation object at the automation interface.  

2) SET PROPERTY

This command sets the property prop of the object obj according to the contents of the field fld. The object obj must be of type OLE2_OBJECT.  

Basic form: SET PROPERTY OF obj prop = fld.

Addition: NO FLUSH- The addition NO FLUSH continues the collection process; even if the next command is not an OLE statement.Thus we can set series of properties in a single transport operation.  

3) GET PROPERTY

This command copies the property p of the object obj to the field f. The object obj must be of type OLE2_OBJECT.

Basic form: GET PROPERTY OF obj p = f.

Addition: NO FLUSH  

4) CALL METHOD

The ABAP key word CALL METHOD calls the method m of the object obj. m can be a literal or a variable.

Basic form: CALL METHOD OF obj m.

Additions:

1. = f Stores the return value of the method in the variable f.

2. EXPORTING p1 = f1... pn = fn

It passes values of fields to the parameters of the method.

If assignment of parameters is by sequence, p1, p2,... must begin with "#", followed bythe position number of the parameter.

Page 371: ABAP Tutorials

The exporting parameters always come at the end of the statement.

3. NO FLUSH.

5) FREE OBJECT

This will releases the storage space required for the object obj. The object can then no longer be processed.  

Now let understand the concept of OLE by taking one example.

Suppose we want exactly this type of output in excels.  

Before starting with OLE, include type pool ole2 in your program.  

 

Note that for each OLE object there has to be a variable holding handle data for that object. The type-pool “ole2” defines the handle variable data of the type ole2_object.For all the OLE automation programs “OLE2INCL” include should be used.  

STEP 1:

First step is to create OLE object for excel application.  

CREATE OBJECT gh_excel 'EXCEL.APPLICATION'.  

gh_excel is the object of type ole2_object.

Page 372: ABAP Tutorials

STEP 2:

Now different properties of the excel object is to be set as per our requirement.

SET PROPERTY OF gh_excel ‘visible’ = 0.

The excel sheet is not visible to the user while data transfer.

CALL METHOD OF gh_excel 'Workbooks'= gh_mapl.

This will call the method of excel ‘Workbooks’ to get the control to object gh_mapl.

gh_mapl is the object of type ole2_object.

CALL METHOD OF gh_mapl 'Add'= gh_map.

It will create a new workbook.  

Now create active sheets of excel.

CALL METHOD OF application 'Worksheets' = sheet

EXPORTING #1 = 1.

CALL METHOD OF sheet 'Activate'. “Activate the sheet.  

SET PROPERTY OF sheet 'Name' = 'sheet_name'.   Sheet is the object of type ole2_object. Similarly you can create many number of sheets in excel. STEP 3:

Now fill the data part into excel.

We will first fill the header part in excel.

PERFORM fill_cell USING 1 7 1 ‘MONTHLY_BILL’.

It will print “Monthly_Bill” in the 7th column of the 1st row of excel.

Here we had used the form “FILL_CELL” for filling the data into the cells.

FORM fill_cell USING i j bold val. “For filling data in excel.

CALL METHOD OF gh_excel ‘CELLS’= gh_zl NO FLUSH

EXPORTING #1 = i #2 = j. “Transferring data to row = i and column = j.

PERFORM err_handle. “For handling automation error.

Page 373: ABAP Tutorials

SET PROPERTY OF gh_zl ‘VALUE’ = val no flush.

GET PROPERTY OF gh_zl ‘FONT’ = gh_f no flush.

SET PROPERTY OF gh_f ‘BOLD’ = bold no flush.

ENDFORM. " fill_cell

Here i = excel row number.

J = excel column number.

Bold = 1 then text will print in Bold.

0 then normal text will be printed in excel.

Val = text you want to print .

Similarly fill all the header details in excel.

i.e.

PERFORM fill_cell USING 2 1 1 ‘VODAPHONE’. “Transferring data to 2nd row and 1st column.

PERFORM fill_cell USING 2 2 1 ‘COMPANY’. “Transferring data to 2nd row and 2nd column.

PERFORM fill_cell USING 3 2 1 WA_OUTPUT-PEIOD. “Transferring data to 3rd row and 2nd column.

PERFORM fill_cell USING 4 1 1 ‘S. No’. “Transferring data to 4th row and 1st column.

PERFORM fill_cell USING 4 2 1 ‘Customer Name’. “Transferring data to 4th row and 2nd column.

PERFORM fill_cell USING 4 3 1 ‘Duration’.  “Transferring data to 4th row and 3rd column.

PERFORM fill_cell USING 4 4 1 ‘Cost’.  “Transferring data to 4th row and 4th column.

PERFORM fill_cell USING 4 5 1 ‘Bill’. “Transferring data to 4th row and 5th column.

After filling the header part fill all the line item details in excel.

STEP 4:

In this scenario we want some columns to be merged in our excel output.

i.e. (column from A1 to E1, column from B1 to E1, etc..)

Page 374: ABAP Tutorials

Now, for this first we select the range of cells. And then merge the range of cells.

CALL METHOD OF gh_excel ‘RANGE’ = gh_rang NO FLUSH

EXPORTING #1 = ‘A1’

#2 = ‘E1’

CALL METHOD OF gh_range ‘SELECT’ NO FLUSH.

SET PROPERTY OF gh_range ‘MERGE’ = 1 no flush.

STEP 5:

Now format the excel according to the requirement.

         To set the width of the column according to the text.

CALL METHOD OF application 'COLUMNS' = COLUMN.CALL METHOD OF COLUMN 'AUTOFIT'.  To delete some line from the excel, then can call this method,

CALL METHOD OF gh_excel 'ROWS' = row Exporting #1 = 1.CALL METHOD OF row 'DELETE'.Free object row.

         To change the format of some cells in excels.

For doing this first set the ranges of the cell we want to format and then change the format of these cells.

For e.g. this will set last 1st row 4th column

CALL METHOD OF gh_excel 'Cells' = wf_cell_from1     EXPORTING     #1 =1    #2 = 4.

Set last 3rd row 4th column.

CALL METHOD OF gh_excel 'Cells' = wf_cell_to1    EXPORTING    #1 = 3    #2 = 4.

Set the range here,  CALL METHOD OF wf_excel 'Range' = wf_cell1

Page 375: ABAP Tutorials

    EXPORTING    #1 = wf_cell_from1    #2 = wf_cell_to1.

Now Format the range of cells here  SET PROPERTY OF wf_cell1 'NumberFormat' = ’@’. ”Here we are setting to this format.

         To have grid lines in our excel output.

For this first set the ranges of the column.

CALL METHOD OF gh_excel ‘RANGE’ = gh_range NO FLUSH

EXPORTING #1 = ‘A1’  “starting from column A

#2 = ‘M’.  “up to column M

Now set the style of all the border position.

For Left edge border, set the line style to 1.

CALL METHOD OF gh_range ‘Borders’ = gh_borders NO FLUSH

EXPORTING #1 = 7.

SET PROPERTY OF gh_borders 'LineStyle'= 1.

Similarly we can call this method for other positions.

For right edge border, export with 10.

For top edge border, export with 8.

For bottom edge border, export with 9.

For inside vertical border, export with 11.

For inside horizontal border, export with 12.

This will set the grid lines in excel like this,  

Page 376: ABAP Tutorials

 

Suppose we want to change the color and width of any particular column.

CALL METHOD OF gh_excel ‘Cells’ = e_cell

EXPORTING #1 = 1 #2 = 3

GET PROPERTY OF e_cell 'Interior' = e_color.

SET PROPERTY OF e_color 'ColorIndex' = 35.

SET PROPERTY OF e_cell 'ColumnWidth' = 20.

Codes for different colors.

STEP 6:At last free all the reserved OLE objects. i.e. Free object column. Free object gh_excel.  Now Save excel spreadsheet to particular filename and quit the excel application. CALL METHOD OF sheet 'SaveAs'

Page 377: ABAP Tutorials

EXPORTING #1 = 'c:\your_excel.xls' "name of excel #2 = 1. "file format CALL METHOD OF sheet 'QUIT'. This closes the Excel documentSET PROPERTY OF application 'visible' = 0. It will close visible excel window and data is lost if not saved.Now our data get saved into excel naming ‘your_excel’.

Understanding "ABAP Unit"

By Nithya Murugesan, YASH Technologies

Introduction:

It is a best practice to modularize our programs as much as we can for better programming. If we want to check one particular module like subroutines, function modules or classes for bugs then we can do it using ABAP Unit. ABAP Unit is a tool for unit testing of ABAP programs.  

How to write these tests:

ABAP unit is based on ABAP objects. The global class CL_AUNIT_ASSERT contains methods which can be used for testing .Tests are implemented in local classes. Inside the local class the necessary method from the global class can be called for testing. These test classes can be written inside the program for which the test is to be done. It will not affect our production code in anyways.  

Difference between Ordinary class and Test class:

Both the test class and test method should have FOR TESTING addition.  

Ex:

CLASS mytest DEFINITION FOR TESTING.

PRIVATE SECTION.

METHODS mytest FOR TESTING.

ENDCLASS.  

Methods in CL_AUNIT_ASSERT for Testing:  

ASSERT_EQUALS ASSERT_DIFFERS

ASSERT_BOUND

Page 378: ABAP Tutorials

ASSERT_NOT_BOUND

ASSERT_INITIAL

ASSERT_NOT_INITIAL

ASSERT_CHAR_CP

ASSERT_CHAR_NP

ASSERT_EQUALS_F

FAIL

ABORT  

ASSERT_EQUALS - Checks the equality of two data objects.

ASSERT_DIFFERS - Checks for the difference of two data objects.

ASSERT_BOUND - checks for the validity of the reference of a reference variable.

ASSERT_INITIAL - checks whether the reference of a reference variable is invalid.

ASSERT_NOT_INITIAL - checks whether the data object is not having its initial value.

ASSERT_SUBRC - checks for the specific value of SY-SUBRC.

ASSERT_EQUALS:  

ASSERT_EQUALS is one of the methods in the class CL_AUNIT_ASSERT. This method can be used for checking equality of two data objects.  

The parameters of the method:  

ACT - Actual result

EXP - Expected Result

MSG - Message to be displayed in the result

LEVEL - Error level (Tolerable/Critical/fatal)

QUIT - If the test fails, flow level is controlled using this

(NO/METHOD/CLASS/PROGRAM)

TOL - Tolerance level for F  

Page 379: ABAP Tutorials

Levels:

0 - Tolerable 1 - Critical

2 - Fatal

Quit:

No ( 0 ) – It will continue the current test Method. Method ( 1 ) – It will interrupt the current test method

Class ( 2 ) – It will interrupt the current test class.

Program ( 3 ) – abandon execution of all test classes for the tested program.  

Tolerance:

If the tolerance limit specified is exceeded then error is shown.

Ex:

Actual result – 24.

Expected Result – 25.

Tolerance – 0.9999. Difference = Expected Result - Actual result. = 1 > tolerance.Therefore displays an error.  

Example Program:  

Let us consider an example for ABAP unit test using the method ASSERT_EQUALS to check the equality of two data objects. In this program, we have two methods divide and factorial in a local class MATH. We want to test the factorial method. So we have created one class and one method MYTEST for testing. In the test method implementation we have called the factorial method and so the data object RESULT is populated. Now we are going to compare the actual data object (RESULT) with the expected result. For that we are calling the ASSERT_EQUALS from the global class passing the expected result.

*----------------------------------------------------------------------** CLASS math DEFINITION*----------------------------------------------------------------------***----------------------------------------------------------------------*CLASS math DEFINITION. PUBLIC SECTION. METHODS divide IMPORTING opr1 TYPE i

Page 380: ABAP Tutorials

opr2 TYPE i EXPORTING result TYPE f RAISING cx_sy_arithmetic_error. METHODS factorial IMPORTING n TYPE i RETURNING value(fact) TYPE i.ENDCLASS. "math DEFINITION*----------------------------------------------------------------------** CLASS math IMPLEMENTATION*----------------------------------------------------------------------***----------------------------------------------------------------------*CLASS math IMPLEMENTATION. METHOD divide. result = opr2 / opr1. ENDMETHOD. "divide METHOD factorial. fact = 1. IF n = 0. RETURN. ELSE. DO n TIMES. fact = fact * sy-index. ENDDO. ENDIF. ENDMETHOD. "factorialENDCLASS. "math IMPLEMENTATIONSTART-OF-SELECTION. DATA w_obj TYPE REF TO math. DATA exc TYPE REF TO cx_sy_arithmetic_error. DATA res TYPE f. DATA result TYPE i. DATA text TYPE string. CREATE OBJECT w_obj. TRY. w_obj->divide( EXPORTING opr1 = 32 opr2 = 4 IMPORTING result = res ). WRITE : res. text = res. CATCH cx_sy_arithmetic_error INTO exc. text = exc->get_text( ). MESSAGE text TYPE 'I'. ENDTRY. CREATE OBJECT w_obj. COMPUTE result = w_obj->factorial( 4 ). WRITE :/ 'The result for factorial is:',result.*----------------------------------------------------------------------** CLASS mytest DEFINITION*----------------------------------------------------------------------***----------------------------------------------------------------------*CLASS mytest DEFINITION "#AU Risk_Level Harmless FOR TESTING. "#AU Duration Short PRIVATE SECTION. METHODS mytest FOR TESTING.ENDCLASS. "mytest DEFINITION*----------------------------------------------------------------------*

Page 381: ABAP Tutorials

* CLASS mytest IMPLEMENTATION*----------------------------------------------------------------------***----------------------------------------------------------------------*CLASS mytest IMPLEMENTATION. METHOD mytest. CREATE OBJECT w_obj. result = w_obj->factorial( 4 ). cl_aunit_assert=>assert_equals( act = result exp = '24' msg = 'Factorial Not calculated Correctly' level = '0' quit = '2' tol = '0.999' ). ENDMETHOD. "mytestENDCLASS. "mytest IMPLEMENTATION

Executing Unit Tests:

For program,

Program -> Test -> Unit Test.  

For class,

Class -> Unit Test.  

For Function Module,

Function Module -> Test -> Unit Test.  

Result of Unit Test:  

If both the actual and the expected result is same, then Unit test does not find any errors. In that case one message will be displayed on status bar like,

 

If it finds errors then a result will be displayed as follows:  

Page 382: ABAP Tutorials

The task is displayed in a tree structure with a Program name, Class name and method name. Both the expected and the actual results can be seen in the Unit test results. Also in the stack it will be displaying the line number where the error occurred. By double clicking the line number we can enter into the source code.  

ABAP Unit results in Code Inspector:

We can see the ABAP unit results in code inspector. While creating the variant, check for the ABAP unit in Dynamic check.

Page 383: ABAP Tutorials

 

In the Code inspector results we can check for the ABAP unit errors, warnings and informations.

Page 384: ABAP Tutorials

Understanding "Checkpoint Group"

By Richa Tripathi, Yash Technologies

The checkpoints are the type of statements introduced in the SAP Web Application Server (SAP WebAS) 6.20 that is totally dedicated to ensuring program correctness and maintainability. This improves the quality of software written in ABAP. These checks are transportable and can be transported .The transaction that takes care of these checkpoints and the place where they are maintained is SAAB.  

The Checkpoints now can be created for break-points and checkpoints and the two statements for this are  

1. Assertions 2. Break-points  

The one which actually does not checks the errors but is used to log the data that u want is LOG-POINT.  

To start with step by step explanation of the checkpoints we start first with the Assertions.  

Assertions syntax as per the SAP Library that is to be used in the coding is as below:

ASSERT [[ID group [SUBKEY subkey]]        [FIELDS field1 field2 table1 table2...]        CONDITION] log_exp.  

Assertions are used as a high quality means of problem determination in the case of code failure. Assertions are invoked at run time. They can be made active or inactive. Assertions can be left in code when promoted to production with no impact to the code. They are only invoked if the checkpoint group is activated.

The checkpoint groups can be activated through the transaction SAAB and that is referred by ID in the programs with assert statements.

This is the transaction below SAAB where in the checkpoint group we can create the group ID.

Page 385: ABAP Tutorials

Clicking on the create button below the Name we get to the below screen.

Now the checkgroup activation can be done with three levels  

1. Personal Activation 2. User Level activation

3. Server Level Activation.  

In the personal level activation that checkgroup will be active for the current user only and for the User the Checkgroup will be active for that user that has been defined and same is for the Server.  

The User when clicked there you can define the Specific users for it as this…  

And similarly it can be done for specific Servers on clicking on the add Sign as below:  

Page 386: ABAP Tutorials

As for the screen below:-  

There are three things that can be controlled with the checkgroups.  

The breakpoints can be made active or inactive. Inactive then that particular statement will be ignored and if break then in the program wherever the statement occurs the program gets into debugging.  

The Statement as per the SAP Library that goes with this in the Program is as below…  

BREAK-POINT { [ID groupID]            | [log text] }.  

Ex. BREAK-POINT ID YH_check.  

Without the addition ID, the breakpoint is always active. The log text is the text which you can specify for the system log which is seen in the logs getting created.

During background processing the program execution is not interrupted. If the program reaches a breakpoint, the entry "Breakpoint reached" is written to the system protocol under which the program name and the location of the breakpoint in the program are recorded. An inactive breakpoint is ignored.

Now taking for the assertions…

Following are the ways the assertion can be used:-

Inactive (default): statement is ignored Log: occurrence is logged

Abort: program terminates with runtime error ASSERTION_FAILED  

Page 387: ABAP Tutorials

The below two options come with a pop-up having options as:-

Break/Log: program is interrupted and starts the debugger / like LOG mode in background, batch etc.

Break/Abort: program is interrupted and starts the debugger / like ABORT mode in background, batch etc.

The below two options come as this...

Assertion RULES:

1. Exception handling should always be used to trap and handle failures. DO NOT use an assertion in the place of exceptions.

2. Assertions should only be used on custom code rather than on standard codes.

3. When an assertion is invoked, it should create a log entry unless and until there is a compelling reason to terminate with a run time error.

Here is a sample program where the LOG-Points and ASSERTIONS are used.

REPORT yh1316_test_checkgrp..      ** Parameters DeclarationsPARAMETERS:  p_carrid LIKE sflight-carrid.

*data : max type i.*Types Declarations of sflightTYPES : BEGIN OF type_s_sflight,        carrid  TYPE sflight-carrid,        connid  TYPE sflight-connid,        fldate  TYPE sflight-fldate,        price   TYPE sflight-price,        max TYPE i,

Page 388: ABAP Tutorials

        END OF type_s_sflight.

*Field String Declarations for sflightDATA: fs_sflight TYPE type_s_sflight.

*Internal table for Sflight DataDATA : t_sflight LIKE                 STANDARD                 TABLE OF fs_sflight.DATA  yh1316_subkey TYPE char200.

IF p_carrid IS INITIAL.  SELECT carrid         connid         fldate         price   FROM sflight   INTO fs_sflight.    WRITE: / fs_sflight-carrid,            fs_sflight-connid,            fs_sflight-fldate,            fs_sflight-price.        APPEND fs_sflight TO t_sflight.    ASSERT ID yh1316_check SUBKEY    'YH1316_parameter_if_initial'                           FIELDS    p_carrid                                     t_sflight                                     fs_sflight-carrid                                     fs_sflight-connid                                     fs_sflight-fldate                                     fs_sflight-price                           condition p_carrid  eq  'LH'  .

  ENDSELECT.

  ASSERT ID yh1316_check SUBKEY    'YH1316_1'                       FIELDS    p_carrid                                 t_sflight         CONDITION p_carrid  EQ  'LH'  .  EXIT.ELSE.

  ASSERT ID yh1316_check SUBKEY    'YH1316_2'                     FIELDS    p_carrid                               t_sflight       CONDITION p_carrid EQ ’LH’.

  SELECT carrid connid fldate MAX( price ) AS max  INTO CORRESPONDING FIELDS OF fs_sflight  FROM sflight  WHERE carrid EQ p_carrid  GROUP BY carrid connid fldate  ORDER BY carrid max DESCENDING.

Page 389: ABAP Tutorials

IF sy-dbcnt < 4.

    APPEND fs_sflight TO t_sflight.    LOG-POINT ID yh1316_check SUBKEY    'LOG_POINT'                       FIELDS    p_carrid                                 t_sflight                                 fs_sflight-connid                                 fs_sflight-fldate                                  fs_sflight-max.    WRITE: / fs_sflight-carrid, fs_sflight-connid, fs_sflight-fldate,    fs_sflight-max.

 ENDIF.  ENDSELECT.ENDIF.

A variant is created for the Particular Checkgroup created. Variant can be created as a Local as well as at a user level. Here it is created at the User Level.

Click on create and enter the following entries.

Page 390: ABAP Tutorials

There are four kind of object type for which a variant can be created as

1. Check Group

2. Program

3. Class

4. Function Group

And for particular Object type the Different options can be given for Breakpoint, Logpoint and Assert. The Options for them are same as stated before in the Personal Activation screen for check group.

Now save the variant and then go back to the checkgroup for which we have created the variant. Don’t forget to activate the variant.

Page 391: ABAP Tutorials

As above it is seen the Local variant is visible in the Variants tab the same way we can create a Global variant also.

Now run the Program.

If the assertion condition is violated the listed logs are created for the assertion as we have selected the log for assertion in the SAAB transaction in the Check Group.

The log will also be created for the LOG-POINT statement and the SUBKEY there defines the Key to distinguish that the log has been created for which Assertion and checkpoint.

In the Log the data is segregated according to the two Hierarchies:-

1. Gropu/Subkey/Program/Procedure

2. Group/Program/Procedure/Subkey  

The log seen is like this.

Page 392: ABAP Tutorials

Double clicking on the Line where the Include line number is seen we can see the description of the log as below.

Page 393: ABAP Tutorials

As we have logged the table entries also double clicking on the table we can see the table entries too.

Page 394: ABAP Tutorials
Page 395: ABAP Tutorials

Understanding "Coverage Analyzer"

By Tanveer Zahaque, YASH Technologies

Coverage Analyzer is a very powerful runtime analysis tool provided by SAP that enables an ABAP developer to monitor processing blocks such as reports, subroutines, function-modules and methods.

Powerful filtering system in Coverage Analyzer facilitates developer to enter the number of calls separately according to periods, users and functional areas.

In a nut-shell; Coverage Analyzer is a function for monitoring the system-wide execution of ABAP programs;

It enables the success of test activities to be assessed for quality checks.

It also provides an overview of the use of programs for development purposes.

Developer can use this tool to trace programs for development purpose and Quality Manager can use this tool to check system performance for quality assurance.

It helps carry out a range of Administration Settings and the Monitoring Activity. Moreover it helps get summarized information of number of program executions, number of runtime errors, number of program

Page 396: ABAP Tutorials

resets. Fascinatingly, the results can be formatted separately according to user-group; each user-group can contain any number of users under one test key.

Broadly, functions of Coverage Analyzer are classified into two;

1.       Administration Settings

On/Off. Test Groups.

Registrations.

Reset.

Settings.

Monitor.

Consistency Checks.

2.       Display

Global. Detail.  

A simple exercise will help us easily understand Coverage Analyzer, rather simply going through documentation.

In order to make use of Coverage Analyzer, user has to have an appropriate role. To check user authorization;

Call up transaction SUIM (User Information System).

Expand Authorizations node.

Choose By Object and execute it (press F8).

Page 397: ABAP Tutorials

 

Check the presence of authorization object S_COV_ADM in the system.

 

Page 398: ABAP Tutorials

Confirm the where-used list for profiles using icon or Ctrl+Shift+F11.

Once user authorization is checked to have absolute access to SCOV (Coverage Analyzer) transaction; user can proceed further. If a role is not assigned to a user, Basis consultant has to be consulted in this regards.

In fact, a tip to be remembered is that Coverage Analyzer tool should be used on weekends or in the evening, when all users and packages are on loose ends. Since backup server collects data from all the servers including local and remote; system needs all packages and users to be in the passive mode.  

Let’s start up with a simple example to understand Coverage Analyzer in a better way:

STEP 1: Call up the transaction SCOV or navigate through SAP Easy Access->SAP Menu->Tools->ABAP Workbench->Test->SCOV (Coverage Analyzer).

Page 399: ABAP Tutorials

 

General Status of the system is shown on the right hand pane of the window;  

Coverage Analyzer administration includes all of the functions required for carrying out settings and checks.

Page 400: ABAP Tutorials

Administration and Display nodes are shown on the left pane of the window.  

STEP 2: Before the Coverage Analyzer being switched on, settings have to be maintained for backup server and filters are to be set. Having not made settings for backup server, if Coverage Analyzer is started, it simply throws out an information message to maintain background server for data collection.

 

So, Administration settings are to be done before starting up the Coverage Analyzer.

Expand Administration node, select Settings;

Settings function is used to set the parameters for the Global and Detail views, and to filter the programs to be checked via the package.

In order to make settings, switch settings to Change Mode (Cntrl+F1).  

Tip to remember: A program is regarded as tested if the following conditions are fulfilled;

Count1 Absolute Value  >  0.

Count2 Absolute Value  > 0.

Page 401: ABAP Tutorials

RABAX2 Absolute Value  = 0.

Unicode Check  = 1.  

Count1 and RABAX1 indicate the number of programs executed and runtime errors since the Coverage Analyzer was started.

Count2 and RABAX2 indicate the number of programs executed and runtime errors since the last reset.  

Further, assign package to be used during analysis. When a package is pre-selected, the evaluation for the Global view is only performed for this package. If this restriction is not applied, all of the programs are included together with those from local packages ($*) and programs generated locally without packages ( ).

If ABAP programs with a set Unicode flag are only to be traced by the Coverage Analyzer, then select Unicode checkbox. Checking Unicode is to mark it as ‘X’, else leave it unattended.

 

It’s optional to set the lights; lights provide a visual means of representing the status of the results for the degree of coverage in the Global and Detail views.

Lights are set by default, which can be set according to developer’s way of analysis.

RED  0 LT 33 %

YELLOW 33 LT 66 %

GREEN66 LE 100%  

Page 402: ABAP Tutorials

 

Further, Monitor Settings have to be done, which includes setting Trace Level and Maximum Entries Log and Maximum Entries Data Monitor.

There are 4 different trace levels (1-4), the higher the trace level, the more information is drawn for debugging.  

 

Tip: The values for Maximum Entries Log and Maximum Entries Data Monitor limit the lines displayed for the General Log and Monitor Data Volumes in the monitor function.

The defaulted lines for log file are 100 and for data volume are 200.  

Background server has to be specified, where precisely data is to be collected. Moreover, the period for which background job has to be repeated is also to be specified.

The defaulted value for Data Collection: Period (Min) is 30 mins, which can be modified based on developer’s way of analysis. In this case, current server is specified as Background server.

Further, Summarization function facilitates checking the same processing blocks in several systems simultaneously.

Tip to remember: The results from the individual systems are local and those from the remote systems are summarized.

Local Degree of coverage  LE  100%.

Summarized degree of coverage LE 100%.

Local Degree of coverage GE Summarized degree of coverage.  

To determine RFC connection with current server, call up transaction SM59->RFC Destinations->R/3 Connections->E6SCLNT900.  

Page 403: ABAP Tutorials

Desired RFC connections in Summarize coverage results can be specified; moreover period and start time for summarize data can also be specified.

Finally, save the Settings.  

STEP 3: Choose On/Off, Status in the Administration node and start up the Coverage Analyzer.

Switch Coverage Analyzer On/Off: This displays the number of programs that have been initialized.

Switch Automatic Recordings On/Off: This displays the automatic recording period and the version number for the Global view.

Switch Data Aggregations from Different Remote Systems: This displays background server and all of the other systems whose results are used for Data-aggregation.

 

If the server is in switched-off mode exception shows RED signal, GREEN signifies server to be in switched-on mode and YELLOW represents either RFC problem or database and shared memory inconsistency.  

In this case, we’ll proceed without switching on Switch Automatic Recording On/Off.

Page 404: ABAP Tutorials

The servers which are actually running are shown as flagged up.  

STEP 4: Create Test-Groups; Test-Groups are made to summarize and display the results of the Coverage Analyzer for a particular set of users under one generic key/heading.

Tip to remember: Test-groups should not be created more than 10. Moreover, only users assigned a role with the authorization object S_COV_ADM are allowed to define group.  

Two pre-defined Test-groups are always available;

ALL – Coverage results summarized for all test groups on the local system.

COND – Coverage results on the local system as well as remote system.  

In this case, we create a test-group.

To create a test-group; switch on the Change Mode, click Append Row icon provided in the application tool-bar.

 

Define a Test-group following Y/Z naming convention; then save it.

Page 405: ABAP Tutorials

STEP 5: Next step is to assign users to the just-made test-group.

To assign Users to a test-group; switch on the Change Mode, click Append Row icon provided in the application tool-bar.

 

Select desired test-group for which users have to be assigned; in this case we assign SAPDEV02 as user to test-group ZTST.

Tip: A test-group can contain any number of users, for example, all HR developers in one group. That makes filtering pretty easy. Moreover, comparison of performance of test-groups can be done in Global view.  

STEP 6: An optional function to be done is Reset; explicitly this function is intended for situations in which the results of the previous analyses are no longer required. It resets all the counters of the Coverage Analyzer to 0 for all the programs of a selected group.

Page 406: ABAP Tutorials

Further more, implicit reset is carried out automatically as soon as the flow or the data of a program changes.

After successful reset, an information message is popped-up;

 

STEP 7: Consistency check has to be done for all the servers including remote ones, before proceeding

to actual analysis;

Check Status of All Servers checks whether the status in the shared memory matches the status in the database.

Check Status of Background Jobs checks whether all the batch jobs of the Coverage Analyzer are activated. If this is not the case, the batch jobs are all rescheduled by means of the Repair function.

Page 407: ABAP Tutorials

Check Table Consistency (Long Runtime) may become inconsistent if the Coverage Analyzer fails on an application server due to system error.

Repair function also bridges the gap between activating and generating a program.  

So, in order to check inconsistencies, check the types of inconsistencies accordingly and Execute Checks, and then choose monitor to check for the inconsistency messages,

GREEN indicates Information message, YELLOW indicates Warning message and RED indicates Error message.

In the present case; no inconsistencies have been found while starting All Servers. In case, there arise any warning or error messages, those problems are to be fixed and then select particular row of the warning/error message and click Completed.  

General Log gives general information, while Monitor Volume gives detailed information of started server.

Once the warning is attended, select the row and hit Completed, which will going to turn yellow signal to green signal.

Tip: Every time inconsistencies are checked; General Log should be refreshed.

To select more than 1 message, keep Cntrl key pressed.  

Page 408: ABAP Tutorials

STEP 8: Display; gives coverage results at author or package level according to criteria you select under Settings. Display gives high-level view.

Views can be based on Author or Package. ALL signifies all the authors on local system based on view given and the COND (y/z test groups) signifies all the authors on both local and remote systems based on view given. If ‘Other view’ is selected as Package, then selection is done accordingly.

 

Note: Since Automatic Recordings were not switched on; percentage-based progress display over time cannot be seen for selected SAPDEV02 author.  

Normally, Display view gives Quality Managers to view the system, the following way;

Page 409: ABAP Tutorials

Unicode:

This value indicates how many percent of the processing blocks have the Unicode flag set (the flag itself is set per program)  

Capacity Utilization:

This value is computed as the ratio of used processing blocks to loaded processing blocks to loaded processing blocks.  

Accumulated Executions (Percent)

This value indicates in percent how many processing blocks have been executed since the start of the Coverage Analyzer.  

Tested processing blocks (Percent)

This value indicates in percent how many processing blocks have been executed in the actual version without runtime errors.

In the example above you can see that currently 98% of the processing blocks in the system belong to a program that has the Unicode flag set, 26% have been executed since start of the coverage analyzer, 9% have been executed in the active version without errors and the capacity utilization is 29%.  

Page 410: ABAP Tutorials

STEP 9: Exact Value Table can be viewed for author SAPDEV02; which displays number processing blocks for author SAPDEV02 on timely manner.

Graphical view of the selected row can be seen using icon; that displays graphical view of the individual date and all dates when no row is selected.

All rows selected for graphical analysis;

 

Individual selection for graphical analysis;

Page 411: ABAP Tutorials

 

Tip: Moreover, previous saved history can also be viewed for the specific user.  

STEP 10: Details view; gives summarized and detailed results. Details give low-level view.

Strong filtering options allow user to select on what conditions results are to be displayed.  

Page 412: ABAP Tutorials

Conditions can be set for range of test-groups, packages and authors pertaining to those test-groups.

In the present example; test-group ZTST and Author SAPDEV02 is taken as single-value selection, which gives results pertaining to specified criteria. Moreover, other filters can also be set and settings should be done defining access via Package Object, Package and Author. Defaulted access-via is Program Object.

Page 413: ABAP Tutorials

Hitting Standard Settings is going to reset all the values.  

Once settings are done; hit execute button, that is going to get detailed information, including number of calls made to that particular object, number of processing blocks, load size in Kilo byte. Besides all the information given; double-clicking the object name will navigate to the particular program or executing block where exactly error has been found.

 

Page 414: ABAP Tutorials

Note: Current Executions = Program units currently used / Total no. of Program units.

Capacity Utilization = No. of Program units currently used / Loaded Program units.  

Conclusion: Likewise, many such program executions, runtime errors and program resets can be easily traced using this powerful ABAP runtime analysis tool - Coverage Analyzer.

FTP file transfer in Background

By Joffy John, Collabera

1)       Creating RFC Destination for FTP.  

Run program: RSFTP005.  

The RFC destinations SAPFTP and SAPFTPA will be created automatically.  

a)       SAPFTP (for local system)

b)       SAPFTPA (for running in Application server)(This is used for file transfer in background.  

2)       Code sample for developing FTP programs can be got from report program  

a)       RSFTP002

b)       RSFTP007

Page 415: ABAP Tutorials

c)       RSFTP008  

3)       Sample code for getting customer details as tab delimited .TXT file in background.

*&---------------------------------------------------------------------**& Report ZCUSTOMER*&*&---------------------------------------------------------------------**&-Customer -All new/changed customer records created during the period.*&---------------------------------------------------------------------**LedgerKey-------------Char(50)*AccountName-----------Char(80)*AccountReference -----Char(50)*Address1 -------------Char(80)*Address2 -------------Char(80)*Town -----------------Char(50)*County / State -------Char(50)*Post Code / ZIP ------Char(20)*Country---------------Char(2)*AccountCurrencyCode --Char(3)*ContactTelephone -----Char(20)REPORT zcustomer.TABLES: kna1,knb1.TYPES: BEGIN OF st_customer, ledgerkey TYPE char50, name1 TYPE kna1-name1, kunnr TYPE kna1-kunnr, name2 TYPE kna1-name2, stras TYPE kna1-stras, ort01 TYPE kna1-ort01, regio TYPE kna1-regio, pstlz TYPE kna1-pstlz, land1 TYPE kna1-land1, waers TYPE knvv-waers, telf1 TYPE kna1-telf1, END OF st_customer.TYPES : BEGIN OF st_cus, ledgerkey(50) TYPE c, "LedgerKey wrk_delim1 TYPE x , name1(80) TYPE c, "AccountName wrk_delim2 TYPE x , kunnr(50) TYPE c, "AccountReference wrk_delim3 TYPE x , name2(80) TYPE c, "Address1 wrk_delim4 TYPE x , stras(80) TYPE c, " Address2 wrk_delim5 TYPE x , ort01(50) TYPE c, " Town wrk_delim6 TYPE x , regio(50) TYPE c, " County / State wrk_delim7 TYPE x , pstlz(10) TYPE c, "Post Code / ZIP wrk_delim8 TYPE x , land1(2) TYPE c, "Country wrk_delim9 TYPE x , waers(3) TYPE c, "AccountCurrencyCode

Page 416: ABAP Tutorials

wrk_delim10 TYPE x , telf1(20) TYPE c, "ContactTelephone END OF st_cus .DATA: wrk_file TYPE char200.DATA: it_customer TYPE STANDARD TABLE OF st_customer, wa_customer LIKE LINE OF it_customer.DATA: it_dat TYPE STANDARD TABLE OF st_cus, wa_dat LIKE LINE OF it_dat.SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-001.SELECT-OPTIONS:cust_no FOR kna1-kunnr,"customer no com_code FOR knb1-bukrs,"company code country FOR kna1-land1, "country creat_on FOR kna1-erdat default sy-datum. "created or changed onSELECTION-SCREEN END OF BLOCK b2.START-OF-SELECTION. IF creat_on-high IS INITIAL. creat_on-high = creat_on-low. ENDIF. CONCATENATE sy-mandt '_1_' creat_on-low '_' creat_on-high '_Cust.txt' INTO wrk_file. PERFORM customer_data_select. "Customer Data File PERFORM build_template_data. PERFORM ftp_file_customer.*&---------------------------------------------------------------------**& Form CUSTOMER_DATA_SELECT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** --> p1 text* <-- p2 text*----------------------------------------------------------------------*FORM customer_data_select . SELECT a~name1 a~name2 a~kunnr a~stras a~ort01 a~regio a~pstlz a~land1 a~telf1 "Details of the Customer based on KNA1. FROM kna1 AS a INNER JOIN knb1 AS b ON a~kunnr = b~kunnr INTO CORRESPONDING FIELDS OF TABLE it_customer WHERE a~kunnr IN cust_no AND ( ( a~erdat IN creat_on OR a~updat IN creat_on ) OR ( b~erdat IN creat_on OR b~updat IN creat_on ) ) AND a~land1 IN country AND b~bukrs IN com_code. IF sy-subrc = 0. LOOP AT it_customer INTO wa_customer. SELECT SINGLE waers FROM knvv INTO wa_customer-waers WHERE kunnr = wa_customer-kunnr.. wa_customer-ledgerkey = '12345'. MODIFY it_customer FROM wa_customer. ENDLOOP. ENDIF.ENDFORM. " CUSTOMER_DATA_SELECT*&---------------------------------------------------------------------**& Form BUILD_TEMPLATE_DATA*&---------------------------------------------------------------------** text

Page 417: ABAP Tutorials

*----------------------------------------------------------------------** --> p1 text* <-- p2 text*----------------------------------------------------------------------*FORM build_template_data . LOOP AT it_customer INTO wa_customer. MOVE-CORRESPONDING wa_customer TO wa_dat. wa_dat-wrk_delim1 = '09'. "for adding tab after each field wa_dat-wrk_delim2 = '09'. wa_dat-wrk_delim3 = '09'. wa_dat-wrk_delim4 = '09'. wa_dat-wrk_delim5 = '09'. wa_dat-wrk_delim6 = '09'. wa_dat-wrk_delim7 = '09'. wa_dat-wrk_delim8 = '09'. wa_dat-wrk_delim9 = '09'. wa_dat-wrk_delim10 = '09'. APPEND wa_dat TO it_dat. ENDLOOP.ENDFORM. " BUILD_TEMPLATE_DATA*&---------------------------------------------------------------------**& Form FTP_FILE_CUSTOMER*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** --> p1 text* <-- p2 text*----------------------------------------------------------------------*FORM ftp_file_customer . DATA: l_user(30) TYPE c VALUE 'ZTEST', "user name of ftp server l_pwd(30) TYPE c VALUE '1234', "password of ftp server l_host(64) TYPE c VALUE '111.2.1.198', "ip address of FTP server l_dest LIKE rfcdes-rfcdest VALUE 'SAPFTPA'."Background RFC destination DATA: w_hdl TYPE i, c_key TYPE i VALUE 26101957, l_slen TYPE i.*HTTP_SCRAMBLE: used to scramble the password provided in a format recognized by SAP. SET EXTENDED CHECK OFF. l_slen = STRLEN( l_pwd ). CALL FUNCTION 'HTTP_SCRAMBLE' EXPORTING SOURCE = l_pwd sourcelen = l_slen key = c_key IMPORTING destination = l_pwd.* To Connect to the Server using FTP CALL FUNCTION 'FTP_CONNECT' EXPORTING user = l_user password = l_pwd host = l_host rfc_destination = l_dest IMPORTING handle = w_hdl

Page 418: ABAP Tutorials

EXCEPTIONS OTHERS = 1. .*FTP_R3_TO_SERVER:used to transfer the internal table data as a file to other system in the character mode. CALL FUNCTION 'FTP_R3_TO_SERVER' EXPORTING handle = w_hdl fname = wrk_file "file path of destination system character_mode = 'X' TABLES text = it_dat EXCEPTIONS tcpip_error = 1 command_error = 2 data_error = 3 OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 RAISING invalid_output_file. ENDIF.*FTP_DISCONNECT: This is used to disconnect the connection between SAP and other system.* To disconnect the FTP CALL FUNCTION 'FTP_DISCONNECT' EXPORTING handle = w_hdl.*RFC_CONNECTION_CLOSE:This is used to disconnect the RFC connection between SAP and other system. CALL FUNCTION 'RFC_CONNECTION_CLOSE' EXPORTING destination = l_dest EXCEPTIONS OTHERS = 1.ENDFORM. " FTP_FILE_CUSTOMER

On running this report in background a file will be created in ftp server location.

Converting an XML file with many hierarchy levels to ABAP format

By Subhashini Kolluri, IBM India

This example shows how we can convert an XML file with many hierarchy levels to ABAP format.  

Copy and paste the following code in notepad and save it as test.xml file.

Save the XML file which in desktop or some other path  

<?xml version="1.0" encoding="UTF-8" ?> <ZEU_MATMAS03> <IDOC BEGIN="1"> <EDI_DC40 SEGMENT="1"> <DOCNUM>0000000000038491</DOCNUM>

Page 419: ABAP Tutorials

<MESTYP>ZEU_MATMAS</MESTYP> </EDI_DC40> <E1MARAM SEGMENT="1"> <MSGFN>004</MSGFN> <MATNR>000000000000010003</MATNR> <E1MAKTM SEGMENT="1"> <MSGFN>005</MSGFN> <SPRAS>E</SPRAS> <MAKTX>promo pack normal</MAKTX> <SPRAS_ISO>EN</SPRAS_ISO> </E1MAKTM> </E1MARAM> </IDOC></ZEU_MATMAS03>

Here we can see that the root node is ZEU_MATMAS03 which is the main structure containing all other structures.

It contains IDOC structure which in turn contains E1MARAM and EDI_DC40 structures within.

EDI_DC40 contains DOCNUM and MESTYP fields.

E1MARAM contains E1MAKTM structure and MSGFN and MATNR fields.  

In SAP we have to create corresponding structures to store this data from XML to ABAP.The main structure contains many deep structures.  

So in ABAP dictionary we first create the structure ZIDOC_TEST which contains Structures ZEDIDC40 and Z1EMARAM_TEST1.  

 

ZIDOC_TEST structure contains ZE1MARAM_TEST1 and ZEDIDC40 structures within.  

ZEDIDC40 contains DOCNUM and MESTYP fields.  

ZE1MARAM_TEST1 contains E1MAKTM structure and MSGFN and MATNR fields.

The structures Z1EMARAM_TEST1 and ZEDIDC40 are also created as shown in the below slides.  

This is the structure of ZEDIDC40 - Control record with fields DOCNUM and MESTYP..

Page 420: ABAP Tutorials

 

The structure ZE1MARAM_TEST1 contains the following fields MSGFN and MATNR.Also a deep structure E1MAKTM.  

 

E1MAKTM Structure is a standard dictionary structure we are using directly with the fields MSGFN,SPRAS,MAKTX and SPRAS_ISO.

 

The following ABAP program converts the given input XML file to ABAP format.  

TYPE-POOLS abap.

Page 421: ABAP Tutorials

*Input file contents as string.XML file path where we saved the file. *Here it is saved in desktop.

*Input file with path as constantCONSTANTS gs_file TYPE string VALUE 'C:\Documents and Settings\Administrator\Desktop\test1.xml'.

*This is the structure type for the data from the XML fileTYPES: BEGIN OF ts_zeu_matmas03,         idoc TYPE ZIDOC_TEST, “ZIDOC_TEST structure we created in SE11       END OF ts_zeu_matmas03.

* Table for storing the XML content from fileDATA: gt_itab       TYPE STANDARD TABLE OF char2048.

* Table and work areas for the data from the XML fileDATA: gt_zeu_matmas03     TYPE STANDARD TABLE OF ts_zeu_matmas03,      gs_zeu_matmas03     TYPE ts_zeu_matmas03.

* Result table that contains references* of the internal tables to be filledDATA: gt_result_xml TYPE abap_trans_resbind_tab,      gs_result_xml TYPE abap_trans_resbind.

* For error handlingDATA: gs_rif_ex     TYPE REF TO cx_root,      gs_var_text   TYPE string.

* Get the XML file from your clientCALL METHOD cl_gui_frontend_services=>gui_upload  EXPORTING    filename                = gs_file  CHANGING    data_tab                = gt_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    not_supported_by_gui    = 17    error_no_gui            = 18    OTHERS                  = 19.

IF sy-subrc <> 0.  MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno          WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

Page 422: ABAP Tutorials

ENDIF.

* Fill the result table with a reference to the data table.* Within the XSLT style sheet, the data table can be accessed with* "IDOC_GET".

GET REFERENCE OF gt_zeu_matmas03 INTO gs_result_xml-value.gs_result_xml-name = 'IDOC_GET'.APPEND gs_result_xml TO gt_result_xml.

* Perform the XSLT stylesheet

TRY.

    CALL TRANSFORMATION z_xml_idoc    SOURCE XML gt_itab    RESULT (gt_result_xml).

In this part of the code  

Z_XML_IDOC should be created in XSLT Editor and write code for that as follows:-

We can go there by double clicking on Z_XML_IDOC.Create it and after copying this code activate it.  

XSLT is a language is used to convert XML from one format to another format.  

Copy paste the following code in XSLT editor :-  

Some rules which were applied for conversion to XSLT are:-

IDOC_GET is used to get the data from IDOC.In the XML file the main node is IDOC which has E1MARAM and EDIDC_40 which in turn contains MSGFN,MATNR and E1MAKTM and EDIDC_40 contains MSGFN and DOCNUM respectively.  

The same type of structure which is used in our program needs to be filled.In our program EDIDC_40 is used as ZEDIDC40 and E1MARAM is used as ZE1MARAM_TEST1.  

The basic template is already filled when we enter the XSLT editor.

We use IDOC_GET to use the IDOC data.We should use the tags to be filled in the hierarchy structure as we declared it in the program.To use the values we need to use the structures in the XML file.Use the corresponding path to access the values.  

After transformation the gt_zeu_matmas03 is filled which can be used for displaying.  

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output encoding="iso-8859-1" indent="yes" method="xml" version="1.0"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <IDOC_GET> <xsl:apply-templates select="//IDOC"/>

Page 423: ABAP Tutorials

</IDOC_GET> </asx:values> </asx:abap> </xsl:template> <xsl:template match="IDOC"> <item> <IDOC> <ZEDIDC40> <MESTYP><xsl:value-of select="EDI_DC40/MESTYP"/></MESTYP> <DOCNUM><xsl:value-of select="EDI_DC40/DOCNUM"/></DOCNUM> </ZEDIDC40> <ZE1MARAM_TEST1> <MSGFN><xsl:value-of select="E1MARAM/MSGFN"/></MSGFN> <MATNR><xsl:value-of select="E1MARAM/MATNR"/></MATNR> <E1MAKTM> <MSGFN><xsl:value-of select="E1MARAM/E1MAKTM/MSGFN"/></MSGFN> <SPRAS><xsl:value-of select="E1MARAM/E1MAKTM/SPRAS"/></SPRAS> <MAKTX><xsl:value-of select="E1MARAM/E1MAKTM/MAKTX"/></MAKTX> <SPRAS_ISO><xsl:value-of select="E1MARAM/E1MAKTM/SPRAS_ISO"/></SPRAS_ISO> </E1MAKTM> </ZE1MARAM_TEST1> </IDOC> </item> </xsl:template></xsl:transform> 

 

*Come back to ABAP editor and copy this code for error handling.

Page 424: ABAP Tutorials

  CATCH cx_root INTO gs_rif_ex.

    gs_var_text = gs_rif_ex->get_text( ).    MESSAGE gs_var_text TYPE 'E'.

ENDTRY.  

*Display the file contents on screen.IF sy-subrc = 0.  LOOP at gt_zeu_matmas03 INTO gs_zeu_matmas03.    WRITE:  gs_zeu_matmas03-idoc-zedidc40-docnum, “document no          / gs_zeu_matmas03-idoc-zedidc40-mestyp, “message type          / gs_zeu_matmas03-idoc-ze1maram_test1-msgfn,”message function          / gs_zeu_matmas03-idoc-ze1maram_test1-matnr,”material no

*all fields of E1MAKTM segment          / gs_zeu_matmas03-idoc-ze1maram_test1-e1maktm-msgfn,          / gs_zeu_matmas03-idoc-ze1maram_test1-e1maktm-spras,          / gs_zeu_matmas03-idoc-ze1maram_test1-e1maktm-maktx,          / gs_zeu_matmas03-idoc-ze1maram_test1-e1maktm-spras_iso.  ENDLOOP.ENDIF.  

We can see the values filled in the heirarchy structure of IDOC as follows:-

 

Execute the ABAP program and we get the file contents displayed as below.So we have converted the given XML File to a structure and display the contents.

Page 425: ABAP Tutorials

Final output of the program is:-

Dialog Programming

Table Control using Wizard in Module Pool Programming

By Venkatraman N, IBM

Pre-requisites:  

The readers must be able to create a module pool program and they should be familiar with screen programming.  

Purpose of this tutorial:  

This is to demonstrate the step by step tutorial of how to make use of table control with wizard, where the developer’s effort to write code with table control without wizard is avoided.  

Introduction:  

Table control with wizard is the control provided by SAP, in which the users are not needed to code separately for table control operations. It generates automatically system generated code for the following table control operations.  

1. Insertion 2. Deletion

3. Scrolling

4. First

5. Last

6. Next

7. Previous

Page 426: ABAP Tutorials

8. Select

9. Select all

10. Deselect

11. Deselect all  

Step 1: Create an internal table and work area, which we are going to deploy in table control.  

 

Step 2: Create a screen called ‘9000’.  

 

Input the screen number as 9000.  

 

Page 427: ABAP Tutorials

Fill up the screen attribute values.

Step 3: Go to the layout of the screen, where you can find the table control with wizard. Drag and drop the table control with wizard to the layout of the screen.  

 

Once you drag and drop the control a popup will appear.  

Page 428: ABAP Tutorials

 

Press Continue. In the next screen enter the table control name as ‘TBC_9000’ or your own name.  

In the next screen you input the internal table and work area which has been created earlier.  

Note: Before it is done, you must activate the page, in which you have declared the internal table and work area. Then only this table control screen will take its properties.

Page 429: ABAP Tutorials

The next screen will automatically retrieve the fields available in the internal table and show. We have to select those fields, which and all should be displayed in table control.

If you have declared any character field for table control line selection, that should not be selected in this screen.  

Select the input/output attributes as ‘Input control’ and give the field for selection of table control rows. Select the multiple line selection.  

Page 430: ABAP Tutorials

Click on Continue. The table control with auto generated code will automatically be created.  

Page 431: ABAP Tutorials

This will automatically create PBO & PAI modules for table control operations.  

Page 432: ABAP Tutorials

 

Step 4: For testing this tutorial, write a simple query to populate the internal table of table control and test the input controls associated with it.  

 

The expected output will be like  

Page 433: ABAP Tutorials

 

Summary :  

As a result of this tutorial, the user will be able to  

1. Use table control with wizard in module pool programming and 2. Create table control operations with system generated code.

3. Splitter Controls and Graphs

4. By Swarna S, Tata Consultancy Services

Page 434: ABAP Tutorials

5.

6. *&-----------------------------------------------------------------7. *& Report Z_SPLIT_GRAPH8. *& Author: Swarna.S.(Tata Consultancy Services)9. * Published at SAPTechnical.COM10. *&-----------------------------------------------------------------11. *& AS : Sample code for creating a splitter screen and graph.12. *& The screen is divided into two by splitter control and can be

resized13. *& Two graphs are drawn on the two splitter containers.14. *& The sample code also describes creating graphs in ABAP.15. *&-----------------------------------------------------------------16. REPORT z_split_graph .17. *type pool declarations for graphical frame work18. TYPE-POOLS: GFW.19. *OK code declaration20. DATA: OK_CODE TYPE SY-UCOMM.21. *structure declaration for graph 1 values22. types : begin of ty_grvalwa1.23. include structure gprval.24. types : end of ty_grvalwa1.25. *structure declaration for graph 1 column names26. types : begin of ty_col1_texts.27. include structure gprtxt.28. types : end of ty_col1_texts.29. *data declarations for graph 1

Page 435: ABAP Tutorials

30. data : grval1 TYPE standard TABLE OF ty_grvalwa1,31. grvalwa1 type ty_grvalwa1,32. COL1_TEXTS TYPE standard TABLE OF ty_col1_texts,33. col1_wa type ty_col1_texts.34. *structure declaration for graph 2 values35. types : begin of ty_grvalwa2.36. include structure gprval.37. types : end of ty_grvalwa2.38. *structure declaration for graph 2 column names39. types : begin of ty_col2_texts.40. include structure gprtxt.41. types : end of ty_col2_texts.42. *data declarations for graph243. data : grval2 TYPE standard TABLE OF ty_grvalwa2,44. grvalwa2 type ty_grvalwa2,45. COL2_TEXTS TYPE standard TABLE OF ty_col2_texts,46. col2_wa type ty_col2_texts.47. *data declarations for containers,splitters,and custom container48. data :CUSTOM_CONTAINER TYPE REF TO CL_GUI_CUSTOM_CONTAINER,49. SPLITTER TYPE REF TO CL_GUI_SPLITTER_CONTAINER,50. CONT1 type ref to cl_gui_container,51. CONT2 type ref to cl_gui_container.52. *Initialisation event53. INITIALIZATION.54. *start of selection event55. START-OF-SELECTION.56. *Call screen for the container for output57. CALL SCREEN 600.58. *PBO module for the output display59. *&----------------------------------------------------------------*60. *& Module PBO_0600 OUTPUT61. *&----------------------------------------------------------------*62. MODULE PBO_0600 OUTPUT.63. *Setting the GUI status for the splitter screen(EXIT button)64. SET PF-STATUS 'SPLITGRAPH'.65. *Setting the title for the splitter control66. SET titlebar 'SPLITGRAPH'.67. *Creating custom container68. CREATE OBJECT CUSTOM_CONTAINER69. EXPORTING70. CONTAINER_NAME = 'CONTAINER'.71. *creating the splitter control72. CREATE OBJECT splitter73. EXPORTING74. PARENT = CUSTOM_CONTAINER75. ROWS = 176. COLUMNS = 277. ALIGN = 15.78. *calling the container method of the splitter class79. *for the first graphic80. CALL METHOD SPLITTER->GET_CONTAINER81. EXPORTING82. ROW = 183. COLUMN = 184. RECEIVING85. CONTAINER = CONT1.86. *calling the container method of the splitter class

Page 436: ABAP Tutorials

87. *for the second graphic88. CALL METHOD SPLITTER->GET_CONTAINER89. EXPORTING90. ROW = 191. COLUMN = 292. RECEIVING93. CONTAINER = CONT2.94. *Graphic 1 display95. REFRESH : grval1,Col1_texts.96. grvalwa1-rowtxt = 'Rice'.97. grvalwa1-val1 = 1100.98. grvalwa1-VAL2 = 4500.99. APPEND grvalwa1 to grval1.100. grvalwa1-ROWTXT = 'Coffee'.101. grvalwa1-VAL1 = 2000.102. grvalwa1-VAL2 = 6000.103. APPEND grvalwa1 to grval1.104. grvalwa1-ROWTXT = 'Tea'.105. grvalwa1-VAL1 = 3500.106. grvalwa1-VAL2 = 7000.107. APPEND grvalwa1 to grval1.108. grvalwa1-ROWTXT = 'Cereals'.109. grvalwa1-VAL1 = 6000.110. grvalwa1-val2 = 7000.111. APPEND grvalwa1 to grval1.112. col1_wa-coltxt = '2005'.113. APPEND col1_wa to COL1_TEXTS.114. COL1_wa-COLTXT = '2006'.115. APPEND col1_wa to COL1_TEXTS.116. *Function module to display graph (Graph 1)117. CALL FUNCTION 'GFW_PRES_SHOW_MULT'118. EXPORTING119. PARENT = CONT1120. PRESENTATION_TYPE = GFW_PRESTYPE_LINES121. SHOW = GFW_FALSE122. TABLES123. VALUES = grval1124. COLUMN_TEXTS = COL1_TEXTS125. EXCEPTIONS126. ERROR_OCCURRED = 1.127. *Graphic 2 display128. REFRESH : grval2,col2_texts.129. grvalwa2-ROWTXT = 'Wheat'.130. grvalwa2-VAL1 = 3000.131. grvalwa2-VAL2 = 5500.132. APPEND grvalwa2 to grval2.133. grvalwa2-ROWTXT = 'Corn'.134. grvalwa2-VAL1 = 2700.135. grvalwa2-VAL2 = 8000.136. APPEND grvalwa2 to grval2.137. grvalwa2-ROWTXT = 'Maize'.138. grvalwa2-VAL1 = 3250.139. grvalwa2-VAL2 = 5000.140. APPEND grvalwa2 to grval2.141. grvalwa2-ROWTXT = 'Barley'.142. grvalwa2-VAL1 = 6500.143. grvalwa2-VAL2 = 9000.

Page 437: ABAP Tutorials

144. APPEND grvalwa2 to grval2.145. COL2_wa-COLTXT = '2005'.146. APPEND col2_wa to COL2_TEXTS.147. COL2_wa-COLTXT = '2006'.148. APPEND col2_wa to COL2_TEXTS.149. *Function module to display Graph 2150. CALL FUNCTION 'GFW_PRES_SHOW_MULT'151. EXPORTING152. PARENT = CONT2153. PRESENTATION_TYPE = GFW_PRESTYPE_LINES154. SHOW = GFW_TRUE155. TABLES156. VALUES = grval2157. COLUMN_TEXTS = COL2_TEXTS158. EXCEPTIONS159. ERROR_OCCURRED = 1.160. ENDMODULE. " PBO_0600 OUTPUT161. *PAI module : Based on user input,action is performed162. *EXIT called to leave program when user clicks it163. *&----------------------------------------------------------------*164. *& Module PAI_0600 INPUT165. *&----------------------------------------------------------------*166. MODULE PAI_0600 INPUT.167. OK_CODE = SY-UCOMM.168. IF OK_CODE EQ 'EXIT'.169. LEAVE PROGRAM.170. ENDIF.171. ENDMODULE. " PAI_0600 INPUT

172. Screen shots of the output.

Page 438: ABAP Tutorials

173.

174. Screen shot of the splitter containers can be resized as shown below:

Page 439: ABAP Tutorials

175.

Page 440: ABAP Tutorials

Text Edit control - Usage and Demo

By Saikumar Bonakurthi, Enteg Infotech

As an ABAP developer, we all know that if we drop a field of type char and length 255 in to the conventional screen painter it will be displayed in a single line. It will not be good interface unless we provide a multi-line input field in the screen. This can be achieved by text editor control. 

The following is our attempt to explain how to implement the text editor control on classic dynpros. 

Text editor is displayed on screen using custom control. So we need a container for the custom control. And text editor control is implemented using class CL_GUI_TEXTEDIT. 

Our declaration part contains

      DATA: LINE_LENGTH      TYPE I VALUE 254,      EDITOR_CONTAINER TYPE REF TO CL_GUI_CUSTOM_CONTAINER,      TEXT_EDITOR      TYPE REF TO CL_GUI_TEXTEDIT,      TEXT             TYPE STRING. 

 Then call the screen (can be any number) 

Page 441: ABAP Tutorials

 START-OF-SELECTION.  CALL SCREEN '100'. 

 Go to screen 100 by double clicking on '100'.

Create a custom control on screen with name TEXTEDIT. 

 

Uncomment both PBO and PAI modules in flow logic screen 

 PROCESS BEFORE OUTPUT. MODULE STATUS_0100.*PROCESS AFTER INPUT. MODULE USER_COMMAND_0100. 

 Define and implement both the modules in the main program itself. 

In PBO create object container EDITOR_CONTAINER. Then create text editor object by exporting the container EDITOR_CONTAINER. 

     CREATE OBJECT EDITOR_CONTAINER      EXPORTING        CONTAINER_NAME              = 'TEXTEDITOR'      EXCEPTIONS        CNTL_ERROR                  = 1        CNTL_SYSTEM_ERROR           = 2        CREATE_ERROR                = 3        LIFETIME_ERROR              = 4        LIFETIME_DYNPRO_DYNPRO_LINK = 5.

    CREATE OBJECT TEXT_EDITOR

Page 442: ABAP Tutorials

      EXPORTING        PARENT           = EDITOR_CONTAINER        WORDWRAP_MODE    = CL_GUI_TEXTEDIT=>WORDWRAP_AT_FIXED_POSITION        WORDWRAP_POSITION          = LINE_LENGTH        WORDWRAP_TO_LINEBREAK_MODE = CL_GUI_TEXTEDIT=>TRUE. 

 You can hide the toolbar and as well as status bar for the text editor control. 

     CALL METHOD TEXT_EDITOR->SET_TOOLBAR_MODE      EXPORTING        TOOLBAR_MODE = CL_GUI_TEXTEDIT=>FALSE.

    CALL METHOD TEXT_EDITOR->SET_STATUSBAR_MODE      EXPORTING        STATUSBAR_MODE = CL_GUI_TEXTEDIT=>FALSE. 

 Define and create a GUI Status in the PBO. 

   SET PF-STATUS 'STATUS_0100'. 

 Very minimum set of tool bar buttons defined in this example 

 

In PAI of the screen 100, handle the save and other user commands. 

   CASE SY-UCOMM.    WHEN 'EXIT'.      LEAVE PROGRAM.    WHEN 'SAVE'.      CALL METHOD TEXT_EDITOR->GET_TEXTSTREAM*         EXPORTING*             ONLY_WHEN_MODIFIED     = CL_GUI_TEXTEDIT=>TRUE          IMPORTING              TEXT                   = TEXT*             IS_MODIFIED            =          EXCEPTIONS              ERROR_CNTL_CALL_METHOD = 1              NOT_SUPPORTED_BY_GUI   = 2              OTHERS                 = 3.

      IF SY-SUBRC <> 0.

Page 443: ABAP Tutorials

        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO                   WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.      ENDIF.

      CALL METHOD CL_GUI_CFW=>FLUSH        EXCEPTIONS          CNTL_SYSTEM_ERROR = 1          CNTL_ERROR        = 2          OTHERS            = 3.      MESSAGE TEXT TYPE 'I'.  ENDCASE. 

 To read the text that is typed in the editor we need to call the method GET_TEXTSTREAM of the editor instance. 

We are just displaying the text typed in the editor in an informative message; the same can be inserted / updated into a database table also. 

The complete coding of the executable program is given below.. 

REPORT  ZTEXT_EDITOR.

DATA: LINE_LENGTH      TYPE I VALUE 254,      EDITOR_CONTAINER TYPE REF TO CL_GUI_CUSTOM_CONTAINER,      TEXT_EDITOR      TYPE REF TO CL_GUI_TEXTEDIT,      TEXT             TYPE STRING.

START-OF-SELECTION.  CALL SCREEN '100'.

**&---------------------------------------------------------------------***&      Module  STATUS_0100  OUTPUT**&---------------------------------------------------------------------***       text**----------------------------------------------------------------------*MODULE STATUS_0100 OUTPUT.

  SET PF-STATUS 'STATUS_0100'.

  IF TEXT_EDITOR IS INITIAL.

    CREATE OBJECT EDITOR_CONTAINER      EXPORTING        CONTAINER_NAME              = 'TEXTEDITOR'      EXCEPTIONS        CNTL_ERROR                  = 1        CNTL_SYSTEM_ERROR           = 2        CREATE_ERROR                = 3        LIFETIME_ERROR              = 4        LIFETIME_DYNPRO_DYNPRO_LINK = 5.

    CREATE OBJECT TEXT_EDITOR      EXPORTING        PARENT                     = EDITOR_CONTAINER

Page 444: ABAP Tutorials

        WORDWRAP_MODE              = CL_GUI_TEXTEDIT=>WORDWRAP_AT_FIXED_POSITION        WORDWRAP_POSITION          = LINE_LENGTH        WORDWRAP_TO_LINEBREAK_MODE = CL_GUI_TEXTEDIT=>TRUE.

*3)HIDE TOOLBAR AND STATUSBAR

    CALL METHOD TEXT_EDITOR->SET_TOOLBAR_MODE      EXPORTING        TOOLBAR_MODE = CL_GUI_TEXTEDIT=>FALSE.

    CALL METHOD TEXT_EDITOR->SET_STATUSBAR_MODE      EXPORTING        STATUSBAR_MODE = CL_GUI_TEXTEDIT=>FALSE.

  ENDIF.ENDMODULE.                 " STATUS_0100  OUTPUT*&---------------------------------------------------------------------**&      Module  USER_COMMAND_0100  INPUT*&---------------------------------------------------------------------**       text*----------------------------------------------------------------------*MODULE USER_COMMAND_0100 INPUT.  CASE SY-UCOMM.    WHEN 'EXIT'.      LEAVE PROGRAM.    WHEN 'SAVE'.      CALL METHOD TEXT_EDITOR->GET_TEXTSTREAM*         EXPORTING*             ONLY_WHEN_MODIFIED     = CL_GUI_TEXTEDIT=>TRUE          IMPORTING              TEXT                   = TEXT*             IS_MODIFIED            =          EXCEPTIONS              ERROR_CNTL_CALL_METHOD = 1              NOT_SUPPORTED_BY_GUI   = 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.

      CALL METHOD CL_GUI_CFW=>FLUSH        EXCEPTIONS          CNTL_SYSTEM_ERROR = 1          CNTL_ERROR        = 2          OTHERS            = 3.      MESSAGE TEXT TYPE 'I'.  ENDCASE.ENDMODULE.                 " USER_COMMAND_0100  INPUT 

 The final Screen shot of the editor: 

Page 445: ABAP Tutorials

Display images on the screen

By Aditya Niyogi, L&T Infotech

Step 1: Upload picture into SAP using the transaction SE78. Test picture. 

 

Page 446: ABAP Tutorials

Step 2: Create a custom screen section in the screen.

 

Step 3: In the PBO module of the screen, attach the following code. Please note that the object name is ‘winny’, please pass your own object name to the method: *&---------------------------------------------------------------------**& Module STATUS_9000 OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*MODULE STATUS_9000 OUTPUT. DATA: W_LINES TYPE I. TYPES PICT_LINE(256) TYPE C. DATA : CONTAINER TYPE REF TO CL_GUI_CUSTOM_CONTAINER, EDITOR TYPE REF TO CL_GUI_TEXTEDIT, PICTURE TYPE REF TO CL_GUI_PICTURE, PICT_TAB TYPE TABLE OF PICT_LINE, URL(255) TYPE C. DATA: GRAPHIC_URL(255). DATA: BEGIN OF GRAPHIC_TABLE OCCURS 0, LINE(255) TYPE X, END OF GRAPHIC_TABLE. DATA: L_GRAPHIC_CONV TYPE I. DATA: L_GRAPHIC_OFFS TYPE I. DATA: GRAPHIC_SIZE TYPE I. DATA: L_GRAPHIC_XSTR TYPE XSTRING.

Page 447: ABAP Tutorials

. CALL METHOD CL_GUI_CFW=>FLUSH. CREATE OBJECT: CONTAINER EXPORTING CONTAINER_NAME = 'PICTURE_CONTAINER', PICTURE EXPORTING PARENT = CONTAINER. CALL METHOD CL_SSF_XSF_UTILITIES=>GET_BDS_GRAPHIC_AS_BMP EXPORTING P_OBJECT = 'GRAPHICS' P_NAME = 'WINNY' P_ID = 'BMAP' P_BTYPE = 'BCOL' RECEIVING P_BMP = L_GRAPHIC_XSTR* EXCEPTIONS* NOT_FOUND = 1* INTERNAL_ERROR = 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. GRAPHIC_SIZE = XSTRLEN( L_GRAPHIC_XSTR ). L_GRAPHIC_CONV = GRAPHIC_SIZE. L_GRAPHIC_OFFS = 0. WHILE L_GRAPHIC_CONV > 255. GRAPHIC_TABLE-LINE = L_GRAPHIC_XSTR+L_GRAPHIC_OFFS(255). APPEND GRAPHIC_TABLE. L_GRAPHIC_OFFS = L_GRAPHIC_OFFS + 255. L_GRAPHIC_CONV = L_GRAPHIC_CONV - 255. ENDWHILE. GRAPHIC_TABLE-LINE = L_GRAPHIC_XSTR+L_GRAPHIC_OFFS(L_GRAPHIC_CONV). APPEND GRAPHIC_TABLE. CALL FUNCTION 'DP_CREATE_URL' EXPORTING TYPE = 'IMAGE' SUBTYPE = 'X-UNKNOWN' SIZE = GRAPHIC_SIZE LIFETIME = 'T' TABLES DATA = GRAPHIC_TABLE CHANGING URL = URL. CALL METHOD PICTURE->LOAD_PICTURE_FROM_URL EXPORTING URL = URL. CALL METHOD PICTURE->SET_DISPLAY_MODE EXPORTING DISPLAY_MODE = PICTURE->DISPLAY_MODE_FIT_CENTER.ENDMODULE. " STATUS_9000 OUTPUT

Output: 

Page 448: ABAP Tutorials

Working with Screen Painter

By Vikram Chellappa, Mouri Tech Solutions

SCREEN PAINTER:-

 Screen painter is a tool in ABAP dev workbench used to create the screens using the

T-code SE51. In the screen painter, you can define the following interface elements with their associated attributes.1. Input/Output Fields2. Field Names3. Checkboxes4. Radio Buttons5. Group Boxes6. Sub screens.7. Pushbuttons with No Fixed Position

and others 

STEP-BY-STEP DEMO FOR SCREEN PAINTER. 

Page 449: ABAP Tutorials

Create a Z program in SE38. 

 

Click on Save. We will write the code later in this. 

Go to transaction SE51. 

 

Enter the created program name and screen number. 

Page 450: ABAP Tutorials

 Enter the short description and click on save. 

 

Click on flowlogic tab. 

Page 451: ABAP Tutorials

 

Uncomment the statement “ MODULE STATUS_0100 “. 

 

Double click the “ status_0100.”

The below screen will be displayed,

Click on yes.

Page 452: ABAP Tutorials

 

Following pop-up screen appears. Select the “zdemo_screen_painter” “main program” and click on continue.

Click on yes.

Page 453: ABAP Tutorials

 

Screen would be displayed as follows: 

 

Now come back to the transaction SE51. Select flow logic. Click in layout. 

Page 454: ABAP Tutorials

 

Screen painter window will be displayed like this. Here we will design the required screen fields.

Click on the middle icon dictionary / program fields window. Or F6. 

 

Following screen appears: 

Page 455: ABAP Tutorials

 Enter the table name in the table field name.

Click on get from dictionary. 

 

Select the required fields from MARA table from dictionary. Click on OK or continue. 

Page 456: ABAP Tutorials

 

 

After placing the required fields, you can view the below screen. 

Page 457: ABAP Tutorials

 

Create the push button from the toolbox. 

 

Select the pushbutton, drag and drop the button onto the screen. 

Page 458: ABAP Tutorials

Create the other required buttons in the same procedure mentioned above and assign the name, text, and function code for each one. 

 

After creating the screen click on save check and activate. 

press flow logic button. . 

Page 459: ABAP Tutorials

 

Click on tab Element List enter OK_CODE. 

 

Paste the below Code in created z program created earlier: 

*&-------------------------------------------------------------------**& Report ZDEMO_SCREEN_PAINTER*&*&-------------------------------------------------------------------**& Demo for Screen Painter.*& By Vikramchellappa.*&-------------------------------------------------------------------*REPORT ZDEMO_SCREEN_PAINTER.

Page 460: ABAP Tutorials

******************************************************************* TABLE DECLARATIONS.****************************************************************** TABLES: MARA.******************************************************************* DATA DECLARATIONS.*****************************************************************DATA: MATNR TYPE MARA-MATNR, ERSDA TYPE MARA-ERSDA, ERNAM TYPE MARA-ERNAM, MTART TYPE MARA-MTART, MATKL TYPE MARA-MATKL, DISPLAY TYPE C, SAVE TYPE C, DELETE TYPE C, CLEAR TYPE C, EXIT TYPE C, OK_CODE LIKE SY-UCOMM.****************************************************************** CALLING SCREEN.*****************************************************************CALL SCREEN 100.*&--------------------------------------------------------------**& Module STATUS_0100 OUTPUT*&--------------------------------------------------------------** text*--------------------------------------------------------------*MODULE STATUS_0100 OUTPUT.* SET PF-STATUS 'ZMENU'.* SET TITLEBAR 'ZMENU_PAINTER'.

CASE SY-UCOMM. WHEN 'EXIT'. LEAVE PROGRAM. WHEN 'BACK'. LEAVE PROGRAM. WHEN 'DISPLAY'. SELECT SINGLE ERSDA ERNAM MTART MATKL FROM MARA INTO (MARA-ERSDA, MARA-ERNAM, MARA-MTART, MARA-MATKL) WHERE MATNR = MARA-MATNR. WHEN 'CLEAR'. CLEAR MARA. ENDCASE.ENDMODULE. " STATUS_0100 OUTPUT

Output:-

 Enter Material number On Material Field. Click on Display. 

Page 461: ABAP Tutorials

 

Material Information is displayed as shown below: 

Demo on Tabstrips

By Vikram Chellappa, Mouri Tech Solutions

In this document, we would work on creating a simple screen with a tabstrip on it. 

Go to SE38 T-code.

Create a Z program.

Page 462: ABAP Tutorials

 

Paste the below code in the source code. 

REPORT ZTABSTRIP.************************************************************************* DATA DECLARATIONS *************************************************************************DATA : NUMBER1 TYPE I,NUMBER2 TYPE I,RESULT TYPE I,N1 TYPE I,N2 TYPE I,OK_CODE LIKE SY-UCOMM.CONTROLS TABSTRIP TYPE TABSTRIP.CALL SCREEN 100.CALL SCREEN 110.CALL SCREEN 130.*&---------------------------------------------------------------------**& Module STATUS_0100 OUTPUT*&---------------------------------------------------------------------*text*----------------------------------------------------------------------*MODULE STATUS_0100 OUTPUT.SET PF-STATUS 'BACK'.ENDMODULE. " STATUS_0100 OUTPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0100 INPUT*&---------------------------------------------------------------------*text*----------------------------------------------------------------------*

Page 463: ABAP Tutorials

MODULE USER_COMMAND_0100 INPUT.CASE OK_CODE.WHEN 'TAB1'.TABSTRIP-ACTIVETAB = 'TAB1'.WHEN 'TAB2'.TABSTRIP-ACTIVETAB = 'TAB2'.RESULT = NUMBER1 + NUMBER2.WHEN 'BACK'.LEAVE PROGRAM.ENDCASE.ENDMODULE. " USER_COMMAND_0100 INPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0130 INPUT*&---------------------------------------------------------------------*text*----------------------------------------------------------------------*MODULE USER_COMMAND_0130 INPUT.RESULT = NUMBER1 + NUMBER2.ENDMODULE. " USER_COMMAND_0130 INPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0110 INPUT*&---------------------------------------------------------------------*text*----------------------------------------------------------------------*MODULE USER_COMMAND_0110 INPUT.N1 = NUMBER1.N2 = NUMBER2.ENDMODULE. " USER_COMMAND_0110 INPUT*&---------------------------------------------------------------------**& Module STATUS_0110 OUTPUT*&---------------------------------------------------------------------*text*----------------------------------------------------------------------*MODULE STATUS_0110 OUTPUT.SET PF-STATUS 'xxxxxxxx'.SET TITLEBAR 'xxx'.ENDMODULE. " STATUS_0110 OUTPUT*&---------------------------------------------------------------------**& Module STATUS_0130 OUTPUT*&---------------------------------------------------------------------*text*----------------------------------------------------------------------*MODULE STATUS_0130 OUTPUT.SET PF-STATUS 'xxxxxxxx'.SET TITLEBAR 'xxx'.RESULT = NUMBER1 + NUMBER2.ENDMODULE. " STATUS_0130 OUTPUT

Double Click on "call screen 100". 

Page 464: ABAP Tutorials

Enter Short descriptions.

Come to Flow logic.

Page 465: ABAP Tutorials

 

Click on Layout Button. or Press Ctrl+F7. 

 

Create A Tab Strip and Sub screens and place Sub screen in the appropriate tab strip. 

Page 466: ABAP Tutorials

 

Enter the name of the created TABSTRIP and sub SCREEN. 

 

Enter the required Name, Text, Function code.

Page 467: ABAP Tutorials

 

 

Enter the OK_CODE. 

Page 468: ABAP Tutorials

 

Double click on CALL SCREEN 110.

Give the short description.

Click on SAVE , CHECK, ACTIVATE .

....Previous 

 

Click on Flow logic and come to layout.

Create 2 Input fields. Enter the name description and Format. 

Page 469: ABAP Tutorials

 

Click on SAVE , CHECK, ACTIVATE . 

Double click on CALL SCREEN 130.

Page 470: ABAP Tutorials

Give the SHORT DESCRIPTION. Click on LAYOUT . 

 

Create a text for Result. 

Page 471: ABAP Tutorials

 

Click on SAVE , CHECK, ACTIVATE . 

Come Back To Source Code. 

Click on SAVE , CHECK, ACTIVATE . 

And EXECUTE.  

Result:- 

Page 472: ABAP Tutorials

 

Enter the Value on A = 50 and B = 50. 

 

View the Result on Tab2. 

Page 473: ABAP Tutorials

Demo on using Table Control

By Raghav Vakada, MouriTech Solutions

*&---------------------------------------------------------------------**& Report Z_DB_TABLECONTROL **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*REPORT Z_DB_TABLECONTROL.TABLES: MARA.CONTROLS MATERIAL TYPE TABLEVIEW USING SCREEN 130.TYPES: BEGIN OF ST_MARA, MATNR TYPE MARA-MATNR, ERSDA TYPE MARA-ERSDA, ERNAM TYPE MARA-ERNAM, LAEDA TYPE MARA-LAEDA, END OF ST_MARA.DATA: IT_ST TYPE TABLE OF ST_MARA, WA_ST TYPE ST_MARA, IT_MARA TYPE MARA, WA_MARA TYPE MARA, OK_CODE LIKE SY-UCOMM.CALL SCREEN 130.*&---------------------------------------------------------------------**& Module V1 INPUT*&---------------------------------------------------------------------*

Page 474: ABAP Tutorials

* text*----------------------------------------------------------------------*MODULE V1 INPUT.CASE OK_CODE.WHEN 'SAVE'.WA_ST-MATNR = MARA-MATNR.WA_ST-ERSDA = MARA-ERSDA.WA_ST-ERNAM = MARA-ERNAM.WA_ST-LAEDA = MARA-LAEDA.MOVE-CORRESPONDING WA_ST TO WA_MARA.INSERT INTO MARA VALUES WA_MARA.WHEN 'DELETE'.WA_ST-MATNR = MARA-MATNR.WA_ST-ERSDA = MARA-ERSDA.WA_ST-ERNAM = MARA-ERNAM.WA_ST-LAEDA = MARA-LAEDA.MOVE-CORRESPONDING WA_ST TO WA_MARA.DELETE MARA FROM WA_MARA.WHEN 'MODIFY'.WA_ST-MATNR = MARA-MATNR.WA_ST-ERSDA = MARA-ERSDA.WA_ST-ERNAM = MARA-ERNAM.WA_ST-LAEDA = MARA-LAEDA.MOVE-CORRESPONDING WA_ST TO WA_MARA.MODIFY MARA FROM WA_MARA.ENDCASE.ENDMODULE. " V1 INPUT*&---------------------------------------------------------------------**& Module EXIT INPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*MODULE EXIT INPUT.IF OK_CODE = 'EXIT'.LEAVE PROGRAM.ENDIF.ENDMODULE. " EXIT INPUTCreate a screen by number 130 and provide the following attributes:

Page 475: ABAP Tutorials

 

LAYOUT:

 

ELEMENT LIST:

Page 476: ABAP Tutorials

 

FLOW LOGIC.

 

EXECUTE: 

Page 477: ABAP Tutorials

Display Logo on Screen

By Suresh Kumar Parvathaneni

You can display logo(s) on your screen using the custom control function. A custom control is an area on the screen, created using the screen painter. Custom controls are used to embed controls. Container controls are instances of special global classes from the SAP Control Framework. The global class for custom controls is called CL_GUI_CUSTOM_CONTAINER. To link a custom control to a container control, pass the custom control name to the CONTAINER_NAME parameter of the container control constructor when you instantiate it. The following is a sample program to demonstrate the logo display using the custom control. This program was written in SAP4.6C. Design a screen with the custom control, by name PICTURE_CONTAINER. It has the following flow logic:

PROCESS BEFORE OUTPUT.MODULE STATUS_0100.*PROCESS AFTER INPUT.MODULE CANCEL AT EXIT-COMMAND.

The GUI status SCREEN100 has the functions BACK, EXIT, and CANCEL (all with type E).

Code

REPORT ZSURESH_TEST .

* Type declarations.....................

TYPES pict_line(256) TYPE c. 

* data declarations......................

DATA :init,

Page 478: ABAP Tutorials

      container TYPE REF TO cl_gui_custom_container,

      editor    TYPE REF TO cl_gui_textedit,

      picture   TYPE REF TO cl_gui_picture,

      pict_tab TYPE TABLE OF pict_line,

      url(255) TYPE c. 

CALL SCREEN 100. 

* Dialog modules......................................

MODULE status_0100 OUTPUT.

  SET PF-STATUS 'SCREEN100'.

  IF init is initial.

    init = 'X'. 

    CREATE OBJECT:

           container  EXPORTING container_name = 'PICTURE_CONTAINER',

           picture    EXPORTING parent = container.

  ENDIF. 

  IMPORT pict_tab = pict_tab FROM DATABASE abtree(pi) ID 'ENJOY'.

  CALL FUNCTION 'DP_CREATE_URL'

       EXPORTING

            type    = 'IMAGE'

            subtype = 'GIF'

       TABLES

            data    = pict_tab

       CHANGING

            url     = url. 

  CALL METHOD picture->load_picture_from_url EXPORTING url = url.

  CALL METHOD picture->set_display_mode

Page 479: ABAP Tutorials

       EXPORTING display_mode = picture->display_mode_fit_center.

 ENDMODULE.

 MODULE cancel INPUT.

  LEAVE TO SCREEN 0.

ENDMODULE.

 

BDC Programming

How to do BDC without writing BDC program

By Vikram Chellappa, Mouri Tech Solutions

In this example, I have used the transaction VV31 (Create Output – Condition Records - Billing) to do the BDC. 

1.       Go to Transaction SHDB and click “New Recording” button.

 

2.       The following popup screen gets populated, there you enter the Recording name and transaction for which you wish to do the BDC (In this example it is VV31). Click “Start recording” button.

 

3.       In the Transaction, enter the mandatory field. In this case it is Output type (AUS1). Hit enter key.

Page 480: ABAP Tutorials

 

4.       The following screen appears for more entry. Enter all the mandatory fields and click on save.

 

5.       SAP will give the Recorded program as shown in the following screen shot.

6.       Click the Export button and save the file as word document file into the system.

Page 481: ABAP Tutorials

7.       Now open the newly created word document file.

 

8.       Select/Highlight the first field in the word document for which for which BDC needs to done. (In this case it is output type i.e. AUS1) and go to the menu path Insert à Field

Page 482: ABAP Tutorials

9.       A new screen will get populated and there you select the “Merge Field” option from the list box and enter the Column Name (In this case the 1st column is output_type).

10.   Now you can see in the word document that the highlighted field will get replaced with the column name.

 

 

11.   Similarly you highlight the other fields for which we need to create the BDC and give the unique column names for those fields.

12.   Now you can see that all the required fields have been mapped with unique column names.

Page 483: ABAP Tutorials

13.   Now go the menu path Tools à Letters and Mailings à Mail Merge Wizard.

14.   A mail merge wizard will gets opened in the right hand side.

15.   Now open the excel file where which you have the data to do the BDC for transaction VV31. Check that the column name in the word document is matching with the column name in the Excel file.

Page 484: ABAP Tutorials

16.   Close the Excel File.

17.   Switch to world document and Now Click “Next: Start document” link in the bottom of Mail Merge wizard

18.   Now click on “Next: Select recipients” link

19.   Now click on “Browse” link

20.   It will open the popup for selecting the file (which is having data for BDC).

Page 485: ABAP Tutorials

21.   Press “Open” button

22.   A new popup will get triggered.

23.   Select the work sheet of the Excel file where the actual data present. In this case it is Sheet1$ and Click “OK” button.

24.   A new popup screen would appear with the data. Click “OK” button.

Page 486: ABAP Tutorials

25.   Now click “Next: Write your letter” link.

26.   Click “Next: Preview your letters” link.

27.   Now you can see the first record got merged with the word document.

Page 487: ABAP Tutorials

28.   Click “Next: Complete the merge” link.

29.   Click the “Edit individual letters…” link

30.   A new popup will get triggered, there you select “All” radio button and click “OK” button.

31.   Now you can see the merge has been done in the word document and it will create the BDC program for all the records in the Excel sheet. (In this case we had 10 records in excel sheet, hence the merge has created 10 pages in the word document. One page for each record)

32.   Now Select the entire content in the word document (i.e. all the 10 pages) and copy it in a notepad and save as separate “TXT” file.

33.   Go to the SHDB transaction and select your recording and click “Change” button.

Page 488: ABAP Tutorials

34.   Now use the “Import” button to download the TXT file which we saved in Step # 32.

35.   Once you click the Import button, a popup will come from there you select the file and click “Transfer” button.

36.   It will transfer the entire content to the SHDB. Now Save the changes. Click “Back” button.

37.   Now click the “Session” button, in order to create a new session.

38.   The following popup will get triggered, there you enter the new session name and check the “Keep session” check box and click “Continue” button.

Page 489: ABAP Tutorials

39.   You will get the “Success Message” that “Batch input session ZTST_GOK was created”.

40.   Now go to the Transaction SM35 (Batch Input: Session Overview), there you select your “Session” which you have created in Step # 38 (You can the status of your session will be New) and click “Process” button.

41.   A small popup will get triggered, there you select the “Background” radio button and check the “Extended Log” check box. Click “Process” button.

Page 490: ABAP Tutorials

42.   You will get the success message “1 session(s) transferred to background processing”.

43.   And you can also see the status of your session has been changed from “New” to “In background”.

44.   Click “Log” button, to see the details about the BDC.

45.   You will taken to the another screen, there you can see status of the BDC.

Page 491: ABAP Tutorials

46.   In our case, the status is “Errors”, to know the details further. Select the entry and click “Analyze session”. It will display the status of all the records.

47.   In the above screen shot you can see the first two records were failed and others were processed. The reason for the same is: For the first time when we used SHDB we created the first condition record. Since this record is already there it failed in the second time. The same thing applies to the second failure case.

Creating a simple database table using BDC

By Banupriya R, YASH Technologies

Report ypriyatest.TABLES: bdcdata.DATA:t_bdcdata LIKE STANDARD TABLE OF bdcdata.PARAMETERS : p_table(15) TYPE c.

Page 492: ABAP Tutorials

DATA: MSG LIKE BDCMSGCOLL, T_MSG LIKE TABLE OF MSG, MESSAGE(72) TYPE C.PERFORM PROCESS.*&---------------------------------------------------------------------**& Form fill_screendata*&---------------------------------------------------------------------

form fill_screendata using value(p_0015) value(p_0016). BDCDATA-PROGRAM = P_0015. BDCDATA-DYNPRO = P_0016. BDCDATA-DYNBEGIN = 'X'. APPEND BDCDATA TO T_BDCDATA. CLEAR BDCDATA.endform. " fill_screendata*&---------------------------------------------------------------------**& Form FILL_FIELD_DATA*&---------------------------------------------------------------------

form FILL_FIELD_DATA using value(p_0020) value(p_0021). BDCDATA-FNAM = P_0020. BDCDATA-FVAL = P_0021. APPEND BDCDATA TO T_BDCDATA. CLEAR BDCDATA. endform. " FILL_FIELD_DATA*&---------------------------------------------------------------------**& Form PROCESS*&---------------------------------------------------------------------

form PROCESS .**first screenPERFORM fill_screendata USING 'SAPMSRD0' '0102'.PERFORM FILL_FIELD_DATA USING 'RSRD1-TBMA' 'X'.PERFORM FILL_FIELD_DATA USING 'RSRD1-TBMA_VAL' p_table.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=ADD'.**second screenPERFORM fill_screendata USING 'SAPLSD41' '2200'.PERFORM FILL_FIELD_DATA USING 'DD02D-DDTEXT' 'Bdc Table'.PERFORM FILL_FIELD_DATA USING 'DD02D-CONTFLAG' 'A'.PERFORM FILL_FIELD_DATA USING 'DD02D-MAINFLAG' 'X'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=CHANGE_MAINTFLAG'.PERFORM FILL_FIELD_DATA

Page 493: ABAP Tutorials

USING 'BDC_OKCODE' '/00'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=DEF'.**second screen filling table fieldsPERFORM fill_screendata USING 'SAPLSD41' '2200'.PERFORM FILL_FIELD_DATA USING 'DD03P-FIELDNAME(01)' 'mandt'.PERFORM FILL_FIELD_DATA USING 'DD03P-FIELDNAME(02)' 'name'.PERFORM FILL_FIELD_DATA USING 'DD03P-FIELDNAME(03)' 'empid'.PERFORM FILL_FIELD_DATA USING 'DD03D-ROLLNAME(01)' 'mandt'.PERFORM FILL_FIELD_DATA USING 'DD03D-ROLLNAME(02)' 'char20'.PERFORM FILL_FIELD_DATA USING 'DD03D-ROLLNAME(03)' 'numc4'.PERFORM FILL_FIELD_DATA USING 'DD03P-KEYFLAG(01)' 'X'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '/00'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=WB_SAVE'.**saving the table****PERFORM fill_screendata USING 'SAPLSTRD' '0100'.PERFORM FILL_FIELD_DATA USING 'KO007-L_DEVCLASS' '$TMP'.PERFORM FILL_FIELD_DATA USING 'KO007-L_AUTHOR' 'SAPDEV02'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=TEMP'.**filling technical settings.PERFORM fill_screendata USING 'SAPLSD41' '2200'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=SE13'.PERFORM fill_screendata USING 'SAPMSEDS' '0050'.PERFORM FILL_FIELD_DATA USING 'BDC_CURSOR' 'DD09V-TABART'.PERFORM FILL_FIELD_DATA USING 'DD09V-TABART' 'APPL0'.PERFORM FILL_FIELD_DATA USING 'DD09V-TABKAT' '0'.PERFORM FILL_FIELD_DATA USING 'ALLOWSTATE-NOT_ALLOWED' 'X'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=SICH'.PERFORM fill_screendata USING 'SAPMSEDS' '0050'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=BACK'.PERFORM fill_screendata USING 'SAPLSD41' '2200'.PERFORM FILL_FIELD_DATA

Page 494: ABAP Tutorials

USING 'BDC_OKCODE' '=WB_SAVE'.PERFORM fill_screendata USING 'SAPLSD41' '2200'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=WB_CHECK'.PERFORM fill_screendata USING 'SAPLSD41' '2200'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=WB_ACTIVATE'.PERFORM FILL_SCREENDATA USING 'SAPLSEWORKINGAREA' '0205'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=WEIT'.PERFORM fill_screendata USING 'SAPLSD41' '2200'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=BACK'.PERFORM fill_screendata USING 'SAPMSRD0' '0102'.PERFORM FILL_FIELD_DATA USING 'BDC_OKCODE' '=BACK'.CALL TRANSACTION 'SE11' USING T_BDCDATA MODE 'A' MESSAGES INTO T_MSG.LOOP AT T_MSG INTO MSG.CALL FUNCTION 'FORMAT_MESSAGE' EXPORTING ID = MSG-MSGID LANG = 'EN' NO = MSG-MSGNR V1 = MSG-MSGV1 V2 = MSG-MSGV2 V3 = MSG-MSGV3 V4 = MSG-MSGV4 IMPORTING MSG = MESSAGE EXCEPTIONS NOT_FOUND = 1 OTHERS = 2 .IF sy-subrc <> 0.* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.ENDIF.IF sy-subrc EQ 0. WRITE / MESSAGE. ENDIF.ENDLOOP.endform. " PROCESS

Output

First Screen

Page 495: ABAP Tutorials

Setting the delivery class and maintenance

Saving the table

Page 496: ABAP Tutorials
Page 497: ABAP Tutorials

Technical Settings

Activating The Table

Page 498: ABAP Tutorials

BDC recording from testing client to development client

Page 499: ABAP Tutorials

By Venkatraman N, IBM

This method would be useful, when you don’t have required datum in development client and when you have same in testing client and you want to BDC recording with that datum.  

Login to the Testing client where you will have data.

Go to transaction SHDB and press new recording.  

As an instance, here we will try to modify vendor’s postal code of his address. So, give FK02 as the transaction code to be executed and give recording name like ‘ZRECORD’.  

 

Page 500: ABAP Tutorials

Now it goes to Vendor master update screen. Opt a vendor and click the address checkbox and press enter.  

 

It will show the vendor’s address information.  

Page 501: ABAP Tutorials

Now change the existing PIN code 700019 to 560076 and press save. It will take you to the recording screen.  

Page 502: ABAP Tutorials
Page 503: ABAP Tutorials

Now you cannot create a program with this recording information in testing client. So, import your recording information to one presentation server file. Press import button.

Give a text file name and save it in the presentation server.  

Page 504: ABAP Tutorials

Then Go to SHDB transaction in development client and go to new recording. Give the recording name as ZRECORDINGNEW and opt the same vendor master updation transaction code FK02.

 

In this case your development client should have at least one vendor. If not create it and input the vendor in FK02 transaction and as you did earlier select the address checkbox.  

Page 505: ABAP Tutorials

 

It will show you the address information. You don’t change anything in that and come back. Because this is not the vendor to whom we are going to change his PIN Code.  

Page 506: ABAP Tutorials

Now it will show you the recording information. Delete all the recording information and press the import button and browse bdc_recording file from the presentation server.  

Page 507: ABAP Tutorials

 

Page 508: ABAP Tutorials

 

The previous recording information will loaded in to BDC recording and go back from the screen. It would popup for saving the recording. Now save that recording.  

 

Page 509: ABAP Tutorials

 

Select the recording and press ‘program’ button. It will popup for new program creation. Input the required details and the expected BDC recording program will get created.  

 

Page 510: ABAP Tutorials

 

 

report ZVENDORUPDATE       no standard page heading line-size 255.

include bdcrecx1.

start-of-selection.

Page 511: ABAP Tutorials

perform open_group.

perform bdc_dynpro      using 'SAPMF02K' '0106'.perform bdc_field       using 'BDC_CURSOR'                              'RF02K-LIFNR'.perform bdc_field       using 'BDC_OKCODE'                              '/00'.perform bdc_field       using 'RF02K-LIFNR'                              'B002568'.perform bdc_field       using 'RF02K-D0110'                              'X'.perform bdc_dynpro      using 'SAPMF02K' '0110'.perform bdc_field       using 'BDC_CURSOR'                              'LFA1-PSTLZ'.perform bdc_field       using 'BDC_OKCODE'                              '=UPDA'.perform bdc_field       using 'LFA1-NAME1'                              'MURARI SHARAN SRIVASTAVA'.perform bdc_field       using 'LFA1-SORTL'                              '000568'.perform bdc_field       using 'LFA1-STRAS'                              'Brook House, Shakespeare Sarani'.perform bdc_field       using 'LFA1-ORT01'                              'Kolkatta'.perform bdc_field       using 'LFA1-PSTLZ'                              '560076'.perform bdc_field       using 'LFA1-LAND1'                              'IN'.perform bdc_field       using 'LFA1-REGIO'                              '25'.perform bdc_field       using 'LFA1-SPRAS'                              'EN'.perform bdc_transaction using 'FK02'.

perform close_group.

………………………………………………………………………………………………………

 

Page 512: ABAP Tutorials