abap in-4-hours[1]

87
ABAP in 4 Hours Krishna Rungta Published by SapTrainingHub.com Copyright 2012 Krishna Rungta Smashwords Edition Smashwords Edition, License Notes This ebook is licensed for your personal enjoyment only. This ebook may not be re-sold or given away to other people. If you would like to share this book with another person, please purchase an additional copy for each recipient. If you’re reading this book and did not purchase it, or it was not purchased for your use only, then please return to Smashwords.com and purchase your own copy. Thank you for respecting the hard work of this author.. Chapter 1 – Introduction to ABAP ABAP stands for – Advanced Business Application Programming. It is a programming language for developing applications for the SAP R/3 system. The latest version of ABAP is called ABAP Objects and supports object-oriented programming. SAP will run applications written using ABAP/4, the earlier ABAP version, as well as applications using ABAP Objects. Without further ado, let’s dive into ABAP.Note, this Chapter will not go into extensive details on ABAP language constructs (which become very boring to read) but quickly introduce key concepts to get you started so you can focus your attention on more important topics. Data Types Syntax to declare a variable in ABAP - DATA Variable_Name Type Variable_Type. Example: DATA employee_number Type I. The following is a list of Data Types supported by ABAP

Post on 18-Oct-2014

764 views

Category:

Technology


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Abap in-4-hours[1]

ABAP in 4 HoursKrishna Rungta

Published by SapTrainingHub.comCopyright 2012 Krishna Rungta

Smashwords Edition

Smashwords Edition, License NotesThis ebook is licensed for your personal enjoyment only. This ebook may not be re-sold or

given away to other people. If you would like to share this book with another person, please purchase an additional copy for each recipient. If you’re reading this book and did not purchase

it, or it was not purchased for your use only, then please return to Smashwords.com and purchase your own copy. Thank you for respecting the hard work of this author..

Chapter 1 – Introduction to ABAPABAP stands for – Advanced Business Application Programming. It is a programming

language for developing applications for the SAP R/3 system.The latest version of ABAP is called ABAP Objects and supports object-oriented

programming. SAP will run applications written using ABAP/4, the earlier ABAP version, as well as applications using ABAP Objects.

Without further ado, let’s dive into ABAP.Note, this Chapter will not go into extensive details on ABAP language constructs (which become very boring to read) but quickly introduce key concepts to get you started so you can focus your attention on more important topics.Data TypesSyntax to declare a variable in ABAP -

DATA Variable_Name Type Variable_Type.

Example:DATA employee_number Type I.

The following is a list of Data Types supported by ABAP

Page 2: Abap in-4-hours[1]

- Assigning Values a=16.move 16 to a.write a to b.

- Arithmetic Operationscompute a = a*100.

Control StatementsFollowing control statements can be used -If … EndIf Loop

if [not] exp [ and / or [not] exp ].……..[elseif exp........][else........]Endif.

Case statementCase variable.when value1.………when value2.………[ when others..........]Endcase.

Do.-While loopWhile <logical expression>.…..…..

Page 3: Abap in-4-hours[1]

Endwhile.Do loop

Do <n> times.…..…..Enddo.

Logical OperatorA list of logical operatorsGE or >=GT or >LE or <=LT or <EQ or =NE or <>

ABAP/4 EditorFinally, here is where you will spent most of your time as a developer creating / modifying

programs. Transaction SE38

****Chapter 2 – Data Dictionary

A data dictionary is a central source of information for the data in a information management system. Its main function is to support the creation and management of data definitions (or “metadata”).

What is Data dictionary used for?• Management of data definitions• Provision of information for evaluations

Page 4: Abap in-4-hours[1]

• Support for software development• Support for documentation• Ensuring that data definitions are flexible and up-to-date

Objects in the ABAP Dictionary resided on three levels that support their re-usability. These levels are:

Tables and structuresData elementsDomainsLet’s look into them in detail -

DomainsDescribes the technical characteristics of a table fieldSpecifies a value range which describes allowed data values for the fieldsFields referring to the same domain (via the data elements assigned to them) are changed when a change is made to the domainEnsures consistencyEx. Purchasing document number (EBELN)

Page 5: Abap in-4-hours[1]

Data ElementsDescribes the role played by a field in a technical contextFields of same semantic meaning can refer to the same data elementContains the field informationEx. Purchasing document number (EBELN)

Page 6: Abap in-4-hours[1]

TablesRepresent the Database Tables where data actually resides.Tables can be defined independently of the database in the ABAP Dictionary.The fields of the table are defined with their (database-independent) SAP ABAP data types and lengths.

Page 7: Abap in-4-hours[1]

StructuresAre record declarations that do NOT correspond to a Database Table.Just like user-defined data type.Defined like a table and can then be addressed from ABAP programs.Structures contain data only during the runtime of a program.

Page 8: Abap in-4-hours[1]

Aggregated Objects of ABAP DictionaryAggregated means consisting of several components. In the ABAP Dictionary, aggregated objects are objects which come from several different transparent tables.ViewsSearch HelpLock ObjectsLet’s look into them in detail

ViewsViews in SAP _ ABAP are used to summarize data which is distributed among several tablesThe data of a view is not actually physically stored. The data of a view is instead derived from one or more other tables

It is tailored to the needs of a specific application

Page 9: Abap in-4-hours[1]

Search HelpA Search help is a tool to help you search for data records in the systemAn efficient and user-friendly search assists users where the key of a record is unknown

Page 10: Abap in-4-hours[1]

Lock ObjectsSimultaneous accessing of the same data record by two users in the SAP system is synchronized by a lock mechanism.Locks are set and released by calling certain function modules. These function modules are generated automatically from the definition of so-called lock objects in the ABAP/4 Dictionary

:

Enqueue_<obj name> – to lock the tabledequeue_<obj name> – to release the lock

Page 11: Abap in-4-hours[1]

Important TransactionsSE11 : Data Dictionary Initial Screen (SE12 Display only)SE13 : ABAP Dictionary : Technical SettingsSE14 : Database UtilitySE15 : Repository Information SystemSE16 : Data BrowserSE17 : General table DisplaySE55 : Table View MaintenanceSM30 : Table Maintenance

****Chapter 3 – Modularity in ABAP: Macro, Include, Subroutines, Function

Modules & Groups

When you modularize source code, you place a sequence of ABAP statements in a module. Then, instead of placing all of the statements in your main program, you just call the module. When the program is generated, the source code in the modularization unit is treated as though it were actually physically present in the main program.Need of Modularization

• Improve the structure of the program.• Easy to read the code• Easy to maintain the code• Avoid redundancy and promotes code reuse

Various Modularization Techniques• Use of Macros• Use of include files• Subroutines• Function Modules

Page 12: Abap in-4-hours[1]

Let’s look into each of them in detail:SAP- ABAP MacroIf you want to reuse the same set of statements more than once in a program, you can include them in a macro.You can only use a macro within the program in which it is defined, and it can only be called in lines of the program following its definition.Macros can be useful for long calculations or complex WRITE statements.Syntax

DEFINE <macro_name>‘Macro StatementsEND-OF-DEFINITIONMacros can use Parameters &N where N = 1,2,3…Example:-DATA: number1 TYPE I VALUE 1.DEFINE increment.ADD 1 to &1.WRITE &1.END-OF-DEFINITION.Increment number1.WRITE number1.Output: 2

Include ProgramsInclude Programs are solely for modularizing source code, and have no parameter interface.Include programs allow you to use the same source code in different programs. They can be useful if you have lengthy data declarations that you want to use in different programs.

SyntaxInclude <include program Name>

Points to Note• Include programs cannot call themselves.• Include programs must contain complete statements.

Example:

INCLUDE ZILX0004.WRITE: / ‘User’, SY-UNAME,/ ‘Date’, SY-DATUM.================================PROGRAM ZRPM0001.INCLUDE ZILX0004.

SubroutinesSubroutines are procedures that you can define in any ABAP program and also call from any

program. Subroutines are normally called internally, that is, they contain sections of code or algorithms that are used frequently locally. If you want a function to be reusable throughout the system, use a function module.

Syntax-FORM <Subroutine> [<pass>].<Statement block>.ENDFORM.<Subroutine> = Name of the subroutine

Page 13: Abap in-4-hours[1]

<pass> = Parameters being passedTypes of Subroutines

InternalSubroutine defined in same program being called.Can access all the data objects declared in the main ABAP/4 program.ExternalSubroutine defined outside the program being called.Need to use the <pass> option or declare data objects in common parts of memory.

Calling a SubroutineInternal Subroutines

PERFORM <subroutine> [<pass>]<subroutine> = Name of the subroutine<pass> = Parameters being passedData declared in main program is automatically available.

External SubroutinesPERFORM <subroutine>(<Program>) [<pass>].PERFORM <subroutine> (<Program>) [<pass>] [IF FOUND].PERFORM (<subroutine>) IN PROGRAM (<Program>) [<pass>] [IF FOUND].PERFORM <index> OF <subroutine1> <subroutine2> <subroutine3> [<pass>].

Points to Note• Nested calls are allowed in subroutines (i.e. PERFORM within a FORM …

ENDFORM ).• Recursive calls are also possible.• To define local data, use the DATA statement after FORM . Each time you enter the

subroutine, the data is recreated (with an initial value) and released at the end (from the stack).

• To define global data used within a subroutine, use the LOCAL statement after FORM . The values are saved when you enter the subroutine and then released at the end (from the stack)

Function ModulesFunction Modules are general purpose ABAP/4 routines that anyone can use. Infact , there

are a large number of standard function Modules available.Function Modules are organized into Function Groups: Collections of logically related

functions. A Function module always belongs to a Function Group.Syntax-FUNCTION <function module><Statements>ENDFUNCTION.

Important information Associated with Function Module• Administration• Import/Changing/Export parameters.• Table Parameters/Exceptions.• Documentation

• Source code – L<fgrp>U01 . <fgrp> is the Function Group

• Global Data – L<fgrp>TOP .Global data for the function group- Accessible across function modules in the function group.

• Main Program – SAPL<fgrp> . Contains the list of all the include files for that function group

Page 14: Abap in-4-hours[1]

Call a Function ModuleTo call a function module, use the CALL FUNCTION statement:CALL FUNCTION <module>[EXPORTING f1 = a 1.... f n = a n][IMPORTING f1 = a 1.... f n = a n][CHANGING f1 = a 1.... f n = a n][TABLES f1 = a 1.... f n = a n][EXCEPTIONS e1 = r 1.... e n = r n [ERROR_MESSAGE = r E]

[OTHERS = ro]].Function Groups

Function groups are containers for function modules. Infact, there are a large number of standard Function Groups.All of the function modules in a function group can access the global data of the group.Like executable programs (type 1) and module pools (type M), function groups can contain screens, selection screens, and lists.Points to Note

• Function Groups cannot be executed.• The name of a function group can be up to 26 characters long.• When you create a function group or function module, the main program and include

programs are generated automatically.• Function groups encapsulate data.

How to create a Function Group1. Goto Transaction SE80.2. Select Program in the DropDown.3. Write the name of the Function Group That you want to create. Generally User made

Function groups start with “Z”. e.g. – <Z_FUNCTION_GROUP_NAME> . Hit Enter Key.

4. Note that The TOP Include is create by default if the user checks the option of creating a TOP include.

How to create a Function Module1. Create a function Group (say “ZCAL“).2. Create a function module, set the attributes like (Function group, Application, Short

Text and Process Type) and Save.3. Include file “LZCALU01” will have source code of first function module.4. Include file “LZCALTOP” will have global data.5. Main program “SAPLZCAL” contains6. Global data Include file “LZCALTOP“7. Function modules include file “LZCALUXX“8. User defined Include files “LZCALF..”, “LZCALO..” and “LZCALI..”9. Define interface parameters and Exceptions10. Write the source code11. Activate Function Module12. Testing the Function Module – Single Test & Debugging13. Documenting and Releasing a Function Module

That’s all to Modularity in ABAP.

Page 15: Abap in-4-hours[1]

****Chapter 4 - Native and Open SQL

The goal of this Chapter is not to teach you SQL or database concepts but to introduce you to the SQL diversity in ABAP.In ABAP/4 programming language, there are two types of SQL being used.

• NATIVE SQL• OPEN SQL.

Open SQL allows you to access the database tables declared in the ABAP dictionary regardless of the database platform that the R/3 system is using.

Native SQL allows you to use database-specific SQL statements in an ABAP/4 program. This means that you can use database tables that are not administered by ABAP dictionary, and therefore integrate data that is not part of the R/3 system.

Open SQL consists of a set of ABAP statements that perform operations on the central database in the R/3 system. The results of the operations and any error messages are independent of the database system in use. Open SQL thus provides a uniform syntax and semantics for all of the database systems supported by SAP. ABAP programs that only use Open SQL statements will work in any R/3 system, regardless of the database system in use. Open SQL statements can only work with database tables that have been been created in the ABAP dictionary.Basic Open SQL Commands

• SELECT• INSERT• UPDATE• MODIFY• DELETE• OPEN CURSOR,FETCH, CLOSE CURSOR

Example

TABLES SBOOK.DATA C TYPE CURSOR,WA LIKE SBOOK.OPEN CURSOR C FOR SELECT * FROM SBOOK WHERE CARRID = ‘LH ‘AND CONNID = ’0400′AND FLDATE = ’19950228′ORDER BY PRIMARY KEY.DO.FETCH NEXT CURSOR C INTO WA.IF SY-SUBRC <> 0.CLOSE CURSOR C.EXIT.ENDIF.WRITE: / WA-BOOKID, WA-CUSTOMID, WA-CUSTTYPE,WA-SMOKER, WA-LUGGWEIGHT, WA-WUNIT,WA-INVOICE.ENDDO.Output the passenger list for the Lufthansa flight 0400 on 28-02.1995:

Page 16: Abap in-4-hours[1]

Open SQL Return CodesAll Open SQL statements fill the following two system fields with return codes.SY-SUBRC

After every Open SQL statement, the system field SY-SUBRC contains the value 0 if the operation was successful, a value other than 0 if not.SY-DBCNT

After an Open SQL statement, the system field SY-DBCNT contains the number of database lines processed.Native SQL

As already mentioned, Native SQL allows you to use database-specific SQL statements in an ABAP program.

To use Native SQL statement, you must precede it with the EXEC SQL statement, and follow it with the ENDEXEC statement.

SyntaxEXEC SQL [PERFORMING <form>].<Native SQL statement>ENDEXEC.There is no period after Native SQL statements. Furthermore, using inverted commas (“) or

an asterisk (*) at the beginning of a line in a native SQL statement does not introduce a comment as it would in normal ABAP syntax. You need to know whether table and field names are case-sensitive in your chosen database.

In Native SQL statements, the data is transported between the database table and the ABAP program using host variables. These are declared in the ABAP program, and preceded in the Native SQL statement by a colon (:). You can use elementary structures as host variables. Exceptionally, structures in an INTO clause are treated as though all of their fields were listed individually.

As in Open SQL, after the ENDEXEC statement, SY-DBCNT contains the number of lines processed. In nearly all cases, SY-SUBRC contains the value 0 after the ENDEXEC statement.Open SQL – Performance Rules

To improve the performance of the SQL and in turn of the ABAP program, one should take care of the following rules-

Keep the Result Set SmallUsing the where clauseIf only one record is required from the database, use SELECT SINGLE whenever possible.Minimize the Amount of Data TransferredRestrict the number of linesIf only certain fields are required from a table, use the SELECT <field1> <field2> INTO …

statementRestrict no of columnsUse aggregate functionsMinimize the Number of Data TransfersAvoid nested select loopsAn alternative option is to use the SELECT. FOR ALL ENTRIES statement. This statement

can often be a lot more efficient than performing a large number of SELECT or SELECT SINGLE statements during a LOOP of an internal table.

Use dictionary viewsUse Joins in the FROM clauseUse sub queries in the where clause

Page 17: Abap in-4-hours[1]

Minimize the Search OverheadUse index fields in the where clauseWhen accessing databases, always ensure that the correct index is being used .Reduce the Database LoadBufferingLogical databasesAvoid repeated database accessUsing Internal Tables to Buffer RecordsTo avoid executing the same SELECT multiple times (and therefore have duplicate selects),

an internal table of type HASHED can be used to improve performance.

****

Chapter 5 - SAP Internal TablesIn this Chapter we will cover the following topics

• Internal Tables. Difference between Internal Tables and Work Areas• Types of Internal Tables• Creating Internal Tables• Populating Internal Tables• Reading Internal Tables• Deleting from Internal table.

Let’s Begin!What is an Internal Table?

Internal tables are used to obtain data from a fixed structure for dynamic use in ABAP. Each line in the internal table has the same field structure. The main use for internal tables is for storing and formatting data from a database table within a program.What is a Work Area?

Work areas are single rows of data. They should have the same format as any of the internal tables. It is used to process the data in an internal table one line at a time.Difference Between Internal Table and a Work Area?

A picture says a thousand words

Page 18: Abap in-4-hours[1]

Types of Internal TablesThere are two types of internal tables.Internal tables with HEADER lineInternal tables without HEADER line.

Internal Tables with Header LineHere the system automatically creates the work area.The work area has the same data type as internal table.This work area is called the HEADER line.It is here that all the changes or any of the action on the contents of the table are done. As a

result of this, records can be directly inserted into the table or accessed from the internal table directly.Internal Tables without Header Line :

Here there is no work area associated with the table.Work area is to be explicitly specified when we need to access such tables.Hence these tables cannot be accessed directly.

Creating Internal TablesThere are many ways to create an Internal Table. Let’s look at them one by one-

1. By Using the Type StatementLet us now create a Internal table itab using the TYPE statement.The syntax is -Types : begin of line,column1 type I,column2 type I,end of line.Example:TYPES : begin of line,empno type I,empname(20) type c ,end of line.The TYPES statement creates a structure line as defined.To actually create an Internal

Table itab use the following command-Data itab type line occurs 10.An internal table itab is created with the structure of line.Besides declaring the structure of an

internal table, the OCCURS clause also defines how many table entries are maintained in main storage(in this case 10). Extra records are written out to paging area and can affect performance2. By referring to another Table

You can create an internal table by referring to an existing table. The existing table could be a standard SAP table, a Z table or another internal table.

Syntax-Data <f> <type> [with header line].

Example-

DATA itab TYPE line OCCURS 10 with header line.Here an internal table itab is created of the type line with a header line. Please note “with

header line” is optional3. By referring to existing Structure

Syntax-

Page 19: Abap in-4-hours[1]

Data <f> LIKE <struct> occurs n [with header line].Example-DATA itab LIKE sline OCCURS 10.Here a table itab is created having a structure same as that of sline

4. By creating a new StructureLet us now create an internal table with a structure of our own. Here the table is created with

an Header line, by default.Syntax -Data : Begin of <f> occurs <n>,<component declaration>,……………………………,End of <f>.Example -Data : Begin of itab occurs 10,column1 type I,column2(4) type C,column3 like mara-ernam,End of itab.Internal table itab is created

Populating Internal TablesNow that we have successfully created some internal tables, let us see how do we populate

them with some records. There are various methods available to populate tables1. Append Data line by line

The first method available is the use of the APPEND statement.Using the APPEND statement we can either add one line from another work area to the internal table or we can add one initial line to the internal table. Syntax -

APPEND [<wa> TO / INITIAL LINE TO] <itable>.Here work area <wa> or the Initial Line is appended to the internal table <itable>.The system

variable SY-TABIX contains the index of the appended line.Example:Data: Begin of itab occurs 10,col1 type C,col2 type I,end of itab.Append initial line to itab.Results : ‘ ‘ ’0′An initial line adds a line initialized with the correct value for its type to the table. Here ,

col1 is an integer and col2 is a character. Then APPEND initial line , adds a line initialized with respect to the data type of the columns, i.e. 0 for Col1 and space for Col2.2. Using COLLECT statement

COLLECT is another form of statement used for populating the internal tables. Generally COLLECT is used while inserting lines into an internal table with unique standard key.Syntax-

COLLECT [<wa> INTO] <itable>.In case of tables with Header line, INTO option is omitted. Suppose there is already an entry

having a key same as the one you are trying to append, then a new line is not added to the table, but the numeric fields of both the entries are added and only one entry corresponding to the key

Page 20: Abap in-4-hours[1]

is present. Value of SY-TABIX is changed to the row of the original entry. Else COLLECT acts similar to APPEND and SY-TABIX contains the index of the processed line.3 . Using INSERT statement

INSERT statement adds a line/work area to the internal table. You can specify the position at which the new line is to be added by using the INDEX clause with the INSERT statement.Syntax

INSERT [<wa> INTO / INITIAL LINE INTO] <itable> [index <idx>].Here, the work area <wa> or INITIAL LINE is inserted into internal table <itable> at

index <idx>.Copying Internal Tables

The contents of one internal table can be copied to another by using the APPEND LINES or INSERT LINES statement. A more simpler way is to use any of the following syntax’s.

MOVE <itab1> To <itab2>.OR<itab1> = <itab2>.These copy the contents of ITAB1 to ITAB2. In case of internal tables with header line we

have to use [] in order to distinguish from work area. So, to copy contents of internal tables with header line the syntax becomes, itab1[] = itab2[].Reading Internal Tables

We are now familiar with the creation of internal tables and populating them with data. We will now see how do we actually use the data or retrieve the data from the internal tables.1 . Using Loop -Endloop

One of the ways of accessing or reading the internal table is by using LOOP-ENDLOOP. Syntax-

LOOP AT <itable> [INTO <wa>]……………………………..ENDLOOP.Here when you say LOOP AT ITABLE, then the internal table ITABLE is read line by line.

You can access the values of the columns for that line during any part of the LOOP-ENDLOOP structure. The value of the SY-SUBRC is set to 0, even if only one record is read.2 . Using READ

The other method of reading the internal table is by using the READ statement. Syntax-READ TABLE <itable> [INTO <wa>] INDEX <idx>.

This statement reads the current line or line as specified by index <idx>. The value of SY-TABIXis the index of the line read. If an entry with the specified index is found, then SY-SUBRC is set to 0. If the specified index is less than 0, then run-time error occurs. If the specified index exceeds table size then SY-SUBRC is set to 4.

Deleting Internal TablesThere are many ways for deleting lines from an internal table.

1. Deleting lines in a loop.This is the simplest way for deleting lines. SyntaxDELETE <ITABLE>.

This statement works only within a loop. It deletes the current line. You can delete the lines in a loop conditionally by adding the WHERE clause.

2. Deleting lines using the index.This is used to delete a line from internal table at any know index.Syntax

DELETE <ITABLE> INDEX <IDX>.

Page 21: Abap in-4-hours[1]

The line with the index <IDX> is deleted. The index of the following line is decremented by 1.

****Chapter 6 - ABAP Table Controls

Table controls and step loops are objects for screen table display that you add to a screen in the Screen Painter.From a programming standpoint, table controls and step loops are almost exactly the same. Table controls are simply improved step loops that display data with the look and feel associated with tables in desktop applications.With table controls, the user can:

• Scroll through the table vertically and horizontally• Re-size the width of a column• Scroll within a field (when field contents are wider than the field)• Select table rows or columns• Re-order the sequence of columns• Save the current display settings for future use

Table controls also offer special formatting features (some automatic, some optional) that make tables easier to look at and use. Table Control provides -

• automatic table resizing (vertical and horizontal) when the user resizes the window• separator lines between rows and between columns (vertical and horizontal)• column header fields for all columns

One feature of step loops is that their table rows can span more than one line on the screen. A row of a table control, on the other hand, must always be contained in a single line (although scrolling is possible).

In general, many of the features provided by the table control are handled locally by your system’s SAP gui frontend, so you do not need to program them yourself. The only notable exception to this is vertical scrolling. Example (Transaction TZ60)

To handle table controls in ABAP programs, you must declare a control in the declaration part of the program for each table control using the following statement:

CONTROLS <ctrl> TYPE TABLEVIEW USING SCREEN <scr>where <ctrl> is the name of the table control on a screen in the ABAP program. The control

allows the ABAP program to read the attributes of the table control and to influence the control .Here, <scr> is the screen number where the initial values of the table are loaded.Cursor Position for a table control can be set in following ways:At PBO you can set the cursor on a specific field of a specific row of a table control.

SET CURSOR FIELD <f> LINE <lin> [OFFSET <off>]

Page 22: Abap in-4-hours[1]

Using the optional addition OFFSET, you can enter the offset of the cursor in the field as described under setting the Cursor Position.At PAI you can read the current cursor position.

GET CURSOR FIELD <f> LINE <lin> …In addition to the information given under Finding Out the Cursor Position,

field <lin> contains information on which row of the table control the cursor is currently on. You can also use

GET CURSOR LINE <lin>.To determine the row of the table control. SY-SUBRC allows you to check if the cursor is

placed in a row of a table control.For getting the corresponding line of the internal table:GET CURSOR line <lin>.ind = <table_control>-top_line + <lin> – 1.Read table <itab> index ind.The system variable stepl - contains the current table line index in a loop …

endloop. Loopc – contains number of lines visible in the tableTo create a table control

1. Add a table control element to your screen2. Give a name to the table control. In the ABAP program declare a structure with the

same ( CONTROLS <tcl> type TABLEVIEW USING SCREEN <scrn >)3. To create fields go to the Dict./Program fields function.

Enter the name of the structure whose fields you want. (If you want it to pick it from dictionary of your program click the relevant puhbutton).In the field list choose the fields you want and choose ok.Click in the table control area.If you want a selection column, check the appropriate check box in the attributes and give it a name. Create the field in the ABAP program. In the PBO you should have the statement

LOOP at <itab> USING CONTROL <cntrl_name>.ENDLOOP.In the PAI you should have.LOOP at <itab>.ENDLOOP.It is within the loops that data transfer happens between the screen and the internal

table.When you populate the internal table use DESCRIBE TABLE <itab> LINES <cntrl_name>-lines, to store the total number of lines in the control. The FIELD statement can be used to control when the data transfer happens.To change the attributes of individual cells temporarily change the SCREEN table in the PBO. You can change the attributes of the structure created by the CONTROLS statement

<cntrl>-fixed_cols etc are the attributes of the control<cntrl>-cols-index etc are the attributes of the columns.<cntrl>-cols-screen-invisible etc are the screen attributes of each column.

****Chapter 7 - ABAP Report Programming

SAP-ABAP supports two types of Programs - Report Programs & Dialog Programs. Report Programs are used when large amounts of data needs to be displayedPurpose/Use of Report Programs

• They are used when data from a number of tables have to be selected and processed before presenting

Page 23: Abap in-4-hours[1]

• Used when reports demand a special format• Used when the report has to be downloaded from SAP to an Excel sheet to be

distributed across.• Used when the report has to be mailed to a particular person.

Important Points to Note about Report Program• Report Programs are always Executable Programs. Program Type is always 1.• Every Report program corresponds to a particular Application Type i.e. either with

Sales & Distribution, FI – CO etc. It can also be Cross Application i.e. type ‘*’.• Report Programming is an Event-driven programming.• The first line of a report program is always Report <report-name>.• In order to suppress the list heading or the name of the program the addition No

Standard Page Heading is used.• The line size for a particular report can be set by using the addition line-size <size>.• The line count for a particular page can be set by using the addition line-count

n(n1). N is the number of lines for the page and N1 is the number of lines reserved for the page footer.

• To display any information or error message we add a message class to the program using the addition: Message-id <message class name>. Message classes are maintained in SE91.

Therefore an ideal report program should start with:Report <report name> no standard page headingline-size <size>line-count <n(n1)>message-id <message class>.

Selection Screen“Selection screen” is the screen where one specifies the input values for which the program

should run.The selection screen is normally generated from the• Parameters• Select-Options

SyntaxSelection-screen begin of screen <screen #>selection-screen begin of block <#> with frame title <text>………………selection-screen end of block <#>selection-screen end of screen <screen #>Parameters

Parameters helps one to do dynamic selection. They can accommodate only one value for one cycle of execution of the program.Syntax

Defining parameters as a data typeParameters p_id(30) type c.Defining parameters like a table field.Parameter p_id like <table name>-<field name>.Parameters can be Checkboxes as well as Radiobuttons.

Page 24: Abap in-4-hours[1]

Parameters p_id as checkbox. Parameters p_id1 radiobutton group <group name>. Parameters p_id2 radiobutton group <group name>. Parameters can be listbox. Parameter p_id like <table name>-<field name> as listboxSelect Options

A Select-Option is used to input a range of values or a set of values to a program.Syntaxselect-options s_vbeln for vbak-vbeln.

You can also define a select option like a variableselect-options s_vbeln for vbak-vbeln no intervals no-extension

Events in an ABAP Report ProgramABAP report programs are event driven programs. The different events in a report Program

are:Load-of-program

Triggers the associated event in an internal session after loading a program of type 1, M, F, or S.

Also runs the associated processing block once and once only for each program and internal session.

The processing block LOAD-OF-PROGRAM has roughly the same function for an ABAP program of type 1, M, F or S as a constructor has for classes in ABAP ObjectsInitialization

This event is executed before the selection screen is displayed.Initialization of all the values.You can assign different values other than the values defaulted on the selection screen.You can fill your selection screen with some values at runtime.

At Selection-ScreenThe event is processed when the selection screen has been processed (at the end of PAI ).Validation & Checks of inputted values happen here

Start-of-SelectionHere the program starts selecting values from tables.

End-of-selectionAfter all the data has been selected this event writes the data to the screen.

Interactive EventsUsed for interactive reporting. It is used to create a detailed list from a basic list.

Formatting the reportABAP allows the reports to be formatted as the user wants it to be. For example, “Alternate

Lines” must appear in different colors and the “Totals” line should appear in Yellow.SyntaxFormat Color nFormat Color n Intensified Onn may correspond to various numbersPlease note that there are other additions along with format as wellFORMAT COLOR OFF INTENSIFIED OFF INVERSE OFF HOTSPOT OFF INPUT

OFFInteractive Programming

Page 25: Abap in-4-hours[1]

Using Interactive Programming users can actively control the data retrieval and display of data

Used to create a detailed list from a very basic listThe detailed data is written on a secondary list.The secondary list may either completely overlay the first screen or one can display it in a

new screenThe secondary lists can be themselves interactive.The first list may also call a transaction.There are different events associated with interactive programming.Some commands used for interactive programming

HotspotIf one drags the mouse over the data displayed in the repor the cursor changes to a Hand

with an Outstretched Index finger. An hotspot can be achieved using the FORMAT statement.Syntax: Format Hotspot On (Off).

HideThis command helps you to store the field names based on which one will be doing further

processing to get a detailed list. It is written directly after the WRITE statement for a field. When a row is selected the values get automatically filled in the variables for further use.

Syntax: Hide <field-name>.Logical Databases

Instead of using “Select” queries you can use logical database to retrieve data for a program.Logical databases are created by transaction SE36

The name of a logical database can be up to 20 characters long. It may begin with a namespace prefix.

The data is selected by another program and one can access the data using GET <table-name> command which places the data in the work area <table-name>.Advantages of a logical database over normal Select queries.

It offers check conditions to see whether the input is correct, complete and plausibleIt contains central authorization checks for database accessEnhancements such as improvement in performance immediately apply to all reports which

use logical database.Note: Due to the complexities involved, logical databases are not used in most of the cases

****Chapter 8 - ABAP Dialog Programming

SAP-ABAP supports two types of programs – Report Program and Dialog Program.If your ABAP program demands user input, Dialog programming is used.A user dialog is any form of interaction between the user and the program and could be any

of the following• Entering data• Choosing a menu item• Clicking a button• Clicking or double clicking an entry

Dialog program is also used when we need to navigate back and forth between screensDialog programs are created with type as ‘M’ – Module Pool. They cannot be executed

independently and must be attached to at least one transaction code in which you specify an initial screen.

Page 26: Abap in-4-hours[1]

Difference between Report and Dialog Programs

Report Program:A report is a program that typically reads and analyzes data in database tables without

changing the database.Dialog Program:

A dialog program allows you to work interactively with the system and to change the contents of the database tables. Each dialog program has a certain sequence of screens that are processed by the system one after the other.A Sample transaction processing in Dialog Programming

Components of Dialog ProgramUnlike report which generally entails the creation of one autonomous program which can be

executed independently of other objects, dialog program development entails development of multiple objects none of which can be executed on its own. Instead all objects are linked hierarchically to the main program and are executed in a sequence dictated by the Dialog Main Program.

The components of a dialog program are:Transaction code

The transaction code starts a screen sequence.You create transaction codes in the Repository Browser in the ABAP Workbench or using

Transaction SE93.A transaction code is linked to an ABAP program and an initial screen.You can start a screen sequence from any ABAP program using the CALL SCREEN

statement.Screens

Each dialog in an SAP system is controlled by one or more screens.You create screens using the Screen Painter in the ABAP Workbench through transaction

SE51Each screen belongs to an ABAP program.

Page 27: Abap in-4-hours[1]

These screens consist of a “screen mask” or “layout” and its flow logic. The screen has a layout that determines the positions of input/output fields and other graphical elements such as checkboxes and radio buttons. A flow logic determines the logical processing within screen.GUI status

Each screen has a GUI status(es) which are independent components of a program.This controls the menu bars, standard toolbar, application toolbar , with which the user can

choose functions in the application.You create them in the ABAP Workbench using the Menu Painter.

ABAP ProgramEach screen and GUI status in the R/3 System belongs to one ABAP program.The ABAP program contains the dialog modules that are called by the screen flow logic,

and also process the user input from the GUI status.ABAP programs that use screens are also known as dialog programs.In a module pool (type M program); the first processing block to be called is always a dialog

module. However, you can also use screens in other ABAP programs, such as executable programs or function modules. The first processing block is then called differently; for example, by the runtime environment or a procedure call. The screen sequence is then started using the CALL SCREEN statement.Screen Flow Logic

Screen Flow logic is primarily divided into four components.1. Process Before Output (PBO) event: which is processed before the screen is

displayed2. Process After Input (PAI) event: which is processed after a user action on the screen3. Process on help request (POH): which is processed when F1 is pressed4. Process on value request (POV):which is processed when F4 is pressed

DynproA screen together with its Flow logic is called a Dynpro (“Dynamic Program” since the

screen flow logic influences the program flow)Each dynpro controls exactly one step of your Dialog Program.The screens belonging to a program are numbered. The screen flow sequence can be either

linear or cyclic. From within a screen chain, you can even call another screen chain and, after processing it, return to the original chain. You can also override the statically-defined next screen from within the dialog modules of the ABAP program.ABAP Module Pool

On a PBO or PAI event a Dynpro calls an ABAP dialog program. Collection of such programs is called the ABAP module pool.

For example modules called at the PAI event are used to check the user input and to trigger appropriate dialog steps, such as the update task.

All dynpros to be called from within one transaction refer to a common module pool.Structure of a Dialog Program

Page 28: Abap in-4-hours[1]

Process Flow for a Dialog Program

****Chapter 9 - Subscreens

Before you read this Chapter make sure you what a Dialog Program is …Subscreens

A subscreen is an independent screen that is displayed in an area of another (“main”) screen.Subscreens allow you to embed one screen within another at runtime. You can include

multiple sub-screens on main screen.The term subscreen applies both to the screen that you embed, and the area on the main

screen in which you place it. This Chapter is about subscreen areas. The actual screens created through SE51 transaction, are called subscreen screens if defined in screen attributes.

When you use a subscreen, the flow logic of the embedded screen is also embedded in the flow logic of the main screen.Hence, Using subscreens on screens is like using includes in ABAP programs.

To use a subscreen, you must follow three simple steps1. Define the subscreen area(s) on a screen2. Define suitable subscreen screens3. Include the subscreen screen in the subscreen area.

Also, you need to adjust the frame of sub-screen and main screen. You need to name it in the field name field.

Further, you also need to adjust the fields within the subscreen to make them appear in main screen. In case the sub-screen is defined to be larger than the available area in the main screen, only the part of subscreen will be visible that fits in the area available. The area is always

Page 29: Abap in-4-hours[1]

measured from the top left corner of screen. Hence you should take adequate care while defining sub-screen areas and creating sub-screens.EXAMPLE

For instance here we have defined two sub-screen areas on main screen and have attached two different Sub-screen to corresponding areas. Whenever main screen is called, the PBO of main screen is called. But before display, the PBO’s of each screen attached with sub-screen areas on main screen are also called.

You can include a subscreen screen using the CALL SUBSCREEN statement in the flow logic of the main screen.

To include a subscreen screen in the subscreen area of the main screen and call its PBO flow logic, use the following statement in the PBO event of the main screen:

PROCESS BEFORE OUTPUTCALL SUBSCREEN <area> INCLUDING [<prog>] <dynp>.This statement assigns the subscreen screen with number <dynp> to the subscreen area

called <area>. You can also specify the program in which the subscreen screen is defined (optional). If you do not specify the program explicitly, the system looks for the subscreen screen in the same ABAP program as the main program. If it does not find a corresponding subscreen screen, a runtime error occurs. The PBO flow logic of the subscreen screen is also included at the same point. This can call PBO modules of the ABAP program in which the subscreen screen is defined. At the end of the subscreen PBO, the global fields from the program are passed to any identically-named screen fields in the subscreen screen. The PBO flow logic of the subscreen screen can itself include further subscreens.

The name <area> of the subscreen area must be entered directly without inverted commas. You can specify the names <prog> and <dynp> either as literals or variables. If you use variables, you must declare and fill identically-named variables in the ABAP program. The screen number <dynp> must be 4 characters long. If you do not assign a subscreen screen to an area, it remains empty.

Page 30: Abap in-4-hours[1]

To call the PAI flow logic of the subscreen screen, use the following statement in the PAI flow logic of the main screen:

PROCESS AFTER INPUTCALL SUBSCREEN <area>.This statement includes the PAI flow logic of the subscreen screen included in the subscreen

area <area> in the PBO event. This can call PAI modules of the ABAP program in which the subscreen screen is defined. Data is transported between identically-named fields in the subscreen screen and the ABAP program either when the PAI event is triggered, or at the corresponding FIELD statements in the PAI flow logic of the subscreen screen.Points to Remember

• Names of elements of sub-screens within a screen should be unique• You should not have OK_CODE or FCODE attached with sub-screen. The

OK_CODE of main screen itself is OK_CODE of sub-screen• Sub-screens cannot have any dialog modules containing SET TITLEBAR, SET PF-

STATUS, SET SCREEN, LEAVE SCREEN or LEAVE TO SCREEN. This will cause runtime error.

• You need to call it in the flow logic (both PBO and PAI) of the main screen.• CALL SUBSCREEN is not allowed in CHAIN..ENDCHAIN and LOOP ENDLOOP

statements• Cannot have an AT EXIT-COMMAND module• The fields that you use are the global fields. They must be declared in the top include• If using subscreens from another dialog program the data transfer will not happen

unless you add specific code.****

Chapter 10 - Process on Value & Process on HelpFirst, to begin with if you know nothing about Screen Flow logic and their uses in SAP ,we

recommend you check our Chapter on Dialog ProgramNow, let’s look into POH and POV in detail

Process on Help-Request (POH): F1 HelpWhenever F1 is pressed the POH event for the specified data element is executed.If the PROCESS ON HELP-REQUEST event does not exist in the process logic of a screen,

the documentation of the field in the ABAP Dictionary is taken as a basis and displayed. Even if that does not exit no help is displayed.

To display field help documentation, you must code the following screen flow logic in the POH event:

PROCESS ON HELP-REQUESTFIELD <f> [MODULE <mod>] WITH <num>

If there is screen-specific data element documentation for the field <f>, you can display it by specifying its number <num>.

The number <num> can be a literal or a variable. The variable must be declared and filled in the corresponding ABAP program.

Note, the FIELD statement does not transfer the contents of the screen field <f> to the ABAP program in the PROCESS ON HELP-REQUEST event. It just shows help documentation. That’s it.

The module <mod> is defined in the ABAP program like a normal PAI module. The processing logic of the module must ensure that adequate help is displayed for the field in

Page 31: Abap in-4-hours[1]

question. Instead of calling an extra screen with text fields, you should use one of the following function modules to display a suitable SAP script document

HELP_OBJECT_SHOW_FOR_FIELDThis function module displays the data element documentation for components of any

structure or database table from the ABAP Dictionary.You pass the name of the component and structure or table to the import parameters FIELD

and TABLE.HELP_OBJECT_SHOW

Use this function module to display any SAP script document.You must pass the document class (for example, TX for general texts, DE for data element

documentation) and the name of the document to the import parameters DOKCLASS and DOKNAME.

For technical reasons, you must also pass an empty internal table with the line type TLINE to the tables parameter of the function module.Process on Value (POV): F4

When the user chooses the function possible entries (F4), the system displays the possible input values for a field (values, check table, matchcode), provided they were stored by the developer.

The event PROCESS ON VALUE-REQUEST is always processed if the user has called “Possible entries”.

To define Possible values for a field on screen, you need to defined following in POV event of screen flow logic:

PROCESS ON VALUE-REQUESTFIELD field name MODULE module nameFor Possible values, within module defined above, you should use the general function

module HELP_VALUES_GET_WITH_TABLE to get possible values from ABAP Dictionary.There are some other functions that can also be used for input help:F4IF_FIELD_VALUE_REQUESTCalls the input help of the ABAP Dictionary dynamically.You can pass the component names of a structure or database table of the ABAP Dictionary

to the function module in the import parameters TABNAME and FIELDNAME.The function module starts the ABAP Dictionary input help for this component. All of the

relevant screen fields are read.If you specify the import parameters DYNPPROG, DYNPNR, and DYNPROFIELD, the

user’s selection is returned to the corresponding field on the screen.If you specify the table parameter RETURN_TAB, the selection is returned into the table

instead.MODULE VALUE_CARRIER INPUT.CALL FUNCTION ‘F4IF_FIELD_VALUE_REQUEST’EXPORTINGTABNAME = ‘DEMOF4HELP’FIELDNAME = ‘CARRIER1′DYNPPROG = PROGNAMEDYNPNR = DYNNUMDYNPROFIELD= ‘CARRIER’.ENDMODULE.

Page 32: Abap in-4-hours[1]

F4IF_INT_TABLE_VALUE_REQUESTThis function module displays a value list that you created in an ABAP program.The value list is passed to the function module as the table parameter VALUE_TAB.If you specify the import parameters DYNPPROG, DYNPNR, and DYNPROFIELD, the

user’s selection is returned to the corresponding field on the screen.If you specify the table parameter RETURN_TAB, the selection is returned into the table

instead.CALL FUNCTION ‘F4IF_INT_TABLE_VALUE_REQUEST’EXPORTINGRETFIELD = ‘CONNID’DYNPPROG = PROGNAMEDYNPNR = DYNNUMDYNPROFIELD = ‘CONNECTION’VALUE_ORG = ‘S’TABLESVALUE_TAB = VALUES_TAB.That’s all to POH and POV. Leave your comments in case of any doubts.

****Chapter 11 - ALV-ABAP List Viewer Programming

The common desired features of any report are “column alignment”, sorting, filtering, subtotals, totals etc. To implement these from scratch, a lot of coding effort is to be put. To avoid that we can use a concept called ABAP List Viewer (ALV).

Using ALV, we can have three types of reports:1. Simple Report2. Block Report3. Hierarchical Sequential Report

Each of these reports provides function modules which help in producing desired output without much effort. Let’s look at them in detail -Simple Report

Important function modules in this report are -• Reuse_alv_fieldcatalog_merge• Reuse_alv_list_display• Reuse_alv_events_get• Reuse_alv_grid_display• Reuse_alv_commentary_write

REUSE_ALV_FIELDCATALOG_MERGEThis function module is used to populate a field catalog which is essential to display the data

in ALV.If the output data is from a single dictionary table and all the columns are selected, then we

need not exclusively create the field catalog. It’s enough to mention the table name as a parameter (I_structure_name) in the REUSE_ALV_LIST_DISPLAY. But in other cases we need to create it.

Note : Fieldcatalog can be filled manually also by filling up all the required details into the internal table

Important parameters in are:

Page 33: Abap in-4-hours[1]

Export:• I_program_name : report id• I_internal_tabname : the internal output table• I_inclname : include or the report name where all the dynamic forms are handled.

Changing• ct_fieldcat : an internal table with the type SLIS_T_FIELDCAT_ALV which is

declared in the type pool SLIS.

REUSE_ALV_LIST_DISPLAYThis is the function module which prints the data.The important parameters are:

Export:• I_callback_program : report id• I_bypassing_buffer : ‘X’• I_buffer_active : ‘ ‘• I_callback_pf_status_set : routine where a user can set his own pf status or change

the functionality of the existing pf status.• I_callback_user_command : routine where the function codes are handled.• I_structure name : name of the dictionary table• Is_Layout : structure to set the layout of the report• It_fieldcat : internal table with the list of all fields and their attributes which are to be

printed (this table can be populated automatically by the function)• It_events: internal table with a list of all possible events of ALV and their

corresponding form names.Tables:

• t_outtab: internal table with the data to be output

REUSE_ALV_EVENTS_GET:Returns table of possible events for a list type

Import:• Et_Events :The event table is returned with all possible CALLBACK events for the

specified list type (column ‘NAME’). For events to be processed by the Callback, their ‘FORM’ field must be filled. If the field is initialized, the event is ignored. The entry can be read from the event table, the field ‘FORM’ filled and the entry modified using constants from the type pool SLIS.

Export:I_list_type:

• 0 = simple list REUSE_ALV_LIST_DISPLAY• 1 = hierarchical-sequential list REUSE_ALV_HIERSEQ_LIST_DISPLAY• 2 = simple block list REUSE_ALV_BLOCK_LIST_APPEND• 3 = hierarchical-sequential block list

REUSE_ALV_BLOCK_LIST_HS_APPEND

REUSE_ALV_GRID_DISPLAYA new function from ABAP4.6 version, to display the results in grid rather than a preview.

Page 34: Abap in-4-hours[1]

Parameters: same as reuse_alv_list_displayNote:

• Grid cannot handle high volumes. A function like sort, scrolling down consumes a lot of resources / time if the volume of data to be displayed is high. There is no clear cut definition such that if the amount of data is X go for list or grid but the developer has to take a call based on his experience. If not sure, then list is the better option

REUSE_ALV_COMMENTARY_WRITEThis is used in the Top-of-page event to print the headings and other comments for the list.Important ParametersIt_list_commentary : Internal table with the headings of the type slis_t_listheader.This internal table has three fields:Typ :

• ‘H’ – header, • ‘S’ – selection, • ‘A’ – action

Key: only when typ is ‘S’.Info : the text to be printed

Block ReportThis looks like a simple report but this report has the features of sorting and filtering only.

This report is used if you have to display more than one report on the output. Technically speaking if you have multiple internal tables with data to be displayed as separate blocks then we go for block report of ALV.

The important functions used for creating this report are:• REUSE_ALV_BLOCK_LIST_INIT• REUSE_ALV_BLOCK_LIST_APPEND• REUSE_ALV_BLOCK_LIST_DISPLAY

REUSE_ALV_BLOCK_LIST_INITThis function module is used to set the default gui status etc. The parameters are similar to

the one used in reuse_alv_list_display or reuse_alv_grid_displayREUSE_ALV_BLOCK_LIST_APPENDThis function module adds the data to the block.Important Parameters

Export:• is_layout: layout settings for block• it_fieldcat: field catalog• I_tabname: internal table name with all possible events

Tables:• t_outtab: internal table with output data.

REUSE_ALV_BLOCK_LIST_DISPLAYThis function module displays the list with data appended by the above function.Parameters: All the parameters are optional.

Hierarchical Reports

Page 35: Abap in-4-hours[1]

Hierarchical display is used for displaying data that are related. Like sales order and item details. Here sales order details can be the header data whereas them items in the sales order can be the item data

The function module used for this isREUSE_ALV_HIERSEQ_LIST_DISPLAY

Export:• I_CALLBACK_PROGRAM• I_CALLBACK_PF_STATUS_SET• I_CALLBACK_USER_COMMAND• IS_LAYOUT• It_fieldcat• It_events• I_tabname_header: Name of the internal table in the program containing the output

data of the highest hierarchy level.• I_tabname_item: Name of the internal table in the program containing the output

data of the lowest hierarchy level.• Is_keyinfo: This structure contains the header and item table field names which link

the two tables (shared key).Tables

• t_outtab_header : Header table with data to be output• t_outtab_item : Name of the internal table in the program containing the output data

of the lowest hierarchy level.All the definitions of internal tables, structures and constants are declared in a type-pool

called SLIS. This internal table can be populated automatically by using REUSE_ALV_FIELDCATALOG_MERGE’.Display Variants

Display variants are used to set the default properties of an alv output like sort criteria, filtering criteria, totaling and subtotaling etc

Display variants can be user specific and standard (standard variants can be used by any user )

Kind of display variants that can be saved is controlled by the parameter i_save that is passed in function modules reuse_alv_list_display / reuse_alv_grid_display

You can provide an option on the selection screen to select what display variant to be usedThe common function modules related to selecting / validating display variants are

• Reuse_alv_variant_default_get• Reuse_alv_variant_f4• Reuse_alv_variant_existence

That’s all to ABAP- ALV programming!****

Chapter 12 - All about SAP scriptsSAP script is the SAP System’s own text-processing system. It looks and feels a lot like

other leading text-processing systems.It is used to print preformatted text in pre-formatted forms.

Components of SAP ScriptSAP Scripts comprises of five main components:

Page 36: Abap in-4-hours[1]

An editor for entering and editing the lines of a textStyles and layout sets for print layout. These are created independent of the individual texts

using the corresponding maintenance transactions and are allocated to the texts laterThe composer is a central output module. The SAP script composer is invisible to the

outsideA programming interface that allows you to include SAP script components into your own

application programs and to control the output of layout sets from within the programsSeveral database tables for storing texts, styles and layout sets

Layout SetTo output documents using the programming interface, R/3 application programs need so-

called layout sets (a kind of form).In SAP script a layout set describes the layout of the individual print pages and uses text elements to supply definable output blocks, which a print program can call. A layout set can be defined as a page design for a document

Layout set on its own doesn’t contain any data. The selection of data for the document is done through the print program. The print program selects the data from database table and feeds it to the layout set. When the print program is executed the document is printed on the screen, printer.

Usually a SAP Script Layout consists of following components1. Header Data:

Header data is used for information and control of SAP printing. The header data comprises of 2 parts-

Device Independent :Stores information like Start page, Default paragraph, Language Attributes etc.

Device Dependent: stores information like Page format ,Orientation Lines per inch etc

2. Paragraph and Character Formats: Paragraphs are formatted using various attributes. For instance Standard paragraph attributes specify Left or Right margin, Alignment, Line spacing etc. Font attributes specify Font family, Font size etc. Character formats allow to format entire blocks of text within a paragraph

3. Windows and Text Elements : Windows are individual text areas (header address, date, footer) in a page. It helps combine the information contained in a document into certain groups and make each group appear on the printed page in an individual area. You can define text elements

Page 37: Abap in-4-hours[1]

(window texts) for each window. The print program accesses text elements by name, formats them and prints them in the respective window. The paragraph and the character formats used must be defined in the form.

4. Pages: They are individual pages of a document and must have a unique name. You will often find different layouts for individual pages: The first page of an invoice differs from the subsequent pages, on which you need not repeat general information, such as address or customer data.

5. Page Windows: While defining windows and pages, you do not yet determine the position and spacing of the texts to be output. A page window defines the rectangular output area in the output medium by specifying the left upper edge of the output area and its width and height

Control CommandsThe purpose of “control commands” is to allow control of the output formatting. These

commands are not interpreted by the SAP script editor, but are passed through to the SAP script Composer for processing. This includes, for example, line and page formatting, the formatting of text according to the paragraph and character formats specified.

SyntaxEnter /: in the paragraph formatExamplesNEW-PAGE – Explicit page breakPROTECT ………ENDPROTECT – To print complete paragraph in one page.INCLUDE – To include the content of another text into current textPERFORM – To call a subroutine of any ABAP program

Print ProgramThe execution of script is done through an ABAP program, which is referred as Print

Program. Each print program should have an ENTRY form , which will be called from customization.

For a standard configuration we can see the form name (script name), print program name and output type in the table TNAPR.The print program uses the Form control functions to call the script.

The print program call either all or some of the form control functions to execute the script• OPEN_FORM (Mandatory): Opens the layout set output• CLOSE_FORM (Mandatory): Ends the layout set output• START_FORM (Optional) :Starts a new layout set• WRITE_FORM (Mandatory): Calls a layout set element• END_FORM (Optional): Ends the current layout set

Output TypesThe output type can specify, a printed form that you need for internal use or a form that you

want to send to a customer or vendor. The output type can also be an internal electronic mail message that you want to send to staff in another department.

For example “Print out” can be classified as one output type of a billing document, i.e. when this output type is executed the billing document is printed. Similarly “Fax” can be an output type, i.e. when this output type is executed a fax of the billing document is sent

Page 38: Abap in-4-hours[1]

All the output types for any document (e.g. billing document) will be stored in the table NAST.Output types are executed through the program RSNAST00.

Example: Output type in a billing document-• Go to VF03• Enter billing document number and press enter again• Chose Output under the menu Go to -> Header• Here Z101 is an output type of a print output

Standard Texts and GraphicsStandard Texts for your report can be created using transaction SO10

Graphics and printer macros are uploaded with report RSTXLDMC into individual standard text documents or through transaction SE78. Graphics are uploaded in “Baseline TIFF 6.0″ format (.tif files on PC)

SAP Script & Standard text elements can exported or imported between two systems using RSTXSCRP programCopying Scripts Across clients:

SAP Script is a client dependent object. Unlike programs, changes done to SAP script in one client will not be reflected in other clients. For copying script from one client to another, go to SE71and use “Copy from Client” option available under Utilities menu or import the transport request, in which the script is saved, from the original client using the transaction SCC1.

Important Points to Note• SAP script does not maintain any versions. So when modifying the SAP script,

ensure that the changes are well documented in script. This applies to the standard texts too.

• The output of the form will differ when viewed on the screen and on the printer. So always test the output of the script on the printer.

****Chapter 13 - Smart Forms

SAP Smart Forms is used to create and maintain forms for mass printing in SAP Systems. As output medium SAP Smart Forms support a printer, a fax, e-mail, or the Internet (by using the generated XML output).

SAP introduced Smart Forms in 1998 to overcome the limitations in SAP Scripts. Smart Forms are easier to develop, maintain and transport than SAP Script.Smart Forms and Sap Scripts Comparison

• Multiple page formats are possible in Smart Forms which is not the case in SAP Scripts

• It is possible to have a Smart Form without a main window.• Routines can be written in Smart Forms tool.• Smart Forms generates a function module when activated.

Page 39: Abap in-4-hours[1]

• Labels cannot be created in Smart Forms.Advantages of Smart Forms

• They help adapting forms without any programming knowledge due to entirely graphical user interface

• When activating the smart form the system automatically generates the function module and at the runtime.

• To make any changes we have to use the Drag & Drop, Cut & Paste. These actions do not include writing of coding lines or using a script language.

• We can insert static and dynamic tables. These include the line feeds in the individual table cells, triggering events for table headings and subtotals and sorting data before output.

• The smart forms allow the user to include graphics, which can be displayed as a part of the form or as background graphics. During printout the user can suppress the background graphic as and when necessary.

• Web Publishing is possible using the generated XML outputArchitecture of SAP Smart Form

Smartforms GuideLet’s go through it in SAP system-

• Enter transaction SMARTFORMS in the transaction code box.• In the next screen , enter a from name and click create

Page 40: Abap in-4-hours[1]

• The next screen is divided into three sections-

1. Navigation window -consist of nodes and sub nodes. They contain all the elements (text, window etc) that belong to sap forms

2. Maintenance window- shows attributes of the elements3. Form printer -window shows the layout of the page

Whenever we create smart forms, SAP creates/generates a function module. Unlike SAP scripts , SAP FORMS allow you to change language.

In the navigation window you will find• Global Data Declarations: The Data defined here can be used throughout the smart

form for coding purposes.• Form Interface: Here all the data which will be passed to the smart form from the

Print program is defined.

Page 41: Abap in-4-hours[1]

Right-Clicking on the Pages will allow creation of New Page, Window, Graphic or Address.

Printing will take place on the basis of ‘next page’ field.But processing will happen as per the sequence in navigation window!

Page 42: Abap in-4-hours[1]

For background picture and graphics you can pick up either black and white or color bitmap images and are stored in the form of standard texts. You may take a detour from the smart form screen and open Form Graphics screen. Transaction code: Se78

Setting in the Graphics in Smart Form Window-

Page 43: Abap in-4-hours[1]

Windows in Smart Forms

There are two types of Windows1. Main2. Secondary

Important Points to Note• You cannot have more than 1 main window in a page. You can have multiple

secondary windows• Whatever you print in secondary window…it has to be static. (If u have 20 lines in a

PO and there is page constraint the lines get carried forward to next page in the main window. i.e. In a predecessor and successor type of content, they will be printed in sequence in main window. This is not allowed in Secondary windows.

Page 44: Abap in-4-hours[1]

Inside the main window we can add text as introduction to customize the form output.

The Output options on each window determine the Line size, Width, Colors and background to be put.

Page 45: Abap in-4-hours[1]

A smart form gives the option of giving the address number which is maintained in the central address management. The address will be directly taken from ADRC table and will be populated in the form.

The two different editors are available in Smartforms

Page 46: Abap in-4-hours[1]

1. Normal Editor

2. Graphics Editor.

This setting can be changed using the Configure editor in Utilities.In Table painter, you can draw the format as per client requirement (e.g. Heading, Sub Heading, Item, Sub Total, Grand Total etc.)

Page 47: Abap in-4-hours[1]

You can use the table layout to determine:• The number of lines and cells• The height of each line• The width of each cell• The alignment of the table in the window

• The Table shows the different line types which will be used in the table. The Line types define the size of each cell and the number of cells in each line.

Page 48: Abap in-4-hours[1]

Smart Forms Programming Flow• When an SAP Smart Form template is created, a user creates the form layout, defines

the required fields, conditions, and special programming instructions in the Smart Form template using the Smart Form Builder.

• After the form design is complete, the form needs to be activated before it can be tested or accessed by the print programs. Activating the form initiates the generation of a function module that handles all of the form’s processing.

• This function module interacts with the application program/print program to create the output in the user-defined output media for the specified device.

• In case of smart forms, we use 2 function modules for the processing of the smart form. To the first function module, we pass the name of the smart form as the import parameter. This then returns the name of the dynamically generated function module which will actually call the smart form.

• The smart form name can be passed on to the function Module – ‘SSF_FUNCTION_MODULE_NAME’

Page 49: Abap in-4-hours[1]

• This will return the Function module name of the smart form which is referenced.

• The Print program will be calling the FM ‘SSF_FUNCTION_MODULE_NAME’ to get the Function module name at Runtime. Thereafter it will call the Function module thus obtained to execute the smart form.

Page 50: Abap in-4-hours[1]

Templates• Template can be used when you know the exact size of the output or the output is in

a fixed format.• E.g. Tax form/ cheques /airline form/railway ticket: all these use templates.• The big between table and template is that in a Table the height changes

dynamically. We call a row a ‘line’ in template.

SMART Styles

Page 51: Abap in-4-hours[1]

A Smart Style contains:• Header data containing the default values of a Smart Style• Paragraph formats including indents and spacing, font attributes, tabs, and outline

and numbering• Character formats including effects (superscript, subscript), barcode and font

attributes• Colors and underlines for a paragraph or character format• You can use the transaction ‘smartforms’ / ‘smartstyles’ to create a smart style.

That’s all to this Chapter****

Chapter 14 - Customer and User ExitsWhat is Customer Exits?

Customer exits are “hooks” provided by SAP within many standard programs, screens and menus on which customers may “hang” custom functionality to meet business requirements. More on this in a moment…Types of Customer Exits

There are three main types of customer exits:1. Function Module Exits2. Screen Exits3. Menu exits

Function Module Exit: It allows customer to add code via a function module at a specific location in an SAP application program

Syntax: CALL CUSTOMER-FUNCTION ’004′Menu Exit: It allows customer to add items to a pull down menu in a standard SAP

program. These items may be used to call add-on programs or custom screens.

Page 52: Abap in-4-hours[1]

Format: +CUS (additional item in GUI status)Screen Exit: It allows customer to add fields to a screen in an SAP program via a

subscreen. The subscreen is called within the standard screen’s flow logic.Format: CALL CUSTOMER-SUBSCREEN CUSTSCR2

Examples of Customer Exits Example of a Screen Exit:

In transaction CAT2 – Time Sheet Entry, HR wishes to include an interactive acknowledgment that knowingly submitting incorrect data is grounds for dismissal.

Example of a Menu Exit: In transaction SE38 – ABAP Editor, the development team wishes to include a menu link to transaction SE80 – Object Navigator for ease of use.

Page 53: Abap in-4-hours[1]

BEFORE

AFTER

Example of a Function Module Exit:The company wants the bank details of the Vendors in the Vendor creation to be

Page 54: Abap in-4-hours[1]

mandatory event .So it must flash an error message that ‘Please Enter the bank details’

BEFORE

AFTER

Locating Customer Exits

Page 55: Abap in-4-hours[1]

• In transaction SMOD and look into the details-

• Or in transaction SE81 you can use the appropriate application area

Create a Customer Exit• To create a customer exit you first need to create a project in transaction CMOD

Page 56: Abap in-4-hours[1]

• Later you assign the Customer Exit to your project.What is a USER EXIT?

User Exit serves the same purpose as Customer Exits but they are available only for the SD module. The exit is implemented as a call to a Function Module. The code is written by the developer.

• Well know User Exit in SD is MV45AFZZ• USEREXIT_FIELD_MODIFICATION : To modify screen attributes• USEREXIT_SAVE_DOCUMENT :To perform operations when user hits Save• USEREXIT_SAVE_DOCUMENT_PREPARE• USEREXIT_MOVE_FIELD_TO_VBAK :When user header changes are moved to

header work area.• USEREXIT_MOVE_FIELD_TO_VBAP :When user item changes are moved to

SAP item work area

****

Chapter 15 - BADIBADI stands for Business Add InsJust like Customer Exits, BADI help hook custom enhancements to SAP functionality.Example of a BADI:

In transaction CAT2 – Time Sheet Entry, HR wishes to include an interactive acknowledgment that knowingly submitting incorrect data is grounds for dismissal. This can be achieved using BADI

Page 57: Abap in-4-hours[1]

Features:1. BADI’s are Object Oriented2. They can be implemented multiple times3. It does not require SAP Software Change Registration4. No effect on release upgraded on the functioning of BADI’s

Define and Implement a BAPIThese involved three steps

Step 1 • Creating BADI Definition: Transaction SE18.

Page 58: Abap in-4-hours[1]

Step 2 • Define BADI interface: Transaction SE19

Step 3 • Define a class implements the interface: During implementation creation, a class for

implementing the enhancement’s interface is also created

Page 59: Abap in-4-hours[1]

****Chapter 16 - All About ABAP Query

The ABAP Query application is used to create reports not already present in SAP system. It has been designed for users with little or no knowledge of the ABAP programming.ABAP Query offers users a broad range of ways to define reports and create different types of reports such as basic lists, statistics, and ranked lists.

The ABAP Query comprises four components:1. Queries2. InfoSets3. User Groups4. Translation of Query

Let’s look into them in detail:- Queries The Queries component is used by end users to maintain queries. One can create queries,

change queries and execute queries. Transaction SQ01

InfoSets • InfoSets are special views of data sources. An InfoSet describes which fields of a

data source can be reported on in queries. An InfoSet can be assigned to several roles or user groups.

Advantages - • By creating InfoSets and assigning them to roles or user groups, the system

administrator determines the range of reports that the individual application departments or end-users are able to generate using the SAP Query.

• End-users are able to work only with those InfoSets that are relevant to their particular area, as designated by the role or user group that they are assigned to.

USER Groups • The User Groups component is used to maintain user groups (from a security standpoint).• Users working in the same application are assigned to the same user group. It does not

matter who actually defined a query in a user group. Every user assigned to the user group is able to execute the query.

Page 60: Abap in-4-hours[1]

• Users in a user group need to have the necessary authorizations before they are able to change or redefine a query.Every user in a system can be assigned to several user groups.

Translation/QUERY Component • A lot of texts are generated when defining queries, InfoSets, and user groups. These

texts are displayed in the language that we chose when we log on to the SAP system. We can compare the text/languages using this component.

Data processing in QueriesData can be processed and presented in 3 ways:-

1. BASIC LIST :Presents data in the order defined by the functional area (supports sorting and summation).

2. STATISTIC : Shows the statistical figures calculated from the basic data.3. RANKED LIST : A ranked list is a specialization of a statistic. Ex. Top ten

customers of a travel agency.A query can have one basic list, up to nine statistics and up to nine ranked lists.

CREATING A QUERY Step 1 Go to SQ01. Give a name to the query and click on the Create button.

Step 2 Give the description of the query in the next screen. Specify the output length and select the processing option from the Further Processing Options box. The data can be displayed in various formats such as table, download to a file, and display in Word etc.

Page 61: Abap in-4-hours[1]

Step 3 Click on the next screen, select the field group to be used.

Step 4 Click on the next screen, select the fields you want displayed

Page 62: Abap in-4-hours[1]

Step 5 On the next screen, select the selection fields and then chose one of the output types

(basic, statistics, ranked). In each of the lists, you can select various options. (eg. Sort order of fields, change output length, column color, totals, page header, page footer etc.) .

Page 63: Abap in-4-hours[1]

Step 6After providing all the above options you can save the query and execute it.

Page 64: Abap in-4-hours[1]

Note:• Transaction to Create/Maintain Infoset -SQ02• Transaction to Create/Maintain UserGroup -SQ03

****

Chapter 17 - SAP BDC – Batch Data CommunicationThis Chapter will cover the following topics-

1. Introduction to BDC.2. Method of Batch Input.3. Batch Data Procedures.4. Writing BDC programs.5. Creating Batch input Session.6. Batch Input Recording.

Let’s Begin! Introduction to Batch input • Batch input is typically used to transfer data from non-R/3 systems to R/3 systems or to

transfer data between R/3 systems.• It is a data transfer technique that allows you to transfer datasets automatically to screens

belonging to transactions, and thus to an SAP system. Batch input is controlled by a batch input session.

Batch input session• Groups a series of transaction calls together with input data and user actions . A batch

input session can be used to execute a dialog transaction in batch input, where some or all the screens are processed by the session. Batch input sessions are stored in the

Page 65: Abap in-4-hours[1]

database as database tables and can be used within a program as internal tables when accessing transactions.

Points to note• BDI works by carrying out normal SAP transactions just as a user would but it execute

the transaction automatically. All the screen validations and business logic validation will be done while using Batch Data Input.

• It is suitable for entering large amount of data.• No manual interaction is required

Methods of Batch Input SAP provides two basic methods for transferring legacy data in to the R/3 System.

1. Classical Batch Input method.2. Call Transaction Method.

Classical Batch Input method• In this method an ABAP/4 program reads the external data to the SAP System and stores

in a batch input session.• After creating the session, you can run the session to execute the SAP transaction in it.• This method uses the function modules BDC_ OPEN, BDC_INSERT and BDC_CLOSE• Batch Input Session can be process in 3 ways• In the foreground• In the background• During processing, with error display• You should process batch input sessions in the foreground or using the error display if

you want to test the data transfer.• If you want to execute the data transfer or test its performance, you should process the

sessions in the background.• Points to note about Classical Batch Input method• Asynchronous processing• Transfer data for multiple transactions.• Synchronous database update.• A batch input process log is generated for each session.• Session cannot be generated in parallel.Call Transaction Method.

• In this method ABAP/4 program uses CALL TRANSACTION USING statement to run an SAP transaction.

• Entire batch input process takes place online in the program

Page 66: Abap in-4-hours[1]

Points to Note:• Faster processing of data• Synchronous processing• Transfer data for a single transaction.• No batch input processing log is generated.

Batch Input Procedures

Page 67: Abap in-4-hours[1]

• You will typically observe the following sequence of steps to develop Batch Input for your organization

• Analysis of the legacy data. Determine how the data to be transferred is to be mapped in to the SAP Structure. Also take note of necessary data type or data length conversions.

• Generate SAP data structures for using in export programs.• Export the data in to a sequential file. Note that character format is required by

predefined SAP batch input programs.• If the SAP supplied BDC programs are not used, code your own batch input program.

Choose an appropriate batch input method according to the situation.• Process the data and add it to the SAP System.• Analyze the process log. For the CALL TRANSACTION method, where no proper log is

created, use the messages collected by your program.• From the results of the process analysis, correct and reprocess the erroneous data. Writing BDC program

• You may observe the following process to write your BDC program• Analyze the transaction(s) to process batch input data.• Decide on the batch input method to use.• Read data from a sequential file• Perform data conversion or error checking.• Storing the data in the batch input structure, BDCDATA.

Page 68: Abap in-4-hours[1]

• Generate a batch input session for classical batch input, or process the data directly with CALL TRANSACTION USING statement.

Batch Input Data Structure Declaration of batch input data structureDATA: BEGIN OF <bdc table>OCCURS <occurs parameters>.INCLUDE STRUCTURE BDCDATA.DATA: END OF <bdc table>.Field name Type Length DescriptionPROGRAM CHAR 8 Module poolDYNPRO NUMC 4 Dynpro numberDYNBEGIN CHAR 1 Starting a dynproFNAM CHAR 35 Field nameFVAL CHAR 80 Field valueThe order of fields within the data for a particular screen is not of any significance

Points to Note• While populating the BDC Data make sure that you take into consideration the user

settings. This is especially relevant for filling fields which involves numbers (Like quantity, amount ). It is the user setting which decides on what is the grouping character for numbers E.g.: A number fifty thousand can be written as 50,000.00 or 50.000,00 based on the user setting.

• Condense the FVAL field for amount and quantity fields so that they are left aligned.• Note that all the fields that you are populating through BDC should be treated as

character type fields while populating the BDC Data table.• In some screens when you are populating values in a table control using BDC you

have to note how many number of rows are present on a default size of the screen and code for as many rows. If you have to populate more rows then you have to code for “Page down” functionality as you would do when you are populating the table control manually.

• Number of lines that would appear in the above scenario will differ based on the screen size that the user uses. So always code for standard screen size and make your BDC work always in standard screen size irrespective of what the user keeps his screen size as.

Creating Batch Input Session • Open the batch input session using function module BDC_OPEN_GROUP.• For each transaction in the session:• Fill the BDCDATA with values for all screens and fields processed in the

transaction.• Transfer the transaction to the session with BDC_INSERT.• Close the batch input session with BDC_CLOSE_GROUP

Batch Input Recorder • Batch input recorder (System > Services > Batch input > Recorder) records

transactions which are manually entered and creates a batch input session which can be executed later using SM35.

Page 69: Abap in-4-hours[1]

• Begin the batch input recorder by selecting the Recording pushbutton from the batch input initial screen.

• The recording name is a user defined name and can match the batch input session name which can be created from the recording.

• Enter a SAP transaction and begin posting the transaction.• After you have completed posting a SAP transaction you either choose Get

Transaction and Save to end the recording or Next Transaction and post another transaction.

• Once you have saved the recording you can create a batch input session from the recording and/or generate a batch input program from the recording.

• The batch input session you created can now be analyzed just like any other batch input session.

• The program which is generated by the function of the batch input recorder is a powerful tool for the data interface programmer. It provides a solid base which can then be altered according to customer requirements.

****Chapter 18 - What is EDI, ALE and iDOC?

EDI, stands for Electronic Data Interchange, is the electronic exchange of structured business data between different applications.EDI Architecture

Page 70: Abap in-4-hours[1]

EDI Architecture consists of -• EDI-enabled applications: They support the automatic processing of business

transactions.• The IDoc interface: This was designed as an open interface. The IDoc interface

consists of IDoc types and function modules that form the interface to the application.

• The EDI subsystem: This converts the IDoc types into EDI message types and vice versa. This component of the EDI architecture is not supplied by SAP.

Advantages of EDI process• Reduced data Entry Errors• Reduced Processing cycle time• Availability of data electronic form• Reduced Paper Work• Reduced Cost• Reduced Inventories and Better Planning• Standard Means of Communicating• Better Business Processes• Competitive Advantage

What is ALE?ALE supports the distribution of the business functions and process across loosely coupled

SAP R/3 systems (different versions of SAP R/3). A connection from R/2 and non-SAP systems is also supported.

ALE supports-• Distribution of applications between different releases of R/3 Systems

Page 71: Abap in-4-hours[1]

• Continued data exchange after a release upgrade without requiring special maintenance

• Customer-specific extensions.• Communication interfaces that allow connections to non-SAP systems.• Coupling of R/3 and R/2 Systems.

Difference between ALE and EDI?• ALE is used to support distributed yet integrated processes across several SAP

systems whereas EDI is used for the exchange of business documents between the systems of business partners (could be non-SAP systems)

• ALE is SAP’s technology for supporting a distributed environment whereas EDI is a process used for exchange of business documents which now have been given a standard format

• Both ALE and EDI require data exchange. An Idoc is a data container which is used for data exchange by both EDI and ALE processes.

What is IDOC?• IDOC is simply a data container used to exchange information between any two

processes that can understand the syntax and semantics of the data.• In simple words, an idoc is like a data file with a specified format which is

exchanged between 2 systems which know how to interpret that data.• IDOC stands for” Intermediate Document”• When we execute an outbound ALE or EDI Process, an IDOC is created. In

an inbound ALE or EDI process, an IDOC serves as input to create an application document. In the SAP System, IDOCs are stored in database. Every IDOC has an unique number (within a client).

• IDOCs are based on EDI standards, ANSI ASC X12 and EDIFACT. In case of any conflict in data size, it adopts one with greater length. IDOCs are independent of the direction of data exchange e.g. ORDERS01: Purchasing module: Inbound and Outbound. IDOCs can be viewed in a text editor. Data is stored in character format instead of binary format. IDOCs are independent of the sending and receiving systems.(SAP-to-SAP as well as Non-SAP)

****

Chapter 19 - IDOC: Definition, Architecture, ImplementationWhat is an IDOC?

• IDOC is simply a data container used to exchange information between any two processes that can understand the syntax and semantics of the data.

• In other words, an IDOC is like a data file with a specified format which is exchanged between 2 systems which know how to interpret that data.

• IDOC stands for” Intermediate Document”• When we execute an outbound ALE or EDI Process, an IDOC is created.• In the SAP System, IDOCs are stored in database. Every IDOC has an unique

number (within a client).Key Features

Page 72: Abap in-4-hours[1]

• IDOCs are independent of the sending and receiving systems.(SAP-to-SAP as well as Non-SAP)

• IDOCs are based on EDI standards, ANSI ASC X12 and EDIFACT. In case of any conflict in data size, it adopts one with greater length.

• IDOCs are independent of the direction of data exchange e.g. ORDERS01 : Purchasing module : Inbound and Outbound

• IDOCs can be viewed in a text editor. Data is stored in character format instead of binary format.

Structure of an IDOC

The Idoc structure consists of 3 parts -1. The administration part (Control Record)- which has the type of idoc, message

type, the current status, the sender, receiver etc. This is referred to as the Control record.

2. The application data (Data Record) – Which contains the data. These are called the data records/segments.

3. The Status information (Status Record)- These give you information about the various stages the idoc has passed through.

You can view an IDOC using transaction WE02 or WE05

Page 73: Abap in-4-hours[1]

As seen in screenshot above IDOC record has three parts Control, Data and Status. Let’s look into them in detail -

Control Record • All control record data is stored in EDIDC table. The key to this table is the IDOC

Number• It contains information like IDOC number, the direction (inbound/outbound), sender,

recipient information, channel it is using, which port it is using etc.• Direction ’1′ indicates outbound, ’2′ indicates inbound. Data Record • Data record contains application data like employee header info, weekly details, client

details etc• All data record data is stored in EDID2 to EDID4 tables and EDIDD is a structure where

you can see its components.• It contains data like the idoc number, name and number of the segment in the idoc, the

hierarchy and the data• The actual data is stored as a string in a field called SDATA, which is a 1000 char long

field. Status Record

• Status records are attached to an IDOC at every milestone or when it encounters errors.

• All status record data is stored in EDIDS table.• Statuses 1-42 are for outbound while 50-75 for inbound

IDOC TypesAn IDOC Type (Basic) defines the structure and format of the business document that is to

be exchanged. An IDOC is an instance of an IDOC Type, just like the concept of variables and variables types in programming languages. You can define IDOC types using WE30

Page 74: Abap in-4-hours[1]

What is a Segment?• Segment defines the format and structure of a data record in IDOC. Segments are

reusable components.• For each segment SAP creates

1. Segment Type (version independent)2. Segment Definition (version dependent)3. Segment Documentation

• The last 3 characters is the version of the segment• Definitions keep changing as per the version but the segment type remains the same.

Transaction: WE31

What is Extension IDOC type?An IDOC is of 2 types:-

1. Basic2. Extension

Page 75: Abap in-4-hours[1]

SAP provides many a pre-defined Basic IDOC Types which cannot be modified. In case you want to add more data to these restricted basic type you may use an extension type. Most of the times you will NOT use extension.

DocumentationEach IDOC are thoroughly documented in transaction WE60

Page 76: Abap in-4-hours[1]

Message Type• A message represents a specific type of document that is transmitted between two

partners Ex. Orders, orders responses, invoices etc.• An idoc type can be associated with many message types• Also a message type can be associated with different idoc types. Transaction WE81

IDOC Views

Page 77: Abap in-4-hours[1]

• An IDOC type can be used for more than one message type, which results in IDOCs containing more fields than required for a particular message type.

• IDOC views are used to improve performance in generating IDOCs to ensure only the relevant segments are filled with data.

• IDOC Views are important only for Outbound Processing.

Partner Profiles• A partner is defined as a business partner with whom you conduct business and

exchange documents• In the partner profile of a partner that we exchange Idocs with, we maintain the

parameters that are necessary for exchanging the data. The transaction used is WE20.

Page 78: Abap in-4-hours[1]

Port• The port defines the technical characteristics of the connection between your SAP

system and the other system you want to transfer data with (subsystem). The port defines the medium in which data is exchanged between the 2 systems.

• There are different types of ports. The 2 most commonly used are the TRFC ports used in ALE and File ports which EDI uses.

• For TRFC ports we have to give the name of the logical destination created using SM59.

• When using file port you can specify the directory where the IDOC file should be placed. The other system or the middleware will pick up the file from here. The Function module can be used to generate a file name for the idoc. While testing you can use “Outbound file” to specify a constant file name. The tab “outbound trigger” can be used to supply information if we want to trigger some processing on the subsystem when an idoc is created at this location. We have to specify the command file name and the directory which has to be run.

Page 79: Abap in-4-hours[1]

This is so CONFUSING!Let’s understand the process of creating an IDOC with an example -

• Whenever a Purchase Order (PO) is created we want to send the IDOC to a vendor.• The PO is sent in the form of an IDOC to the vendor (partner). That partner has to be

EDI enabled in that system. SAP should realize that it could send doc to this vendor electronically.

• The PO sent as an outbound idoc by the customer will be inbound idoc for the vendor. The SAP system on the vendors side can process this to create an application document (a sales order) on their system.

• Quotation, RFQ, PO, SO, Invoice, delivery note etc are some of the commonly exchanged documents through IDOC

• The process of data transfer out of your SAP system is called the Outbound process,

while that of data moving into you SAP system is called Inbound process. As a developer or a consultant who will be involved in setting up theses process for your organization. Here are the steps how to set them up-

The Outbound ProcessSteps Involved -

• Create segments(WE31)• Create an idoc type(WE30)• Create a message type (WE81)• Associate a message type to idoc type(WE82)• Create a port(WE21)• If you are going to use the message control method to trigger idocs then create the

function module for creating the idoc and associate the function module to an outbound process code

Page 80: Abap in-4-hours[1]

• Otherwise create the function module or standalone program which will create the idoc

• Create a partner profile (WE20) with the necessary information in the outbound parameters for the partner you want to exchange the idoc with. Trigger the idoc.

The Inbound ProcessSteps Involved-

• Creation of basic Idoc type (Transaction WE30)• Creating message type (Transaction WE81)• Associating the Message type to basic Idoc type (Transaction WE82)• Create the function module for processing the idoc• Define the function module characteristics (BD51)• Allocate the inbound function module to the message type(WE57)• Defining process code (Transaction WE42)• Creation of partner profile (Transaction WE20)

****

Chapter 20 - All About BAPI• BAPIs are standardized programming interfaces (methods) enabling external

applications to access business processes and data in the R/3 System. They provide stable and standardized methods to achieve seamless integration between the R/3 System and external applications, legacy systems and add-ons.

• BAPIs are defined in the BOR (Business object repository) as methods of SAP business object types that carry out specific business functions. They are implemented as RFC-enabled function modules and are created in the Function Builder of the ABAP Workbench.

• Some BAPIs and methods provide basic functions and can be used for most SAP Business Objects. These are called STANDARDIZED BAPI’s.

List of Standardized BAPIs:1. BAPIs for Reading Data – GetList() , GetDetail() , GetStatus() , ExistenceCheck()2. BAPIs for Creating or Changing Data- Create() ,Change(),Delete() and Undelete() ,3. BAPIs for Mass Processing -ChangeMultiple(), CreateMultiple(), DeleteMultiple().

How to create a BAPIStep 1.

• Go to transaction sw01 (Tools->Business Framework -> BAPI Development ->Business Object builder) .

• Select the business object, according to the functional requirement for which the BAPI is being created.

Page 81: Abap in-4-hours[1]

Step2.• Open the business object in change mode. Then Select Utilities ->API Methods

->Add method. • Then enter the name of the function module and select Continue.

Step 3In the next dialog box, following information needs to be specified:

Page 82: Abap in-4-hours[1]

1. Method : Suggest an appropriate name for the method,2. Texts : Enter description for the BAPI3. Radio buttons: Dialog, Synchronous, and Instance-independent.

BAPI‘s are usually implemented synchronously.

Step 4• To create the method select Yes in the next dialog box.

Page 83: Abap in-4-hours[1]

Step5• After the program has been generated and executed, check the program in the

method just created. Thus, a BAPI is created.

Testing the BAPI• You can test the BAPI by testing the individual method of the Business Object in the

Business Object Builder.(or one can use the transaction ‘SWUD’ to test the method).

Releasing and freezing the BAPI• To release the BAPI, first release the function module (using transaction se37) .• Set the status of the method to ‘released’ in the Business Object Builder (using

transaction SWo1 – Edit-> change status-> released.)• You can also use the BAPI Explorer (Transaction code BAPI) for 360′ view on

BAPI

****Chapter 21 - RFC

What is RFC?• A Remote Function Call(RFC) is a call to a function module running in a system

different from the caller’s. The remote function can also be called from within the same system (as a remote call).The RFC interface provides the ability to call remote functions.

• RFC consists of two interfaces:1. A calling interface for ABAP Programs2. A calling interface for Non-SAP programs.

Page 84: Abap in-4-hours[1]

Any ABAP program can call a remote function using the CALL FUNCTION…DESTINATION

statement. The DESTINATION parameter tells the SAP System that the called function runs in a system other than the caller’s.

Syntax-CALL FUNCTION ‘remotefunction’DESTINATION destEXPORTING f1 =IMPORTING f2 =TABLES t1 =EXCEPTIONS

Logical Destinations are defined via transaction SM59 and stored in Table RFCDESFunctions of the RFC interface

• Converting all parameter data to the representation needed in the remote system• Calling the communication routines needed to talk to the remote system.• Handling communications errors, and notifying the caller, if desired (using

EXCEPTIONS paramater of the CALL FUNCTION).Types of RFC

1. Synchronous RFC – The calling program continues the execution only after the called function is complete.

2. Asynchronous RFC – The calling program continues the execution without waiting for return from the called function.

3. Transactional RFC - The called function module is executed exactly once in the RFC target system. Each function call is seen as a transaction in the target system. Transactional RFCs use the suffix IN BACKGROUND TASK. Eg. : CALL FUNCTION ‘remotefunction’ IN BACKGROUND TASK

How to Code an RFC?1. In the function module attributes tab (transaction code SE37), set the processing type

as Remote-enabled module to create a remote function module.

Page 85: Abap in-4-hours[1]

2. Write the code for the function module.

3. Define the destination of the RFC server in the RFC client system that calls the remote function (via SM59 transaction).

Page 86: Abap in-4-hours[1]

4. Declaring Parameters: All parameter fields for a remote function module must be defined as reference fields, that is, like ABAP Dictionary fields.

5. Exceptions: The system raises COMMUNICATION_FAILURE and SYSTEM_FAILURE internally. You can raise exceptions in a remote function just as you would in a locally called function.

Debugging Remote Function Calls• It is not possible to debug a remote function call to another system.• However, when testing ABAP-to-ABAP RFC calls, you can use the ABAP debugger

to monitor the execution of the RFC function in the remote system.• With remote calls, the ABAP debugger (including the debugging interface) runs on

the local system. Data values and other run information for the remote function are passed in from the remote system.

****

Page 87: Abap in-4-hours[1]

About the Author

Krishna is a Computer Engineer and a SAP Consultant. He has over 8 years of experience working for many MNC’s. Recently , he quit is cushy job and is on a mission to make education fun and free. This book is a step in that direction

Connect with USTwitter : http://twitter.com/SAPTHubFacebook: http://www.facebook.com/pages/Sap-Training-Hub/139632216092864Blog: http://www.saptraininghub.com/