Você está na página 1de 743

Example: Parameters, Write, Data, If-else 28 April

REPORT Z930_PROG2.

*PARAMETERS p_x type i.


*PARAMETERS p_y type i.

PARAMETERS : p_x type i DEFAULT 10 OBLIGATORY,


p_y type i DEFAULT 20.

data gv_r1 type i.


data gv_r2 type i.

*gv_r1=p_x+p_y. "syntax error

gv_r1 = p_x + p_y.


gv_r2 = p_x - p_y.

*write 'sum of two numbers is ',gv_r1. "syntax error


write :/ 'sum of two numbers is ',gv_r1,
/ 'difference of two numbers is ',gv_r2.

uline. "underline
*format color 9. "syntax error
format color 3.
write :/ 'sum of two numbers is ',gv_r1.

if gv_r2 >= 0.
write :/ 'Difference of two numbers is ',gv_r2.
else.
write :/ 'Difference of two numbers is -' no-gap,gv_r2 no-sign LEFT-JUSTIFIED.
endif.
format color off.

Example: Constants

REPORT Z930_PROG3.

data gv_x type i value 10. "declaration and initialization


write :/ gv_x.
gv_x = 56.
write :/ gv_x.
uline.
*constants c_y type i. "syntax error
constants c_y type i value 20.
write :/ c_y.
*c_y = 24. "syntax error

1st May
Example: Selection Screen Radiobuttons

REPORT Z930_PROG4.

*PARAMETERS p_x type i.


*PARAMETERS p_y type i.

PARAMETERS : p_x type i DEFAULT 20 OBLIGATORY,


p_y type i DEFAULT 10 OBLIGATORY.

PARAMETERS : p_r1 RADIOBUTTON GROUP grp1,


p_r2 RADIOBUTTON GROUP grp1,
p_r3 RADIOBUTTON GROUP grp1 DEFAULT 'X',
p_r4 RADIOBUTTON GROUP grp1.

data gv_res type i.

if p_r1 = 'X'.
gv_res = p_x + p_y.
write :/ 'Sum of Two numbers is ',gv_res.
elseif p_r2 = 'X'.
gv_res = p_x - p_y.
if gv_res >= 0.
write :/ 'Difference of Two numbers is ',gv_res.
else.
write :/ 'Difference of Two numbers is -' no-gap,gv_res no-sign LEFT-JUSTIFIED.
endif.
elseif p_r3 = 'X'.
gv_res = p_x * p_y.
write :/ 'Product of Two numbers is ',gv_res.
*else. "(or)
elseif p_r4 = 'X'.
gv_res = p_x / p_y.
write :/ 'Division of two numbers is ',gv_res.
endif.

Example: Selection Screen Checkboxes

REPORT Z930_PROG5.

PARAMETERS : p_x type i,


p_y type i.
PARAMETERS : p_c1 as CHECKBOX default 'X',
p_c2 as CHECKBOX,
p_c3 as CHECKBOX default 'X',
p_c4 as CHECKBOX.

data gv_res type i.

if p_c1 = 'X'.
gv_res = p_x + p_y.
write :/ 'Sum of Two numbers is ',gv_res.
endif.
if p_c2 = 'X'.
gv_res = p_x - p_y.
if gv_res >= 0.
write :/ 'Difference of Two numbers is ',gv_res.
else.
write :/ 'Difference of Two numbers is -' no-gap,gv_res no-sign,

LEFT-JUSTIFIED.
endif.
endif.
if p_c3 = 'X'.
gv_res = p_x * p_y.
write :/ 'Product of Two numbers is ',gv_res.
endif.
if p_c4 = 'X'.
gv_res = p_x / p_y.
write :/ 'Division of two numbers is ',gv_res.
endif.

2nd May

Example: Data Types and System Fields

REPORT Z930_PROG6.

*data gv_x type i DECIMALS 2. "syntax error


data gv_x type i. "declaration
gv_x = 105. "assignment
write gv_x. "display
*gv_x = 123.45. "syntax error
gv_x = '123.45'.
write / gv_x.
gv_x = '123.87'.
write / gv_x.

uline.
data gv_y type p.
gv_y = '123.45'.
write / gv_y.

uline.
data gv_z type p DECIMALS 2.
gv_z = '123.45'.
write / gv_z.

uline.
data gv_m type c.
gv_m = 'Gensoft Technologies'.
write / gv_m.

uline.
data gv_k(10) type c. "array of characters
gv_k = 'Gensoft Technologies'.
write / gv_k.

uline.
data gv_r type string.
gv_r = 'Gensoft Technologies'.
write / gv_r.

uline.
data gv_r1 type d. "date-8 bytes
gv_r1 = sy-datum. "system field for application server current date
write / gv_r1. "ddmmyyyy
write /(10) gv_r1. "dd.mm.yyyy
write /(10) gv_r1 using EDIT MASK '__/__/____'. "dd/mm/yyyy

uline.
data gv_r2 type t. "time-6 bytes
gv_r2 = sy-uzeit. "system field for application server current time
write / gv_r2. "hhmmmss
write /(8) gv_r2. "hh:mm:ss
write /(8) gv_r2 using edit mask '__-__-__'. "hh-mm-ss

uline.
write / sy-repid. "current program name
write / sy-uname. "login user name
write / sy-pagno. "current page no
write / sy-dynnr. "current screen no

Example: Event handling on Selection Screen Radio Buttons

REPORT Z930_PROG7.

PARAMETERS : p_x type i DEFAULT 20,


p_y type i DEFAULT 10.

PARAMETERS : p_r1 RADIOBUTTON GROUP grp1 USER-COMMAND abc,


p_r2 RADIOBUTTON GROUP grp1,
p_r3 RADIOBUTTON GROUP grp1,
p_r4 RADIOBUTTON GROUP grp1.

at SELECTION-SCREEN ON RADIOBUTTON GROUP grp1.


* if sy-ucomm = 'abc'. "not satisfied as function code is always captured in upper case
if sy-ucomm = 'ABC'.
* message 'Selected the Radiobutton' type 'I'. "information msg
if p_r1 = 'X'.
message 'First Radiobutton selected' type 'I'.
elseif p_r2 = 'X'.
message 'Second Radiobutton selected' type 'I'.
elseif p_r3 = 'X'.
message 'Third Radiobutton selected' type 'I'.
elseif p_r4 = 'X'.
message 'Fourth Radiobutton selected' type 'I'.
endif.
endif.

3rd may
Example: Looping Statements, Continue and Exit statements

REPORT Z930_PROG8.

PARAMETERS p_x type i.

data : gv_y type i value 1,


gv_res type i.

write :/ 'While loop...'.


while gv_y <= 10.
gv_res = p_x * gv_y.
write :/ p_x,'*',gv_y,'=',gv_res.
gv_y = gv_y + 1.
endwhile.

uline.
gv_y = 1.
write :/ 'While loop...'.
while gv_y <= 10.
if gv_y ne 4.
gv_res = p_x * gv_y.
write :/ p_x,'*',gv_y,'=',gv_res.
endif.
gv_y = gv_y + 1.
endwhile.

uline.
gv_y = 1.
write :/ 'While loop...'.
while gv_y <= 10.
if gv_y eq 4.
gv_y = gv_y + 1.
continue.
endif.
gv_res = p_x * gv_y.
write :/ p_x,'*',gv_y,'=',gv_res.
gv_y = gv_y + 1.
endwhile.

uline.
write :/ 'DO...enddo..First Syntax..'.
gv_y = 1.
do.
gv_res = p_x * gv_y.
write :/ p_x,'*',gv_y,'=',gv_res.
gv_y = gv_y + 1.
if gv_y > 10.
exit.
endif.
enddo.

write :/ 'After do..enddo'.

uline.
write :/ 'DO...enddo..Second Syntax..'.
gv_y = 1.
do 10 times. "suitable for executing statements repeatedly for fixed no of times
gv_res = p_x * gv_y.
write :/ p_x,'*',gv_y,'=',gv_res.
gv_y = gv_y + 1.
enddo.

Example: Case-Endcase

REPORT Z930_PROG9.

PARAMETERS : p_x type i DEFAULT 10,


p_y type i DEFAULT 5,
p_ch type i.

data gv_res type i.

case p_ch.
when 1.
gv_res = p_x + p_y.
write :/ 'Sum is ',gv_res.
when 2.
gv_res = p_x - p_y.
write :/ 'Difference is ',gv_res.
when 3.
gv_res = p_x * p_y.
write :/ 'Product is ',gv_res.
when 4.
gv_res = p_x / p_y. "quotient
write :/ 'Division is ',gv_res.
when 5.
gv_res = p_x mod p_y. "remainder
write :/ 'Remainder is ',gv_res.
when others.
message 'Please enter choice as 1/2/3/4/5' type 'I'.
endcase.

Example: Check Statement

REPORT Z930_PROG10.

PARAMETERS p_x type i.

data gv_r type i.

gv_r = p_x mod 2.

write :/ 'Before checking condition...'.

check gv_r eq 0.
write :/ 'Even no'.
write :/ 'End of program'.

Example: Field-Symbols

REPORT Z930_PROG11.

data gv_r type i value 10.

*FIELD-SYMBOLS abc. "syntax error

FIELD-SYMBOLS <abc>. "capable of storing any type of data

write :/ 'Integer variable gv_r is ',gv_r,


/ 'Field Symbol <abc> is ',<abc>.

uline.
*<abc> = gv_r. "runtime error-error at assignment

assign gv_r to <abc>.


write :/ 'Integer variable gv_r is ',gv_r,
/ 'Field Symbol <abc> is ',<abc>.

uline.
gv_r = 20.
write :/ 'Integer variable gv_r is ',gv_r,
/ 'Field Symbol <abc> is ',<abc>.

uline.
<abc> = 30.
write :/ 'Integer variable gv_r is ',gv_r,
/ 'Field Symbol <abc> is ',<abc>.

uline.
data gv_m type string value 'Gensoft'.
assign gv_m to <abc>.
write :/ 'Integer variable gv_r is ',gv_r,
/ 'Field Symbol <abc> is ',<abc>,
/ 'String gv_m is ',gv_m.

5th may
Basic Programming Complete Notes

c/c++/java for variable declaration:

int x=10;

char y;

float z;

int x,y,z;

c/c++/java for reading user input:

scanf, cin,System.in.read

c/c++/java for displaying output:

printf,cout,System.out.println

ABAP statements / keywords:

1. Data: used for declaring variables

Syntax:

data [:] <variable name> <type/like> <data type> [value <initial value>]
[decimals <no.of decimals>]....

[ ] --> optional (may / may not be used)

< > --> mandatory / obligatory

Eg: data x type i.

data x type i value 10.

data abc type c.

2. Parameters: generates selection screen for reading user input

Syntax:

parameters [:] <variable name> <type/like> <data type> [default <default value>]
[obligatory] [lower case].....

3. Write: generates List processing screen(output screen) for displaying the result

Syntax:

write [:] <variable> ...........

4. Constants: used for declaring fixed value variables. It must be initialized at the time
of initialization itself.

Syntax:

constant [:] <variable> type <datatype> value <fixed value>.

Conditional statements:

1. if-else

Syntax:

if <condition 1>.

statements.

elseif <condition 2>.

statements.
----

elseif <condition n>.

statements.

else.

statements.

endif.

2. Case-endcase (similar to switch statement in 'C' lang)

Syntax:

case <variable>.

when <value 1>.

statements.

when <value 2>.

statements.

----

when others.

statements.

endcase.

3. Check:

Syntax:

check <condition>.

statements.
Looping statements:

1. While-endwhile

Syntax:

while <condition>.

statements.

endwhile.

2. Do-enddo

Syntax 1:

do.

statements.

<Exit condition>.

enddo.

Syntax 2:

do <n> times.

statements.

enddo.

3. Loop-endloop

syntax:

loop at <int.table> [condition].

statements.

endloop.

4. Select-endselect

Syntax:
select <query>.

statements.

endselect.

Operators in ABAP:

Arithmetic Operators:

+, -, *, / (quotient), mod (remainder)

Logical Operators:

AND, OR

Relational Operators:

Symbolic Format (or) Character Format

< lt (less than)

> gt (greater than)

<= le (less than or equal to)

>= ge (greater than or equal to)

= eq (assignment / equal to)

<> ne (not equal to)

?= Type casting symbol

Standard objects --> are provided by SAP

--> Starts with other than 'Z' / 'Y'

--> read and execute

--> for modification --> need to provide access key

Access key --> 16 digit secured password used for modifying standard objects

--> will be provided by SAP itself (if required)


Custom objects / zee objects --> developed by ABAP consultants on behalf of customer
--> Starts with 'Z' / 'Y'

--> do not require access key for development/modification

Developer access key --> needs to be provided when we are trying to develop first object in the
registered user (one time task)

--> used for authenticating (checking) the user as a registered developer

Package --> it is like a directory / folder which is a collection of objects

--> A object stored in $tmp (local object) cannot be transported

--> A object must be stored in transportable package so that it can be


assigned to a change/transportable request which can be
transported from one client to other

Note: Executable programs starts with 'Report' keyword

Execution of objects:

1. Save (ctrl + s)

2. Check for syntax errors (ctrl + f2)

3. Activate the object (ctrl + f3)

4. Execute the object (f8)

Notes:

1. Parameter variable names should not exceed 8 characters and should not contain
special characters.
2. Parameters / Parameter is the statement used for generating selection screen for
reading the input values
3. Default is the option/addition used as part of parameters statement to provide default
values for selection screen fields
4. Obligatory is the option used as part of parameters statement to make a selection
screen field as mandatory
5. By default, numeric data types (integer(i), packed(p), float(f)) are right-justified and
character data types (character( c ), date (d), time (t) are left-justified).
6. We use : (colon chain operator) as part of ABAP statements whenever we perform
multiple operations using single keyword.
7. To check the DOCUMENTATION (for understanding the syntax of statement and its
related options), put the cursor on the relevant abap statement and press F1 key
8. No standard page heading is the option used as part of report statement to suppress
(remove) the default title display in the list processing screen.
9. To generate selection text for a parameter variable, follow the path given below.
10. To change the Date and time formats display, we can use the addition EDIT
MASK as part of write statement.
11. Integers cannot store decimal values, if any decimal value is stored in integer
variable; it will round off to nearest integer. To store the decimal values, we can use
packed data type and use the addition decimals to specify the no. of decimal positions.

Selection-texts for the selection screen parameter variables:

Develop and activate the program first, choose the menu go to  text elements 
selection texts  under selection texts tab, provide meaningful text for the parameter
variables, activate.

Reference:
ABAP System Fields:

These are provided by SAP itself and they start with SY-….. . The Values for these System fields
are assigned by SAP itself.

Sy-datum  Current application server date

Sy-uzeit  Current Application server time

Sy-repid  Current Program name

Sy-uname  Login user name

Sy-dynnr  current screen no.

Note: By default, selection-screen number is always 1000.

Numeric Values:

By default, Integers cannot store decimal values. If any Decimal value is assigned to
integer variable in single quotes, then the value will be rounded off to the nearest
integer and stored in the integer variable. To store decimal values, we can use P
(Packed) data type and while declaring packed variables, we need to use decimals
addition to specify number of decimal places.

Character Fields:

A variable declared as C (character) can store only single character by default, to store
more number of characters declare the variable as array of characters or as a string data
type.

Selection-screen elements

Selection-screen is used for reading the user input. As part of selection-screen we can design
following selection screen elements.

a. Labels(comment)

b. Input fields

c. Push buttons

d. Checkboxes

e. Radio buttons
f. Blocks

g. Tabbed blocks

h. List box(drop down)

Syntax for selection-screen Blocks:

Selection-screen begin of block <block name> [with frame title <title variable>.

Selection-screen elements.

Selection-screen end of block<block name>.

Syntax for labels(comment):

Selection-screen comment <start position>(<width>) <label variable>.

Syntax for pushbuttons:

Selection-screen pushbutton <start position> <width> <button variable> user-command


<function code>.

Event handling in selection-screen:

As part of ABAP prog.lang, there are many events provided by SAP which are triggered at
different places. These events can be handled to provide dynamic features to the applications;
these events are raised by SAP itself.

As part of selection-screen also, the following are the events:-

1. Initialization.

2. At selection-screen output.

3. At selection-screen on <field>.

4. At selection-screen.

5. At selection-screen on value-request.

6. At selection-screen on help-request.

7. At selection-screen on radio button group


Initialization:

This is the first event triggered/raised whenever a selection-screen is displayed. This event is
triggered only once in the life time of a selection-screen.

This event can be handled to initialize the selection-screen fields.

At selection-screen output:

This event is triggered in the following two cases:

Case 1: Whenever the selection screen is displayed for the first time (triggers after the
initialization event)

Case 2: It is also triggered after the at selection-screen event.

This event can be handled to refresh the selection-screen elements dynamically. i.e screen
refreshing logic should be implemented as part of this event.

Syntax for Selection Screen Radio buttons:

Parameters <radio button name> radiobutton group <group name> [user-command <function
code>].

Eg: Parameters p_r1 radiobutton group grp1.

Note: In a group of radiobuttons, only one radiobutton can be selected.

A Radiobutton will contain either X (or) as values

X indicates  Selected, indicates  Not selected

By Default, First radiobutton in the group will be selected.

At selection-screen on radio button group:

This event is triggered whenever the user selects a radio button in the radio button group of a
selection screen. In this case, the function code of the radio button group is captured in the
system field SY-UCOMM and the radio button value is set to X .

Syntax for Selection screen Checkboxes:

Parameters <Checkbox name> as checkbox [user-command <function code>].

Note: In case of checkboxes on selection-screen, we can select any no. of checkboxes.


A checkbox can contain either X (or) as values

X  selected,  not selected

By Default, None of the checkboxes will be selected.

At selection-screen:

This event is triggered whenever the user selects/deselects a checkbox of a selection screen. In
this case, the function code of the selected / deselected checkbox is captured in the system
field SY-UCOMM and the value of the checkbox is set to X (if selected) otherwise space (if
deselected).

This event is also triggered when the user performs the following actions on the selection
screen field.

a. Clicking a pushbutton.

b. Pressing enter key in the input field.

c. Selecting a value in the drop down.

d. On selection / deselection of a checkbox

At selection-screen on field:

a. This event is triggered whenever the user press enter key in the input field.
b. This event can be handled to validate the field.

Continue Statement:

Whenever continue statement is executed inside a loop, the statements after the continue
statement will be skipped i.e. the rest of the statements will not be executed for the current
iteration and the control jumps to next iteration for condition check. Before the continue
statement is executed, the iteration variable needs to be incremented / decremented
otherwise it leads to infinite execution.

Exit Statement:

Whenever the exit statement is executed inside a loop the control jumps out of the current
loop, if the exit statement is executed independently outside the loop, the control comes out of
the program execution i.e rest of the statements after exit statement will not be executed.

The Difference between While-Endwhile and Do-Enddo is in case of While-endwhile, the


condition is checked first and if it is true, the control enters the while loop and then executes
the statements. In case of Do-endo, the control first enters the do loop, executes the
statements at-least once and then check the condition for continuing the iteration of loop or to
exit the loop.

Check statement is used for condition check. If the check condition is true, it executes the
statements after check otherwise ignores it.

String Functions:

1. Strlen  Returns Length of string


2. Translate  Converts a given string to upper case/lower case
3. Concatenate  Combines multiple strings into single string
4. Split  Splits the given string into multiple substrings based on the delimiter
5. Condense  Removes the blank spaces of a string
6. Replace  Replaces the source pattern of a string with the given target pattern
7. Overlay  Replaces the blank spaces of the source string with the corresponding
positioned character in the target string
8. Shift  shifts the contents of the string to the specified direction and no.of places
9. Unpack  It prefixes the character field containing numeric values with the appropriate
no. of zero s depending on the field width.
10. Pack It removes the leading zero s from the character field containing numeric values

Note: Off-set logic is used for extracting the portion of the string.

Submit, Export and Import keywords:

1. Submit keyword is used for calling a program from another program


2. The addition and return as part of submit statement returns the control back to
calling program otherwise the control remains in called program
3. To exchange data between 2 programs we need to use export and import
statements along with submit statement
4. Export statement writes a variable value to ABAP memory referring to a memory id.
5. Import statement reads the value from ABAP memory by referring to a memory id
6. The life time of ABAP memory is within the session. i.e once the user log off of the
session, the variable values maintained in ABAP memory for that particular session
will be destroyed.

Field-symbols are a special data structure used for holding any kind of data. i.e it is capable of
storing any kind of data. Field-symbol variable must be enclosed between < and > . We use
the keyword assign to assign a variable value to the field-symbol. Once a variable is assigned
to the field-symbol, there will be a pointer link between the variable and field-symbol, so any
changes made to the data of the variable will automatically reflect the value of field-symbol and
vice versa.
Exception Handling:

- An exception is a runtime error which is raised during the program execution.

- If the exception is not handled, the program execution will be terminated.

- Exception handling is a process of handling the Runtime Error s and continue the
program execution without termination.

- The exceptions which are raised by SAP are called as Standard Exceptions.

- These standard exceptions are raised from standard exception classes which start with
Naming convention CX___ .

- We can handle these exceptions by using TRY and CATCH blocks.

- Inside the TRY Block we need to keep those statements where the possible exceptions
might occur.

- The CATCH block is placed immediately after the Try Block; it is responsible for
handling the exceptions by providing appropriate exception handling statements which
can be system defined exception message / user-defined exception message.

- CX_ROOT is common for any exceptions i.e it is super class(parent class) for all
exception classes.

- As part of the catch block we need to provide the exception class name which is
responsible for raising the exception.

- If we are not sure about the exception class, we can give the exception class name as
CX_ROOT .

- CX_ROOT is super class for all the exception classes


6th may
Example: Selection-Screen Blocks, Pushbuttons, Labels, Events  Initialization, At selection-
screen

REPORT Z930_PROG17.

data : gv_res type i,


gv_val type string,
gv_str type string.

SELECTION-SCREEN begin of block bk1 WITH FRAME TITLE t1.

SELECTION-SCREEN begin of line.


SELECTION-SCREEN COMMENT 6(15) lb1.
PARAMETERS p_x type i DEFAULT 10 OBLIGATORY.
SELECTION-SCREEN end of line.

SELECTION-SCREEN begin of line.


SELECTION-SCREEN COMMENT 6(15) lb2.
PARAMETERS p_y type i DEFAULT 5 OBLIGATORY.
SELECTION-SCREEN end of line.
SELECTION-SCREEN end of BLOCK bk1.

SELECTION-SCREEN BEGIN OF BLOCK bk2 with FRAME title t2.


SELECTION-SCREEN PUSHBUTTON 9(12) b1 USER-COMMAND fc1.
SELECTION-SCREEN PUSHBUTTON 23(12) b2 USER-COMMAND fc2.
SELECTION-SCREEN PUSHBUTTON 37(12) b3 USER-COMMAND fc3.
* SELECTION-SCREEN PUSHBUTTON /13(12) b4 USER-COMMAND fc4.
SELECTION-SCREEN skip 2.
SELECTION-SCREEN PUSHBUTTON 13(12) b4 USER-COMMAND fc4.
SELECTION-SCREEN PUSHBUTTON 28(12) b5 USER-COMMAND fc5.
SELECTION-SCREEN end of block bk2.

INITIALIZATION.
* message 'initialization' type 'I'.
lb1 = 'First Number'.
lb2 = 'Second Number'.
t1 = 'Input Values'.
t2 = 'Operations'.
b1 = 'Addition'.
b2 = 'Difference'.
b3 = 'Product'.
b4 = 'Clear'.
b5 = 'Exit'.
at SELECTION-SCREEN.
case sy-ucomm.
when 'FC5'.
leave PROGRAM.
when 'FC4'.
clear : p_x,
p_y.
when 'FC1'.
clear gv_res.
gv_res = p_x + p_y.
* CONCATENATE 'Sum of Two numbers is ' gv_res into gv_str SEPARATED BY space..
gv_val = gv_res.
CONCATENATE 'Sum of Two numbers is ' gv_val into gv_str SEPARATED BY space..
message gv_str type 'I'.
when 'FC2'.
clear gv_res.
gv_res = p_x - p_y.
gv_val = gv_res.
CONCATENATE 'Difference of Two numbers is ' gv_val into gv_str SEPARATED BY space..
message gv_str type 'I'.
when 'FC3'.
clear gv_res.
gv_res = p_x * p_y.
gv_val = gv_res.
CONCATENATE 'Product of Two numbers is ' gv_val into gv_str RESPECTING BLANK
S.
message gv_str type 'I'.
endcase.

Stuctures: 8th may


Example: Declaring Structures and Accessing Structure Fields – Syntax 1

REPORT Z930_PROG18.

* Syntax 1 for declaring structure (work area) (line type) (row type)
data : begin of emp,
empno type i,
ename(20) type c,
empdesig(25) type c,
end of emp.

write :/ 'EMP Structure.....'.


*write :/ empno. "syntax error
write :/ emp-empno,emp-ename,emp-empdesig.

emp-empno = 6.
emp-ename = 'Ravi'.
emp-empdesig = 'Manager'.

write :/ 'EMP Structure.....'.


write :/ emp-empno,emp-ename,emp-empdesig.

emp-empno = 16.
emp-ename = 'Vamshi'.
emp-empdesig = 'Employee'.

write :/ 'EMP Structure.....'.


write :/ emp-empno,emp-ename,emp-empdesig.

Example: Standard Syntax for declaring Structures and Accessing Structure Fields, =
(Assignment), Move and Move-Corresponding statements

REPORT Z930_PROG19.

types : begin of ty_emp, "creates template of fields-memory will not be allocated


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

*ty_emp-empno = 4. "memory will not be allocated for types declaration

data : emp1 type ty_emp,


emp2 type ty_emp.
clear emp1.
emp1-empno = 5.
emp1-ename = 'Ravi'.
emp1-empdesig = 'Manager'.
write :/ 'EMP1 structure.....'.
write :/ emp1-empno,emp1-ename,emp1-empdesig.

write :/ 'EMP2 structure.....'.


write :/ emp2-empno,emp2-ename,emp2-empdesig.

uline.
emp2 = emp1. "assignment operator
write :/ 'EMP2 structure after assignment.....'.
write :/ emp2-empno,emp2-ename,emp2-empdesig.

clear emp2.
write :/ 'EMP2 structure after clear.....'.
write :/ emp2-empno,emp2-ename,emp2-empdesig.

uline.
move emp1 to emp2.
write :/ 'EMP2 structure after move.....'.
write :/ emp2-empno,emp2-ename,emp2-empdesig.

clear emp2.
write :/ 'EMP2 structure after clear.....'.
write :/ emp2-empno,emp2-ename,emp2-empdesig.

uline.
move-CORRESPONDING emp1 to emp2.
write :/ 'EMP2 structure after move corresponding'.
write :/ emp2-empno,emp2-ename,emp2-empdesig.

clear emp2.
write :/ 'EMP2 structure after clear.....'.
write :/ emp2-empno,emp2-ename,emp2-empdesig.

Example: Copying Data between two structures – Different no and Different field names

REPORT Z930_PROG20.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data emp type ty_emp.

clear emp.
emp-empno = 5.
emp-ename = 'Krishna Prasad'.
emp-empdesig = 'Manager'.
write :/ 'EMP structure.....'.
write :/ emp-empno,emp-ename,emp-empdesig.

uline.
types : begin of ty_dept,
deptno type i,
dname(10) type c,
end of ty_dept.

data dept type ty_dept.


write :/ 'DEPT Structure......'.
write :/ dept-deptno,dept-dname.

uline.
dept = emp.
write :/ 'DEPT Structure after assigning emp...'.
write :/ dept-deptno,dept-dname.

clear dept.
write :/ 'DEPT Structure after clear...'.
write :/ dept-deptno,dept-dname.

uline.
move emp to dept.
write :/ 'DEPT Structure after move...'.
write :/ dept-deptno,dept-dname.

clear dept.
write :/ 'DEPT Structure after clear...'.
write :/ dept-deptno,dept-dname.

uline.
move-CORRESPONDING emp to dept.
write :/ 'DEPT Structure after move-corresponding...'.
write :/ dept-deptno,dept-dname.

Example: Move-Corresponding scenario 1 (integer to integer-different field position)

REPORT Z930_PROG21.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data emp type ty_emp.

clear emp.
emp-empno = 5.
emp-ename = 'Krishna Prasad'.
emp-empdesig = 'Manager'.
write :/ 'EMP structure.....'.
write :/ emp-empno,emp-ename,emp-empdesig.

uline.
types : begin of ty_dept,
dname(10) type c,
deptno type i,
empno type i,
end of ty_dept.

data dept type ty_dept.


write :/ 'DEPT Structure......'.
write :/ dept-dname,dept-deptno,dept-empno.

uline.
*dept = emp. "syntax error

* move emp to dept. "syntax error

move-CORRESPONDING emp to dept.


write :/ 'DEPT Structure after move-corresponding...'.
write :/ dept-dname,dept-deptno,dept-empno.
Example: Move-Corresponding scenario 2 (Integer to character)

REPORT Z930_PROG22.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data emp type ty_emp.

clear emp.
emp-empno = 5.
emp-ename = 'Krishna Prasad'.
emp-empdesig = 'Manager'.
write :/ 'EMP structure.....'.
write :/ emp-empno,emp-ename,emp-empdesig.

uline.
types : begin of ty_dept,
dname(10) type c,
deptno type i,
empno(3) type c,
end of ty_dept.

data dept type ty_dept.


write :/ 'DEPT Structure......'.
write :/ dept-dname,dept-deptno,dept-empno.

uline.
*dept = emp. "syntax error

* move emp to dept. "syntax error

move-CORRESPONDING emp to dept.


write :/ 'DEPT Structure after move-corresponding...'.
write :/ dept-dname,dept-deptno,dept-empno.

Example: Move-Corresponding scenario 3 (Character to Integer-Data compatable)

REPORT Z930_PROG23.

types : begin of ty_emp,


empno(3) type c,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data emp type ty_emp.

clear emp.
emp-empno = '5'.
emp-ename = 'Krishna Prasad'.
emp-empdesig = 'Manager'.
write :/ 'EMP structure.....'.
write :/ emp-empno,emp-ename,emp-empdesig.

uline.
types : begin of ty_dept,
dname(10) type c,
deptno type i,
empno type i,
end of ty_dept.

data dept type ty_dept.


write :/ 'DEPT Structure......'.
write :/ dept-dname,dept-deptno,dept-empno.

uline.
*dept = emp. "syntax error

* move emp to dept. "syntax error

move-CORRESPONDING emp to dept.


write :/ 'DEPT Structure after move-corresponding...'.
write :/ dept-dname,dept-deptno,dept-empno.

Example: Move-Corresponding scenario 3 (Character to Integer-Data Not compatable-


Runtime error)

REPORT Z930_PROG24.

types : begin of ty_emp,


empno(3) type c,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.
data emp type ty_emp.

clear emp.
emp-empno = 'A5'.
emp-ename = 'Krishna Prasad'.
emp-empdesig = 'Manager'.
write :/ 'EMP structure.....'.
write :/ emp-empno,emp-ename,emp-empdesig.

uline.
types : begin of ty_dept,
dname(10) type c,
deptno type i,
empno type i,
end of ty_dept.

data dept type ty_dept.


write :/ 'DEPT Structure......'.
write :/ dept-dname,dept-deptno,dept-empno.

uline.
*dept = emp. "syntax error

* move emp to dept. "syntax error

move-CORRESPONDING emp to dept.


write :/ 'DEPT Structure after move-corresponding...'.
write :/ dept-dname,dept-deptno,dept-empno.

STRUCTURES: (WORK AREA / LINE TYPE / ROW TYPE)

 It is user defined data type which is a collection of different types of fields.

 In structures the memory allocation is continuous. All the fields are stored one after the
other.

 The size of the structure is equal to sum of the sizes occupied by structure fields.

 We can access the structure fields by using structure name.

SYNTAX:

DATA: BEGIN OF <STRUCTURE NAME>,


FIELD 1,
FIELD 2,
------------,
FIELD N,
END OF <STRUCTURE NAME>.

Structure can store only one record.

 We use structures whenever we need to capture interrelated information in the form of a


record.

Eg: employee  e p o, e a e, e pdesig, e psal…..


student  stude tid, stude t a e, stude t addr…..
bank  a k a o, a k a .holder a e, a holder addr….

 By default, structure fields are initialized to respective default values based on the data
types.

 At any point of time a structure can store only single record.

COPYING DATA BETWEEN TWO STRUCTURES:

 We can copy the data of one structure to another structure by using assignment operator,
move and move-corresponding statements.

 In case of assignment (=) and move statement, it only checks for corresponding data types
of the fields and not for names and the no of fields. If any one of the corresponding field
data type is not matching it leads to syntax error.

MOVE CORRESPONDING:

It is used to copy the data between dis-similar structures.


It is recommended not to use the move-corresponding statement because of the following 2
reasons.

 It decreases the performance, because each field of the source structure is compared with
all the fields of the target structure which is time consuming and thereby decreases the
performance.
 It may lead to run-time error i.e. While copying the data between two fields it only checks
for matching field s names but not for data types. If data types are not type compatible it
leads to run-time error.
Nested structure:

Declaring a structure inside another structure.

Syntax:

Data : begin of <structure name1>,  outer structure


Field1,
Field2,--------,
Begin of <structurename2>,  inner structure
Field1,
Field 2,
--- ---
End of <structurename2>,
End of <structurename1>.

Accessing outer structure fields


<outer structure> - <field name>

Accessing inner structure fields


<outer structure> - <inner structure> - <field name>

Including Structures inside other structure


Note: We can include one structure inside another structure by using include structure (or)
include type statement. The included structure can be local structure (available in same
object) or a global structure defined in the database.
Standard syntax for declaring structure:
1. Create Types declaration with the required fields

Syntax:
Types: begin of <type name>,
Field 1,
Field 2,
--- --- --
Field n,
End of <type name>.
Note: Types declaration doesn t allocate any memory; it only provides the template of
the fields (field names and their data types). Types keyword is used for creating user-
defined data type.
2. Based on Types declaration, we can create n no. of instances (structures/work
areas)
Syntax:

Data <structure name> type <type name>.


Internal Tables:

 It is a temporary table created in application server.


 The lifetime and scope of the internal table is within the program execution where it is
created. i.e Once the Program execution is completed, the memory allocated for the
internal table will be destroyed.
 Internal table can be created either with header or without header.
 A header of an internal table is like a work area (structure) which can be used to process
the internal table.
 Work area can store only single record.
 The body of the internal table can store multiple records.

Syntax 1: declaring internal tables

Data : begin of <internal table> occurs <n>,

Field1,

Field2,

- - - --,

Field k,

End of <internal table>.

<n>-> ranges from 0,1,2,- -- --- ---

0 -> 8kb,

1 ->16kb,

2-> 24kb,----…multiples of 8

Note: In the above syntax, the occurs <n> will specify the initial amount of memory that
needs to be allocated for the internal table. If the initial memory is utilized, the memory
automatically gets increased to the amount of initial size.

Note:

The above syntax is considered as internal table with header.

 We generally use internal tables to store the data retrieved from database table s,
process the data and then displaying the formatted(processed) data / update it back to
database.
Append :

This statement copies the data from work area to the end of the internal table.

Loop:

This statement is used for processing the internal table.

 Its copies each record from body to header.

 The number of times the loop execution depends upon the loop condition and internal
table data.

SORT:

 Before processing the internal table based on a condition, it is always recommended to


sort the internal table based on the field on which the condition is specified.

 If the sort field is not specified, by default it will be sorted on first character field of
the internal table. If no character fields are available in the internal table, then sorting
will be done on first field of the internal table.

 If the sorting order is not specified, by default sort is in ascending order.

 The index of the internal table starts from 1.

 Sy-tabix is the system field which hold s the index position of the internal table.

 Sy-index is the system field which stores the iteration value for the looping statements
like while end-while and do enddo .

Describe :
This statement counts the no of records of the internal table and stores the count value in the
system field sy-tfill.
If we use the lines addition as part of describe statement, the count value is stored inside the
program variable specified as part of lines addition.
Syntax:
Describe table <internal table> [ lines <variable> ].

Note: Occurs statement in declaring the internal table allocates initial memory for the internal
table, if the initial memory is utilized, the memory automatically gets extended to the amount
of initial size.

Note: We can use loop statement to process all records / records based on range of indexes /
records based on condition.

Second syntax for internal table:-

Data: <internal table> like <existing structure> occurs <n>


[With header line]

In case of above syntax the internal table can be declared either with header or without header.

 The above syntax will copy only the structure but not the data.

 To copy data from one internal table to other internal table we can use either append
lines statement or directly use the = operator / move statement with [ ] (in case of
internal table with headers).

Append lines: It will copy all the records / range of records (based on indexes) from source
to target internal table.

To delete the records from internal tables, we can use the following:

1. Refresh: It will delete all the records; it is always used only on internal table.

2. Clear: It will delete all records, use [ ] (for internal tables with header). Clear can be used
on normal variables or work areas also.

3. Free: It will delete all the records; it is always used only on internal table. The difference
between refresh and free is refresh clears the data but doesn t de-allocate the memory ,
whereas free statement clears the internal table and gets the internal table to initial
state.
4. Delete: Deletes the records of the internal table based on a condition

5. Delete adjacent duplicates: Deletes adjacent duplicate records from internal table
based on the comparing field. The pre-requisite for using this is the data in the internal
table should be sorted based on the comparing field (field specified in delete adjacent
duplicates statement).

 In the first syntax and in second syntax we must use occurs keyword as part of
internal table declaration.

 The occurs keyword will allocate some initial memory; this memory automatically gets
extended depending on the usage.

 If the allocated memory is not utilized, then there will be memory wastage, to avoid this
we can use following standard syntax .

Standard syntax of declaring the internal table:

Step 1: Declare the required fields using the type s declaration. This declaration
provides a template of the internal table and work area.
Syntax:

Types : begin of <type name>,


Field1,
Field 2,
- - - ---,
Field n,
End of <type name>.

Note: Types keyword is used for creating a user defined data type. It doesn t allocate any
memory, it only provides template of the fields (field name, field type)

Step 2: Declare the internal table based on types declaration


Syntax:

Data : <internal table> type <standard table of>/<sorted table of>/ <hashed table of>
<type name> [with header line].
Note: The default internal table type is standard .
In the above syntax if the internal table is declared without header then perform step 3.

Step 3:

Declare the work area based on types declaration.

 This work area (structure) can be a normal work area or a field symbol work area.

Syntax for normal work area:-

Data <work area> type <type name>.

Syntax for field-symbol work area:-

Field-symbols <<field symbol variable>> like line of <internal table>.

Note: If we use normal work area as part of loop, we need to use into and if we use field-
symbol work area as part of loop, we need to use assigning keyword.

 It is always recommended to declare the internal table without header

 To process this internal table we need to declare explicit work area.

Standard Internal tables:


1. Key specification is optional
2. Supports only non-unique key specification
3. Sort without the sorting field will sort the data on key specification field (if declared)
otherwise it sorts on first character field of the internal table (if available) otherwise first
field of the internal table
4. Append and Insert statements are supported, Append statement always adds data to
the end of the internal table and insert can be used to add the data either at the end or
in a specific index position of a internal table
5. Supports indexed search, linear search (default), binary search
Read statement:

 It is used for reading specific record from the internal table.

 It always read s single record.

 If the read is successful the system field Sy-subrc is set to 0. Other wise 4.

 Sy-subrc is a system field used for storing the execution status of ABAP statements.

 Read statement can be used either based on the index or based on a condition.

Note: If the read is successful, sy-subrc is set to zero and the content of the record read
is copied to work area specified in read statement

 Before/while using Read statement, it is recommended to perform the following to


improve the performance:
 A) Sort the internal table based on search field
 B) Use the transporting addition as part of read statement to transport only specific
fields from body to work area; otherwise all fields are transported from body to work
area.
 C) Use the addition binary search in the read statement to minimize the search, before
that, sort the internal table based on search field; otherwise using binary search doesn t
have any effect.
 Use the addition transporting no fields as part of read statement when we need to
check only the existence of the record but not interested in the content of the record. In
this, it is better not to specify any work area as part of read statement as we are not
transporting any data from body to work area, otherwise it leads to warning.
 It is always recommended to clear the variable values before using them, otherwise if
the variable is used as it is, it refers to previous value (last value stored in the variable)
which leads to data inconsistency. Here a variable can be an individual variable or work
area.

Modify statement:

This statement is used for updating the internal table as well as database table. In case
of modifying the internal tables we need to modify referring to work area.
 As part of using modify statement it is always recommended to use transporting
option so that only the fields specified in the transporting addition/option will be
compared between work area and corresponding record in the internal table body. If
the transporting option is not specified, all the fields will be compared between work
area and body which decreases performance.
 Using the modify statement inside a loop will decrease the performance.
 To overcome this, it is recommended to use the following:
 A) Field symbol work area instead of normal work area so that any changes made to the
data of the field-symbol work area will automatically update the corresponding row in
the internal table (field-symbol work area will act as pointer). i.e explicitly we need not
use the modify statement.
 B) Use modify statement outside loop using where clause referring to work area.

Sorted internal tables:


1. Key Specification is Mandatory
2. Supports both non-unique and unique key specifications
3. Append and Insert statements are supported, but in case of Append, we need to
ensure the sorting sequence based on key specification field and also provide unique
values for the unique key field, otherwise it leads to runtime error. Because of this
reason, it is recommended to use insert statement on sorted internal tables.
4. If the sorted internal table is declared using unique key specification and if we try to
insert any duplicate entries for the unique key field using insert statement, it ignores
the duplicate entry and considers only the first entry which is inserted.

5. Sort statement is not supported


6. Supports indexed, linear and binary search for searching a record using read
statement

Hashed internal table:

 Key specification is mandatory


 Supports only unique key specification
 Doesn t support explicit or implicit index operations
 i.e. Implicit  Append statement not supported
 Implicit  Read with Binary search not supported
 Explicit  insert with index not supported
 Explicit  Read with index not supported

Small tables  Standard internal tables


Huge tables Hashed internal table
i.e. In case of standard internal tables, time consumed for searching a record depends
on the no. of records/size of internal table.
In case of hashed internal tables, irrespective of no. of records/size of internal table,
time consumed for searching a record is constant.
Example: Internal table declaration, filling data manually and displaying data

REPORT Z930_PROG25.

data : begin of emp occurs 0, "internal table with default header


empno type i,
ename(20) type c,
empdesig(25) type c,
end of emp.

write :/ 'data in default header....'.


write :/ emp-empno,emp-ename,emp-empdesig. "refers to header

emp-empno = 6.
emp-ename = 'Ravi'.
emp-empdesig = 'Manager'.
append emp. "copies data from header to end of internal table body

clear emp.
emp-empno = 16.
emp-ename = 'Ashok'.
emp-empdesig = 'Employee'.
append emp.

clear emp.
emp-empno = 9.
emp-ename = 'Srinivas'.
emp-empdesig = 'Manager'.
append emp.

clear emp.
emp-empno = 11.
emp-ename = 'Praveen'.
emp-empdesig = 'Employee'.
append emp.

clear emp.
emp-empno = 14.
emp-ename = 'Suraj'.
emp-empdesig = 'Manager'.
append emp.

write :/ 'Data in internal table...'.


loop at emp.
write :/ emp-empno,emp-ename,emp-empdesig,sy-tabix.
endloop.

write :/ 'Data in internal table with designation Manager'.


loop at emp where empdesig = 'Manager'.
write :/ emp-empno,emp-ename,emp-empdesig,sy-tabix.
endloop.

write :/ 'Data in internal table from position 2 to 4'.


loop at emp from 2 to 4.
write :/ emp-empno,emp-ename,emp-empdesig,sy-tabix.
endloop.

Example: Sort and describe statements

REPORT Z930_PROG26.

data : begin of emp occurs 0, "internal table with default header


empno type i,
ename(20) type c,
empdesig(25) type c,
end of emp.

emp-empno = 6.
emp-ename = 'Ravi'.
emp-empdesig = 'Manager'.
append emp. "copies data from header to end of internal table body

clear emp.
emp-empno = 16.
emp-ename = 'Ashok'.
emp-empdesig = 'Employee'.
append emp.

clear emp.
emp-empno = 9.
emp-ename = 'Srinivas'.
emp-empdesig = 'Manager'.
append emp.

clear emp.
emp-empno = 11.
emp-ename = 'Praveen'.
emp-empdesig = 'Employee'.
append emp.

clear emp.
emp-empno = 14.
emp-ename = 'Suraj'.
emp-empdesig = 'Manager'.
append emp.

write :/ 'Data in internal table...'.


loop at emp.
write :/ emp-empno,emp-ename,emp-empdesig.
endloop.

sort emp. "sorts on first character field if available, otherwise sorts on first field
write :/ 'Data in internal table after default sort...'.
loop at emp.
write :/ emp-empno,emp-ename,emp-empdesig.
endloop.

sort emp by empno. "sorts on specific field(empno)-ascending


write :/ 'Data in internal table after sorting on employee no...'.
loop at emp.
write :/ emp-empno,emp-ename,emp-empdesig.
endloop.

sort emp by empno DESCENDING. "sorts on specific field(empno)-descending


write :/ 'Data in internal table after sorting on employee no in descending order...'.
loop at emp.
write :/ emp-empno,emp-ename,emp-empdesig.
endloop.

ULINE.
*data gv_cnt type i.
*describe table emp lines gv_cnt.
*write :/ 'No of records in emp...',gv_cnt. "(or)
describe table emp.
write :/ 'No of records in emp...',sy-tfill.

Example: Copying data between internal tables, clearing internal table data
REPORT Z930_PROG27.

data : begin of emp occurs 0,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of emp.

emp-empno = 6.
emp-ename = 'Ravi'.
emp-empdesig = 'Manager'.
append emp.

clear emp.
emp-empno = 16.
emp-ename = 'Ashok'.
emp-empdesig = 'Employee'.
append emp.

clear emp.
emp-empno = 9.
emp-ename = 'Srinivas'.
emp-empdesig = 'Manager'.
append emp.

clear emp.
emp-empno = 11.
emp-ename = 'Praveen'.
emp-empdesig = 'Employee'.
append emp.

clear emp.
emp-empno = 14.
emp-ename = 'Suraj'.
emp-empdesig = 'Manager'.
append emp.

write :/ 'Data in internal table emp...'.


loop at emp.
write :/ emp-empno,emp-ename,emp-empdesig.
endloop.

uline.
data emp2 like emp OCCURS 0 WITH HEADER LINE. "copies only fields(structure)
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2....',sy-tfill.

uline.
emp2 = emp. "copies data from header to header
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2....',sy-tfill.

uline.
emp2[] = emp[]. "copies data from body to body
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2....',sy-tfill.

uline.
clear emp2. "clears header
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2 after clear....',sy-tfill.

uline.
clear emp2[]. "clears body
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2 after clear[]....',sy-tfill.

uline.
append lines of emp to emp2.
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2 after append lines....',sy-tfill.

uline.
refresh emp2.
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2 after refresh....',sy-tfill.

uline.
append lines of emp from 2 to 4 to emp2.
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2 after append lines from source to target index....',sy-tfill.

uline.
free emp2.
DESCRIBE TABLE emp2.
write :/ 'No of records in emp2 after free....',sy-tfill.
Example: Standard Internal table with default Header line

REPORT Z930_PROG28.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

*data t_emp type STANDARD TABLE OF ty_emp with HEADER LINE. "(or)
data t_emp type TABLE OF ty_emp with HEADER LINE. "default is standard

clear t_emp. "clears header


t_emp-empno = 5.
t_emp-ename = 'Ravi'.
t_emp-empdesig = 'Manager'.
append t_emp.

clear t_emp. "clears header


t_emp-empno = 15.
t_emp-ename = 'Srinivas'.
t_emp-empdesig = 'Employee'.
append t_emp.

clear t_emp. "clears header


t_emp-empno = 3.
t_emp-ename = 'Kiran'.
t_emp-empdesig = 'Employee'.
append t_emp.

clear t_emp. "clears header


t_emp-empno = 9.
t_emp-ename = 'Vamshi'.
t_emp-empdesig = 'Manager'.
append t_emp.

loop at t_emp.
write :/ t_emp-empno,
t_emp-ename,
t_emp-empdesig.
endloop.

Example: Standard Internal table without default Header line, Explicit Normal work area and
Explicit Field-symbol work area

REPORT Z930_PROG29.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data t_emp type TABLE OF ty_emp. "without default header

*clear t_emp. "clears body


*t_emp-empno = 5. "syntax error
data wa_emp type ty_emp. "normal work area
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
*append t_emp. "syntax error
append wa_emp to t_emp.

clear wa_emp. "clears work area


wa_emp-empno = 15.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.
clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

write :/ 'Data in internal table t_emp...'.


*loop at t_emp. "syntax error
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
data t_emp2 type table of ty_emp.
DESCRIBE TABLE t_emp2.
write :/ 'No of records in t_emp2....',sy-tfill.

uline.
append lines of t_emp to t_emp2.
DESCRIBE TABLE t_emp2.
write :/ 'No of records in t_emp2 after appending lines of t_emp....',sy-tfill.

uline.
write :/ 'Data in internal table t_emp2...'.
*loop at t_emp2 into wa_emp.
* write :/ wa_emp-empno,
* wa_emp-ename,
* wa_emp-empdesig.
*endloop. "(or)

FIELD-SYMBOLS <abc> like line of t_emp2. "field symbol work area


*loop at t_emp2 into <abc>. "runtime error
loop at t_emp2 ASSIGNING <abc>.
write :/ <abc>-empno,
<abc>-ename,
<abc>-empdesig.
endloop.

Example: Append Vs Insert on Standard Internal tables

REPORT Z930_PROG30.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data t_emp type TABLE OF ty_emp. "without default header


data wa_emp type ty_emp. "normal work area

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 15.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

write :/ 'Data in internal table t_emp...'.


loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Karan'.
wa_emp-empdesig = 'Manager'.
insert wa_emp into t_emp index 2.

write :/ 'Data in internal table t_emp after insert into index 2..'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

clear wa_emp.
wa_emp-empno = 6.
wa_emp-ename = 'Mani'.
wa_emp-empdesig = 'Manager'.
insert wa_emp into table t_emp.

write :/ 'Data in internal table t_emp after insert ...'.


loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Standard Internal table with non-unique key specification field and behavior of sort
statement

REPORT Z930_PROG31.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data t_emp type TABLE OF ty_emp. "without default header


data wa_emp type ty_emp. "normal work area

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 15.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

write :/ 'Data in internal table t_emp...'.


loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
*data t_emp2 type TABLE OF ty_emp with UNIQUE key empno. "syntax error
data t_emp2 type TABLE OF ty_emp with NON-UNIQUE key empno.
DESCRIBE TABLE t_emp2.
write :/ 'No of records in t_emp2....',sy-tfill.

uline.
append lines of t_emp to t_emp2.
DESCRIBE TABLE t_emp2.
write :/ 'No of records in t_emp2 after append lines....',sy-tfill.

uline.
write :/ 'Data in internal table t_emp2...'.
loop at t_emp2 into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
sort t_emp.
write :/ 'Data in internal table t_emp after default sort...'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
sort t_emp2. "sorts on key field - empno
write :/ 'Data in internal table t_emp2 after default sort...'.
loop at t_emp2 into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Rajesh'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp2.

uline.
write :/ 'Data in internal table t_emp2 after inserting duplicate key field value...'.
loop at t_emp2 into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.
Example: Standard Internal table-Read Statement

REPORT Z930_PROG32.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data t_emp type TABLE OF ty_emp. "without default header


data wa_emp type ty_emp. "normal work area

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 15.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kavitha'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.
write :/ 'Data in internal table t_emp...'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
clear wa_emp.
read table t_emp into wa_emp index 2. "indexed search
if sy-subrc eq 0.
write :/ 'Record with index 2 is found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with index 2 not found...'.
endif.

uline.
clear wa_emp.
sort t_emp by empno.
read table t_emp into wa_emp with key empno = 3. "linear search/sequential search
if sy-subrc eq 0.
write :/ 'Record with empno 3 is found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with empno 3 is not found...'.
endif.

uline.
clear wa_emp.
read table t_emp into wa_emp with key empno = 9
TRANSPORTING empno ename.
if sy-subrc eq 0.
write :/ 'Record with empno 9 is found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with empno 9 is not found...'.
endif.
uline.
*clear wa_emp.
*read table t_emp into wa_emp with key empno = 5
* TRANSPORTING NO FIELDS. "warning because work area is specified
read table t_emp with key empno = 5
TRANSPORTING NO FIELDS.
if sy-subrc eq 0.
write :/ 'Record with empno 5 is found...'.
else.
write :/ 'Record with empno 5 is not found...'.
endif.

uline.
clear wa_emp.
read table t_emp into wa_emp
with key empno = 15 BINARY SEARCH.
if sy-subrc eq 0.
write :/ 'Record with empno 15 is found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with empno 15 is not found...'.
endif.

Example: Sorted Internal tables – Append Statement

REPORT Z930_PROG33.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

*data : t_emp type SORTED TABLE OF ty_emp, "syntax error as key is missing
*data : t_emp type SORTED TABLE OF ty_emp with NON-UNIQUE key empno, "(or)
data : t_emp type SORTED TABLE OF ty_emp with UNIQUE key empno,
wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Mahesh'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Sorted Internal tables – Append Statement – Runtime Error – Sorting Sequence not
ensured

REPORT Z930_PROG34.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data : t_emp type SORTED TABLE OF ty_emp with UNIQUE key empno,
wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Mahesh'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 11.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp. "leads to runtime error as sorting sequence not maintained

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Sorted Internal tables – Insert Statement – Sorting Sequence automatically taken
care by Insert

REPORT Z930_PROG35.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.
data : t_emp type SORTED TABLE OF ty_emp with UNIQUE key empno,
wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Mahesh'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 11.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
*append wa_emp to t_emp. "leads to runtime error as sorting sequence not maintained
insert wa_emp into table t_emp.

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Sorted Internal tables – Append Statement – Runtime Error – Duplicate entries
found for unique key field
REPORT Z930_PROG36.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data : t_emp type SORTED TABLE OF ty_emp with UNIQUE key empno,
wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Mahesh'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Sorted Internal tables – Insert Statement - Duplicate entries ignored for unique key
field by Insert

REPORT Z930_PROG37.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data : t_emp type SORTED TABLE OF ty_emp with UNIQUE key empno,
wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Mahesh'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
*append wa_emp to t_emp. "leads to runtime error as duplicate key field value found
insert wa_emp into table t_emp.

*SORT t_emp by ename. "syntax error

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Sorted Internal tables – Read Statement

REPORT Z930_PROG38.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data : t_emp type SORTED TABLE OF ty_emp with UNIQUE key empno,
wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Mahesh'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.
clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 10.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
*insert wa_emp into t_emp index 3. "runtime error
insert wa_emp into t_emp index 4.

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
clear wa_emp.
read table t_emp into wa_emp index 2. "indexed search
if sy-subrc eq 0.
write :/ 'Record with index 2 found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with index 2 not found...'.
endif.

uline.
clear wa_emp.
read table t_emp into wa_emp with key empno = 10. "linear search
if sy-subrc eq 0.
write :/ 'Record with empno 10 found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with empno 10 not found...'.
endif.

uline.
clear wa_emp.
read table t_emp into wa_emp with key empno = 10 BINARY SEARCH. "binary search
if sy-subrc eq 0.
write :/ 'Record with empno 10 found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with empno 10 not found...'.
endif.

Example: Hashed Internal tables

REPORT Z930_PROG39.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

*data : t_emp type HASHED TABLE OF ty_emp, "syntax error


*data : t_emp type HASHED TABLE OF ty_emp with NON-UNIQUE key empno, "syntax error
data : t_emp type HASHED TABLE OF ty_emp with UNIQUE key empno,
wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
*append wa_emp to t_emp. "syntax error
insert wa_emp into table t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Mahesh'.
wa_emp-empdesig = 'Employee'.
insert wa_emp into table t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Manager'.
insert wa_emp into table t_emp.
clear wa_emp.
wa_emp-empno = 14.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
insert wa_emp into table t_emp.

clear wa_emp.
wa_emp-empno = 10.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
insert wa_emp into table t_emp.

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

sort t_emp.
uline.
write :/ 'Data after default sort....'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
clear wa_emp.
*read table t_emp into wa_emp index 2. "syntax error

read table t_emp into wa_emp with key empno = 10. "linear search
if sy-subrc eq 0.
write :/ 'Record with empno 10 found...'.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
else.
write :/ 'Record with empno 10 not found...'.
endif.

*read table t_emp into wa_emp with key empno = 10 BINARY SEARCH. "syntax error
Example: Modifying content of internal tables

REPORT Z930_PROG40.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data t_emp type TABLE OF ty_emp. "without default header


data wa_emp type ty_emp. "normal work area

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 15.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kavitha'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.
clear wa_emp.
wa_emp-empno = 34.
wa_emp-ename = 'Kamal'.
wa_emp-empdesig = 'Supervisor'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 1.
wa_emp-ename = 'Kranthi'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 27.
wa_emp-ename = 'Ram'.
wa_emp-empdesig = 'Supervisor'.
append wa_emp to t_emp.

write :/ 'Data in internal table t_emp...'.


loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

loop at t_emp into wa_emp where empdesig = 'Manager'.


wa_emp-empdesig = 'Sr.Manager'.
* modify t_emp from wa_emp. "by default it compares all fields between work area and corres
ponding record in body
modify t_emp from wa_emp TRANSPORTING empdesig.
endloop.

uline.
write :/ 'Data in internal table t_emp after using modify inside loop...'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
FIELD-SYMBOLS <abc> like line of t_emp.
loop at t_emp ASSIGNING <abc> where empdesig = 'Employee'.
<abc>-empdesig = 'Sr.Employee'.
endloop.

write :/ 'Data in internal table t_emp after changes to field symbol work area...'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

uline.
clear wa_emp.
wa_emp-empdesig = 'Sr.Supervisor'.
modify t_emp from wa_emp TRANSPORTING empdesig
where empdesig = 'Supervisor'.

write :/ 'Data in internal table t_emp after using modify with where clause...'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Deleting content of internal tables

REPORT Z930_PROG41.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data t_emp type TABLE OF ty_emp. "without default header


data wa_emp type ty_emp. "normal work area

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 15.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kiran'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 9.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Kavitha'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 34.
wa_emp-ename = 'Kamal'.
wa_emp-empdesig = 'Supervisor'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 87.
wa_emp-ename = 'Soujash'.
wa_emp-empdesig = 'CEO'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 1.
wa_emp-ename = 'Kranthi'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 67.
wa_emp-ename = 'Rajneesh'.
wa_emp-empdesig = 'CEO'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 27.
wa_emp-ename = 'Ram'.
wa_emp-empdesig = 'Supervisor'.
append wa_emp to t_emp.

write :/ 'Data in internal table t_emp...'.


loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

delete t_emp where empdesig = 'CEO'.

uline.
write :/ 'Data after deleting CEOs...'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

sort t_emp by empdesig.


delete ADJACENT DUPLICATES FROM t_emp COMPARING empdesig.

uline.
write :/ 'Data after using deleteing adjacent duplicate empdesig.....'.
loop at t_emp into wa_emp.
write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.
DEBUGGING

It is the process of checking the flow of program execution step by step

 To take the program to Debugging mode we need to set Break points in the
program.
 A breakpoint is a signal to the system which stop s the program execution whenever it is
encountered.
 We can set the breakpoint s in two ways:

1. Manually by clicking set breakpoint option on appl.toolbar


2. By using keyword Breakpoint .

We can set the break-points only in active mode of a program.

Navigation͛s in debugging mode:

F5 (Single step):
It executes single step at a time.

F6 (Execute):
It is similar to F5 but when F6 is pressed at the time of calling the block s (subroutine,
function module, method); the entire block will be executed as a single step without the
control going to block definition.

F7 (Return):
When F7 is pressed inside a block definition the control comes out
of the current block by executing the remaining steps of the block as a single step.

F8 (run to):

Whenever F8 is pressed, the control jumps to the next breakpoint if available,


otherwise it executes the remaining steps of the program as a single step.

Note: We cannot debug the variable declarations; we can debug only the executable
statements.
 It is recommended not to set the break-points by using break-point keyword. Because
there is a possibility that developer might forgot to remove the break-point keyword
before transporting the object to next configured client.
 If it is transported as it is, the program execution will be halted and the control will be
taken to debugging mode which is an escalation in quality/production system.

WatchPoints: are created in the debugging mode to provide conditional break-point.


Whenever the watchpoint condition is reached, the program execution will be stopped
from where we can continue to debug the statements.

MODULARIZATION TECHNIQUES

Modularization is the process of breaking the program into multiple blocks.

A block is a set/collection of statements which is defined only once and can be called / accessed
any no. of times.

Advantages of Modularization:

 Increases reusability.

 Efficient control on the flow of program execution.

 Maintenance cost is decreased.

Following are the Modularization techniques:

 Subroutines

 Include programs

 Macros(HR-ABAP)

 Function modules

 Methods(OOPS ABAP)

Subroutines:

It is a block of statements, which is defined only once and can be called any number of times.

Subroutine can be created either with parameters or without parameters.

A subroutine is associated with 2 sections.

 Defining the subroutine

 Calling the subroutine


Subroutine as to be defined at the end of the program.

Whenever a subroutine is called the control jumps to subroutine definition.

There are two types of subroutines.

 Internal subroutine

 External subroutine

Internal subroutine:

It is defined as well as called from the same program.

Syntax for defining internal/external subroutine:

Form <subroutine> [ parameters list]

statements.

Endform.

Syntax for calling internal subroutine:

perform <subroutine> [parameters list]

External subroutine:

They are defined in external programs and called from other programs.

The external program can be another executable program or a subroutine pool.

Subroutine pool:

It is a repository object which is a collection of one or more external subroutines

Syntax for calling external subroutines:

Syntax 1

Perform <subroutine> in program <external program> [parameters list].

Syntax 2

Perform <subroutine> (<external program>) [parameters list].

Note: External program can be either another executable program or subroutine pool.

Subroutines with parameters( for data exchange and manipulation)

We can define subroutines with parameters.


For this we use the following keywords.

1. Using

2. Changing

3. Tables

The parameters specified as part of subroutine definition are called as formal parameters and
the parameters specified at the time of calling the subroutine are called as actual parameters.

Using:

Using is the keyword used as part of subroutine definition and subroutine calling to deal with
standard data types as parameters.

The formal parameters and actual parameters names can be same or different.

The number of formal parameters depends upon the number of actual parameters.

Subroutines returning values:

For this we can use the keywords changing or tables.

The number of return parameters depends upon number of changing and tables parameters.

The changing and tables parameters can be used for both passing the values as well as
returning the values.

We can pass parameters to subroutines in two ways.

1. Pass by reference (default).

2. Pass by value.

Pass by reference:

In this, the address of actual parameters are copied to formal parameters. So, any changes
made to the formal parameters variables will automatically reflect the content of the actual
parameters.

Pass by value:

In this the values of actual parameters are copied to formal parameters. So, any changes made
to the data of formal parameters will not reflect the content of the actual parameters. For this,
we need to use the keyword value as part of formal parameters.

Internal tables as parameters to subroutines:


We need to use tables keyword as part of subroutine call and subroutine definition to deal with
internal tables as parameters to subroutines.

In this case, if we perform the operations like delete and modify on formal internal table with
where clause, we must specify the structure of the formal internal table and it is done by using
the keyword structure as part of subroutine definition.

In this case, any changes made to the data of the formal internal table, will automatically reflect
actual internal table data.

Internal tables are always passed by reference.

INCLUDE PROGRAMS:

It is a reusable repository object, which can be used for declaring global variables, subroutines,
module definitions and class definitions.

To use the components of include program inside other repository objects, we must include the
include program by using include keyword.

Syntax:

Include <include name>.

It is recommended to include the include program at the beginning of the repository object.

If the include program contains any block definitions (subroutine or module definitions or class
definitions) and if the include program is included at the beginning of the executable program,
it leads to syntax error statement is not accessible . To avoid this, explicitly we need to handle
the event ͞start-of-selection͟ after include statement to indicate the starting point of program
execution.

Start-of-selection event should be handled after the include statement.

Start-of-selection event indicates starting point of program execution.

Function modules:

It is a set of statements which are defined only once and can be called any no. of times. We can
create custom function modules by using function builder tool (se37).

There are many standard function modules provided by SAP itself. These function modules can
be called/accessed in different programs by passing values to the appropriate parameters.

Function modules (custom/standard) are stored inside function group.

Function group is a container of function modules.

Table for function module-> TFDIR (accessed from SE11)


Table for repositor o je ts e e uta le, in lude, su routine pool… - TADIR

Table for SAP Tables  DD02L

Function group:

Before creating custom function module, we need to create or consider a function group which
already exists.

Function group can be created either by se80 (object navigator) / se37.

In SE37, choose the menu GOTO  function groups  create group

Whenever a function group is created, SAP creates two include programs.

A. Include ending with ͚TOP͛:

This is called as top include program, which can be used for declaring global variables,
subroutine, module definitions and class definitions.

The components of the top include program can be accessed by all the function modules of
that particular function group.

B. Include ending with ͚UXX͛

It is reserved for SAP internal use. As part of this include, SAP generates sub includes (i.e),
whenever a new function module is created, a sub include will be generated on behalf of that
function module.

The no of sub includes depends upon the no. of function modules of that function group.

Syntax for defining function module:

Function <function name>.

Statements.

Endfunction.

Syntax for calling normal function module:

Call function <function name> <parameter list>.

Before calling any function module, we must check the signature of the function module to
understand the parameter types, return values, default values, pass by value or pass by
reference, optional and mandatory parameters.

As part of function modules we have 4 types of parameters:

1. Import
2. Export

3. Tables

4. Changing

Import parameters:

Are the parameters which are received by the function module.

Export parameters:

Are the parameters which are returned by the function module.

Export parameters are always optional.

Changing parameters:

Acts as both import and export, we go for changing parameters when we need to use same
variable for passing the value as well as receiving the return value.

Tables:

Are used for dealing with internal tables as parameters to function modules , these internal
tables must refer to dictionary structures created in se11.
Example: Internal Vs External Subroutines, Passing parameters to subroutines, Subroutine
pool

Executable program

REPORT Z930_PROG42.

write :/ 'Welcome'.
perform sub1.
write :/ 'Hi'.
perform sub1.
write :/ 'Hello'.
perform sub1.
perform sub2.
write :/ 'Bye'.

uline.
*perform sub3. "syntax error as no internal subroutine sub3 is defined
perform sub3 in program z930_prog43.
perform sub4 in program z930_prog43. "(or)
perform sub4(z930_prog43).

uline.
*perform sub5 using 20 30. "syntax error as no internal subroutine sub5 is defined
perform sub5(z930_subpool) using 20 30. "actual parameters
*perform sub5(z930_subpool) using 12. "syntax error
data : gv_r1 type i value 10,
gv_r2 type i value 5,
gv_r3 type i.
perform sub6(z930_subpool) using gv_r1 gv_r2 CHANGING gv_r3.
write :/ 'Division is ',gv_r3.

form sub2.
write :/ 'Inside subroutine sub2....'.
endform.

form sub1.
write :/ 'CORE ABAP'.
write :/ 'OOPS ABAP'.
write :/ 'CROSS APPS'.
endform.
Executable program containing external subroutines

REPORT Z930_PROG43.

data : gv_x type i value 10,


gv_y type i value 5,
gv_res type i.

write :/ 'inside program 43...'.

form sub3.
gv_res = gv_x + gv_y.
write :/ 'Sum is ',gv_res.
endform.

form sub4.
gv_res = gv_x - gv_y.
write :/ 'Difference is ',gv_res.
endform.

Subroutine pool containing external subroutines

PROGRAM Z930_SUBPOOL.

*write :/ 'hi'. "syntax error

data gv_res type i.

form sub5 using m n. "formal parameters


gv_res = m * n.
write :/ 'Product is ',gv_res.
endform.

form sub6 using m n CHANGING gv_res.


gv_res = m / n.
endform.

Example: Internal tables as parameters to subroutines

REPORT Z930_PROG44.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data : t_emp type table of ty_emp,


wa_emp type ty_emp.

clear wa_emp.
wa_emp-empno = 5.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 8.
wa_emp-ename = 'Srinivas'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 6.
wa_emp-ename = 'Ashok'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 4.
wa_emp-ename = 'Sourabh'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

perform abc tables t_emp.


uline.

DESCRIBE TABLE t_emp.


write :/ 'No of records in t_emp before deleting managers from lt_emp...',sy-tfill.
perform pqr tables t_emp.
DESCRIBE TABLE t_emp.
write :/ 'No of records in t_emp after deleting managers from lt_emp...',sy-tfill.
form abc tables lt_emp.
DESCRIBE TABLE lt_emp.
write :/ 'No of records :',sy-tfill.
endform.

*form pqr TABLES lt_emp. "syntax error


* delete lt_emp where empdesig = 'Manager'.
*endform.

form pqr TABLES lt_emp STRUCTURE wa_emp.


delete lt_emp where empdesig = 'Manager'.
endform.

Example: Passing Parameters by Reference

REPORT Z930_PROG45.

data : gv_x type i value 10,


gv_y type i value 5.

write :/ 'Values of gv_x and gv_y are :',gv_x,gv_y.

perform abc using gv_x gv_y.

write :/ 'Values of gv_x and gv_y after calling subroutine are :',gv_x,gv_y.

form abc using m n. "formal parameters


data lv_z type i. "local variable
lv_z = m.
m = n.
n = lv_z.
endform.

Example: Passing Parameters by Value

REPORT Z930_PROG46.

data : gv_x type i value 10,


gv_y type i value 5.

write :/ 'Values of gv_x and gv_y are :',gv_x,gv_y.

perform abc using gv_x gv_y.

write :/ 'Values of gv_x and gv_y after calling subroutine are :',gv_x,gv_y.
form abc using value(m) value(n). "formal parameters
data lv_z type i. "local variable
lv_z = m.
m = n.
n = lv_z.
endform.
Example: Including Include Program containing only variable declarations

Include Program:

data : gv_x type i,


gv_y type i,
gv_z type i.

types : begin of ty_emp,


empno type i,
ename(20) type c,
empdesig(25) type c,
end of ty_emp.

data : t_emp type table of ty_emp,


wa_emp type ty_emp.

Executable Program:

REPORT Z930_PROG47.

include zincl1.
gv_x = 10.
gv_y = 20.
gv_z = gv_x + gv_y.
write :/ 'Sum is ',gv_z.

uline.
clear wa_emp.
wa_emp-empno = 6.
wa_emp-ename = 'Ravi'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 16.
wa_emp-ename = 'Vamshi'.
wa_emp-empdesig = 'Employee'.
append wa_emp to t_emp.

clear wa_emp.
wa_emp-empno = 3.
wa_emp-ename = 'Manoj'.
wa_emp-empdesig = 'Manager'.
append wa_emp to t_emp.

loop at t_emp into wa_emp.


write :/ wa_emp-empno,
wa_emp-ename,
wa_emp-empdesig.
endloop.

Example: Including Include Program containing variable declarations and subroutine


definitions

Include Program:

data : gv_x type i,


gv_y type i,
gv_z type i.
form sub1.
gv_x = 10.
gv_y = 20.
gv_z = gv_x + gv_y.
write :/ 'sum is ',gv_z.
endform.
form sub2 using m n.
gv_x = m.
gv_y = n.
gv_z = gv_x - gv_y.
write :/ 'Difference is ',gv_z.

endform.

Executable Program:

REPORT Z930_PROG48.

include zincl2.
START-OF-SELECTION.
write :/ 'Begin of executable program....'.
perform sub1.
*perform sub2. "syntax error
perform sub2 using 10 2.
Example: Calling Function Module without any parameters

Function Module Source code (SE37):

Executable program:

REPORT Z930_PROG49.
write :/ 'Begin of executable program.....'.
*call function 'z930fm1'. "RUNTIME ERROR - as F.M name specified in lower case
call function 'Z930FM1'.

Example: Function Module without Parameters (Local variables)


Executable Program:

REPORT Z930_PROG50.

CALL FUNCTION 'Z930FM2'.

Example: Function Module with import Parameters


Executable Program:

REPORT Z930_PROG51.

PARAMETERS : p_x type i,


p_y type i.

*call FUNCTION 'Z930FM3' EXPORTING i_x = p_x i_y = p_y. "(or)

*call FUNCTION 'Z930FM3'


*EXPORTING
** i_x = p_x
* i_y = p_y. "runtime error as mandatory parameter value missing

call FUNCTION 'Z930FM3'


EXPORTING
i_x = p_x
i_y = p_y.

Example: Function Module with import and export Parameters


Executable Program:

REPORT Z930_PROG52.

PARAMETERS : p_x type i,


p_y type i.

data : gv_r1 type i,


gv_r2 type i.

CALL FUNCTION 'Z930FM4'


EXPORTING
I_X = p_x
I_Y = p_y
IMPORTING
E_R1 = gv_r1
E_R2 = gv_r2.

write :/ 'Sum is ',gv_r1,


/ 'Difference is ',gv_r2.

uline.
clear : gv_r1,
gv_r2.

CALL FUNCTION 'Z930FM4'


EXPORTING
* I_X = p_x
I_Y = 20
IMPORTING
E_R1 = gv_r1
E_R2 = gv_r2.

write :/ 'Sum is ',gv_r1,


/ 'Difference is ',gv_r2.

uline.
clear : gv_r1,
gv_r2.

CALL FUNCTION 'Z930FM4'


EXPORTING
I_X = 34
I_Y = 20
IMPORTING
E_R1 = gv_r1.
* E_R2 = gv_r2.

write :/ 'Sum is ',gv_r1,


/ 'Difference is ',gv_r2.

Example: Function Module with import and changing Parameters


Executable Program:

REPORT Z930_PROG53.

PARAMETERS : p_x type i,


p_y type i.

CALL FUNCTION 'Z930FM5'


EXPORTING
I_X = p_x
CHANGING
C_Y = p_y.

write :/ 'Sum is ',p_y.


Example: Function Module with exception handling
Executable Program:

REPORT Z930_PROG54.

PARAMETERS : p_x type i,


p_y type i.

data gv_res type i.

CALL FUNCTION 'Z930FM6'


EXPORTING
I_X = p_x
I_Y = p_y
IMPORTING
E_Z = gv_res
EXCEPTIONS
MYEXCEPTION =1
OTHERS = 2.

if sy-subrc eq 0.
write :/ 'Division is ',gv_res.
elseif sy-subrc eq 1.
message 'Cannot divide by zero' type 'I'.
elseif sy-subrc eq 2.
message 'Unknown error' type 'I'.
endif.

write :/ 'End of program...'.


DATABASE PROGRAMMING:

To interact with the SAP Database from ABAP applications, we use two types of SQL (Standard
query language) statements.

1. Open SQL

2. Native SQL

Native SQL: Every database vendor provides their own set of SQL statements used for
interacting with their own databases. Native SQL statements are enclosed between
͚EXEC SQL͛ and ͚ENDEXEC͛.

Oracle Corporation  Oracle database  Native SQL statements (specific to ORACLE).

Microsoft  SQL Server  Native SQL statements (specific to SQL Server)

Open SQL: is not specific to any database. i.e. they can be used to interact with any of
the databases. These open SQL statements are internally converted to native SQL by a
tool called as database interface.

Performance wise Native sql is faster than open sql.

But it is recommended to use Open sql only because in future if the customer changes
the database also, we need not modify the objects.

Procedure for interacting with databases from ABAP Programs:

1. Analyze the db table and the required fields (field name, data types, sequence)
which needs to be retrieved

2. Declare the corresponding declarations (structure / internal table/ individual fields)

structure -> for holding single record

int.table -> for holding multiple records

fields --> for holding individual fields

3. Retrieve the data from the database tables and store the same in the required target
variables

4. Process the target variables (structure / internal table / fields) accordingly

Select single: is an open sql statement used for retrieving single record from the
database table. Whenever we use select single, it is recommended to use where clause
in the select query comparing with primary key field to ensure appropriate record is
retrieved (if available).
Select..endSelect: is a open SQL statement used for retrieving multiple records from the
database. It is a looping statement, where in, for each select statement execution, it
retrieves single record, and the no. of times the select query execution depends on the
no. of records satisfying the condition. If there are more select queries, it increases
network traffic and thereby decreases performance. Because of this reason, it is
recommended to minimize the usage of select..endselect and instead use ͚select into
table͛ statement and retrieve the required no. of records using one select statement
execution and store the retrieved data into an internal table.

CURSORS:

A cursor is a data structure which can be used for holding multiple records.

Cursors in OPEN SQL:

1. Declaring the cursor

Syntax:

Data <cursor name> type CURSOR.

2. Open the cursor

Syntax:

Open cursor <cursor name> for <select query>.

Note: Only select statements can be associated with the cursors. Whenever a cursor is
opened, the select query associated with the cursor will be executed and the result of
the select query is stored in the cursor which is called as activeset.

3. Read the cursor data

Syntax:

Fetch next cursor <cursor name> into <target fields>.

Note: Fetch statement reads content of the current cursor line into target fields. If the
fetch is successful, sy-subrc is set to 0 otherwise 4.

4. Close the cursor

Syntax:

Close cursor <cursor name>.


Cursors in NATIVE SQL:

1. Open the cursor

Syntax:

EXEC SQL.
Open <cursor name> for <select query>.
ENDEXEC.

2. Read the cursor data

Syntax:

EXEC SQL.
Fetch next <cursor name> into <target fields>.
ENDEXEC.

3. Close the cursor

Syntax:

EXEC SQL.
Close <cursor name>.
ENDEXEC.

At selection-screen on value request:

This event is triggered when the user presses ͞F4͟ Key in a selection screen input field.

This event can be handled to provide ͞custom F4͞help for a selection screen input field. As part
of this event, we can call the function module F4IF_INT_TABLE_VALUE_REQUEST to populate
custom F4 values

At selection-screen on help request:

This event is triggered when the user press ͞F1͟ key on a selection screen field.

This event can be handled to provide ͞custom f1 help͟ for the selection screen field.
Native Sql and Open Sql

Reading single records


Example: Reading Single Record from Database Table – OPEN SQL – Select Single

REPORT Z930_PROG55.

*PARAMETERS p_kunnr(10) type c. "not recommended


*PARAMETERS p_kunnr type kunnr. "data element (or)
PARAMETERS p_kunnr type kna1-kunnr.

*data : gv_land1 type kna1-land1,


* gv_name1 type kna1-name1,
* gv_ort01 type kna1-ort01.
*
*select single
* land1 name1 ort01
* from kna1
* into (gv_land1,gv_name1,gv_ort01)
* where kunnr = p_kunnr.
*if sy-subrc eq 0.
* write :/ 'Customer Country :',gv_land1,
* / 'Customer Name :',gv_name1,
* / 'Customer City :',gv_ort01.
*else.
* write :/ 'No Customer'.
*endif. "(or)

types : begin of ty_kna1,


land1 type kna1-land1,
name1 type kna1-name1,
ort01 type kna1-ort01,
end of ty_kna1.

data wa_kna1 type ty_kna1.

data : gv_land1 type kna1-land1,


gv_name1 type kna1-name1,
gv_ort01 type kna1-ort01.

select single
land1 name1 ort01
from kna1
into wa_kna1
where kunnr = p_kunnr.
if sy-subrc eq 0.
write :/ 'Customer Country :',wa_kna1-land1,
/ 'Customer Name :',wa_kna1-name1,
/ 'Customer City :',wa_kna1-ort01.
else.
write :/ 'No Customer'.
endif.

Example: Reading Single Record from Database Table – NATIVE SQL

REPORT ZDB2.

PARAMETERS p_kunnr type kna1-kunnr.

data : gv_land1 type kna1-land1,


gv_name1 type kna1-name1,
gv_ort01 type kna1-ort01.

EXEC SQL.
select land1, name1, ort01
from kna1
into :gv_land1,:gv_name1,:gv_ort01
where kunnr = :p_kunnr
endexec.
if sy-subrc eq 0.
write :/ 'Customer Found....'.
write :/ 'Customer Country :',gv_land1,
/ 'Customer Name :',gv_name1,
/ 'Customer City :',gv_ort01.
else. "sy-subrc eq 4
write :/ 'Customer Not Found'.
endif.
Reading multiple records

Example: Reading Multiple Records from Database Table – OPEN SQL (select into table)

REPORT Z930_PROG56.

PARAMETERS p_land1 type kna1-land1.

types : begin of ty_kna1,


kunnr type kna1-kunnr,
name1 type kna1-name1,
ort01 type kna1-ort01,
end of ty_kna1.

data : t_kna1 type table of ty_kna1,


wa_kna1 type ty_kna1.

select kunnr name1 ort01


from kna1
into table t_kna1
where land1 = p_land1.
if sy-subrc eq 0.
write :/ 'No of records retrieved is ',sy-dbcnt.
loop at t_kna1 into wa_kna1.
write :/ wa_kna1-kunnr,
wa_kna1-name1,
wa_kna1-ort01.
endloop.
else.
write :/ 'No customers in the given country...'.
endif.

Example: Custom F4 Help and Custom F1 Help for Selection-Screen Input Field

REPORT Z930_PROG57.

PARAMETERS p_kunnr type kna1-kunnr.

types : begin of ty_kna1,


land1 type kna1-land1,
name1 type kna1-name1,
ort01 type kna1-ort01,
end of ty_kna1.

data wa_kna1 type ty_kna1.

data : gv_land1 type kna1-land1,


gv_name1 type kna1-name1,
gv_ort01 type kna1-ort01.

types : begin of ty_f4values,


kunnr type kna1-kunnr,
name1 type kna1-name1,
ort01 type kna1-ort01,
end of ty_f4values.

data t_f4values type table of ty_f4values.

select single
land1 name1 ort01
from kna1
into wa_kna1
where kunnr = p_kunnr.
if sy-subrc eq 0.
write :/ 'Customer Country :',wa_kna1-land1,
/ 'Customer Name :',wa_kna1-name1,
/ 'Customer City :',wa_kna1-ort01.
else.
write :/ 'No Customer'.
endif.

at SELECTION-SCREEN on VALUE-REQUEST FOR p_kunnr.


* message 'hello' type 'I'.
select kunnr name1 ort01
from kna1
into table t_f4values
where land1 in ('AR','AU','BE').
if sy-subrc eq 0.
CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
EXPORTING
RETFIELD = 'KUNNR'
* DYNPPROG = 'Z930_PROG57' "(or)
DYNPPROG = sy-repid
* DYNPNR = '1000' "(or)
DYNPNR = sy-dynnr
DYNPROFIELD = 'P_KUNNR'
VALUE_ORG = 'S'
TABLES
VALUE_TAB = t_f4values
EXCEPTIONS
PARAMETER_ERROR =1
NO_VALUES_FOUND =2
OTHERS = 3.
endif.

at SELECTION-SCREEN on HELP-REQUEST FOR p_kunnr.


* message 'Customer Number' Type 'I'. "(or)

CALL FUNCTION 'POPUP_TO_INFORM'


EXPORTING
TITEL = 'Custom F1 Help'
TXT1 = 'Customer Number'
TXT2 = 'Table: KNA1, Field: Kunnr'.
Dictionary objects (se11)

1. Tables

2. Views

3. Data elements

4. Domains

5. Type Groups

6. Search Helps

7. Table Types

8. Lock objects

9. Structures

Table can be used to store the data permanently.

Data  master data / Transaction data

Master data:

The data which doesn t change frequently is known as master data.

Example:- Empno, ename, customer no, customer name ,bank account no, bank account holder
name, material data, vendor data.

Transaction data:

Day to day business data is called transaction data.

Example:-Emp attendance details, emp salaries, customer orders, bank transactions.

Business Document s- are used for data exchange

Enquiry form, quotation, purchase order document, sales order document, billing document,
delivery schedule document.

 Every business document contains 1 header record and one or more item record s.

 Header records data will be stored in header tables.

 Item records data will be stored in item tables.

Example for Header and item tables:

VBRK  Billing document header data


Key fields  mandt(client), vbeln(billing document no)

Eg: vbeln  0090005178

VBRP  Billing document item data

Key fields  mandt (client), vbeln (billing document no), posnr (item no)

Eg: vbeln  0090005178  contains 4 items

Other header and item tables: - Sales Documents (VBAK and VBAP),
Purchase Documents (EKKO and EKPO)

 As part of database tables we can directly use the standard tables, enhance the
standard table (adding fields).

 We can also create the custom tables for storing the customer specific data.

To create dictionary objects, we use t-code -> se11.

Primary key:

A field declared as primary key can t accept the duplicate values.

In SAP, every table must contain minimum 1 key field and max. 16 primary fields. Primary key
fields must be at the beginning of the table.

Combination of primary key fields is called as composite key.

Based on the client concept, the database tables are classified into two types.

i. Client dependent tables.

ii. Client independent tables.

Client dependent tables:

The tables which contains MANDT as first field is called client dependent.

MANDT field will hold the client no.

The records in these tables are specific to the client i.e. the record inserted in one client will not
available in other client.

Eg: KNA1, MARA, LFA1, VBAK, VBAP, EKKO, EKPO, VBRK, VBRP

Client independent tables:

This table doesn t contain MANDT field.


The record s in this tables are not specific to any client s i.e. they are available across the
client s.

Eg: TFDIR, TADIR

Table creation:

 A table is dictionary object which is a collection of rows (records) and columns (fields)

 Tables are used for storing the data permanently.

In ABAP a table field can be created in two ways:-

i. By using direct data types.

ii. By using data elements and domains (recommended).

Procedure for creating custom database tables:

i. Analyze the fields and the corresponding data types.

ii. Create and activate the table.

iii. Generate table maintenance.

iv. Declare and define events (if required) at the table maintenance level.

v. Create the t-code for the table maintenance.

Minimum settings required for creating custom database tables:

Delivery and maintenance settings:

1. Delivery class.

2. Data browser / table view maintenance.

Delivery class:

It is used for controlling the transporting of table data.

The possible value s are A or C .

A -> application table used for storing master and transaction data.

Generally it is recommended to create the client dependent table as application table.

C -> customizing table used for storing customers specific data.

Data browser / table view maintenance:

It can contain the following 3 possible values.


In dialog box:

1. Display / Maintenance allowed with restriction.

Note:

In this we can only view the data but we can t perform the operations like insertion,
deletion and modification.

2. Display Maintenance allowed.

It supports all the operations i.e we can view, insert , delete and modify.

3. Display maintenance not allowed.

It doesn t support any of the operations.

Technical settings:

1. Data class.

2. Size category

Data class:

It specifies the schema (partition) in which the table as to be stored. As an ABAP Consultant we
will use only Master Schema (APPL0) and Transaction schema (APPL1).

Size category:

It specifies the initial amount of memory that needs to be allocated for the database table.

 When the initial memory is utilized, the memory gets extended automatically to the
amount of initial size.

 In size category the range of number of data records depends upon structure of the
table .

Enhancement category:

It specifies the type of enhancement that can be made to the table.

Enhancement is a process of adding the additional fields in the standard tables.

Limitations of table fields creation using direct data types:

 Always the character field values are captured in upper case.

 We cannot impose validations on table data.

 It doesn t support reusability


 Cannot maintain field labels

Table maintenance:

After creating every database table, ABAP consultant must generate Table Maintenance.

 The table maintenance allows the end user to maintain the table for performing the
operations like insertion, deletion, Modification and view the data (display).

 For generating table maintenance we require function group.

 A function group is an object which stores the objects related to table maintenance.
I.e. dependent objects (screens, subroutines, f.m s) related to table maintenance are
stored inside function group.

 For creating Function group, we use se80

 As part of generating table maintenance, we need to specify maintenance type which


is of two types.

 Maintenance type is of two types:-

i. One step:

In one step only one screen is generated called as overview screen in which all the CRUD
(create, read, update and delete) operations are performed.

ii. Two step:

 In two step, Two screens will be generated, overview screen and single screen.

 In overview screen we can only view the data, delete the data and modify the data.

 In single screen we can insert the data.

Procedure for generating Table maintenance:

1. Create /Consider a function group (se80)->z830fgroup

2. In SE11, navigate to the table, choose the menu utilities table maintenance
generator

Authorization group  &nc&

Note: Authorization group is an object created by BASIS consultant which is associated


with set of users who are authorized to maintain a particular object (table).

Function group  z830fgroup (existing function group)

Maintenance type one step (select the radiobutton)


Propose overview screen no by choosing find scr numbers  propose screen no.
on appl.toolbar

3. Click on create button (appl.toolbar)

 Once a table maintenance is generated, we can maintain the table using the T-code
SM30 .

 To minimize the process of table maintenance, we need to create custom t-code for
every table maintenance

Custom t-code creation SE93

Creating T-code for table maintenance:

SE93 .provide custom t-code (ZTEMP), create  pro ide short te t … , hoose the
radiobutton Transaction with parameters Provide Transaction (SM30), select the checkbox
skip initial screen , in gui support select the checkbox sap gui for windows and provide
default values for the skipped screen at the end

Name of screen field value

Viewname z830emp

Update X

Note: For collecting screen field names, goto sm30 initial screen, press f1 in table/view field and
collect the screen field name, similarly put focus on maintain button, press f1 and collect the
function code (upd) (equal to update)

Note: Whenever we create t-code for any object, select the check box SAP GUI for windows ,
otherwise t-code cannot be used (incomplete).

Table creation using data elements and domains:

Data element: is a reusable dictionary object which provides description for the field. I.e. the
description (labels) maintained at data element level will automatically appear on the screen
wherever the data element is referred. It can be created by referring to a direct data type /
referring to a domain. We can also associate a search help (f4 help) as part of data element.

Domain: is a reusable dictionary object which stores technical properties of the field like data
t pe, size, fi ed alues, alue ta le….

Note:

If it is client dependent table we have to give minimum two primary key fields otherwise if only
mandt is primary key field then we can maintain maximum of single record.

Collection of Primary key fields is called as Composite key.


Creating dictionary structures (Global structures): A structure is a collection of different types
of fields (se11  choose data type radio button, provide name of structure (z830str), Create 
choose structure radio button and create the required fields.

Once a dictionary structure is created, we can include the dictionary structure in other
dictionary structures / database tables by using .include keyword.

We can also include dictionary structures inside local structures of repository objects using the
statements include structure <structure name> or include type <structure name>

Dictionary structure:

Including Dictionary structures in other Dictionary Objects:


Including Dictionary structures in Repository Objects (Executable program):

REPORT ZUSEGLOBALSTR.

types : begin of ty_emp,


empno type i,
ename(20) type c.
* include structure z7amstr.
include type z7amstr.
types : empdesig(25) type c,
end of ty_emp.

data wa_emp type ty_emp.

wa_emp-empno = 6.
wa_emp-ename = 'Ravi'.
wa_emp-jdate = sy-datum.
wa_emp-jtime = sy-uzeit.
wa_emp-empdesig = 'Manager'.

write :/ wa_emp-empno,
/ wa_emp-ename,
/ wa_emp-jdate,
/ wa_emp-jtime,
/ wa_emp-empdesig.

Note: Once a table maintenance is generated and later on if we make any changes to the table
like adding ne fields, hange in field la el/data t pe… , these changes will not reflect the
existing table maintenance. For reflecting these changes, we need to delete the existing table
maintenance and re-generate the same.

Events at table level:

We can define and implement the events as part of table maintenance to handle user
actions.These events are implemented in the subroutine which is stored in a include program of
the function group.

Requirement: Whenever a new entry is created in the table (z730employee), automatically we


need to assign appl.server date and time to the table fields (jdate and jtime).

Navigation: In the table maintenance screen, choose the menu environment  modification 
events, click on new entries button, provide the following

T(time of event) Form routines


05 abc (after giving subroutine name, press enter key it shows an icon in
the editor column button)

To define the subroutine, click on the corresponding editor button, choose new include,
continue.

form abc.
z730employee-jdate = sy-datum.
z730employee-jtime = sy-uzeit.
endform.

SAVE AND ACTIVATE.

Note: After Implementing events at table level, we need to activate the function group of table
maintenance so that the include programs of that function group gets adjusted otherwise when
we maintain the table, it generates runtime error.

Type groups:

 It is a collection of global types and constants.

 All the components in the type group must prefix with type group name followed by
_.

 Inside the type group we can use only types and constant keywords.

 To use the components of the type group inside the repository objects, We must
declare the type group by using the keyword type-pools" .

 Standard type-groups: CNTL, CNDP, SLIS, ICON, VRM…..

Type-group creation in SE11:

TYPE-POOL ZABC .

*data x type i. "syntax error


*constants x type i. "syntax error

*constants x type i value 10. "syntax error

constants zabc_x type i value 10.


constants zabc_y type string value 'Gensoft'.

types zabc_m type i.

types : begin of zabc_emp,


empno type i,
ename type string,
empdesig type string,
end of zabc_emp.

types : begin of zabc_student,


cname type string.
* include structure z7amstr. "(or)
include type z7amstr.
types : caddr type string,
end of zabc_student.

Using Type-group in Executable program:

*type-pools zabc. "mandatory till ECC 6.0


write :/ zabc_x,zabc_y.

*zabc_m = 20. "syntax error


uline.
data gv_m type zabc_m.
gv_m = 20.
write :/ gv_m.

uline.
data wa_emp type zabc_emp.
wa_emp-empno = 6.
wa_emp-ename = 'Raju'.
wa_emp-empdesig = 'Manager'.
write :/ wa_emp-empno,
/ wa_emp-ename,
/ wa_emp-empdesig.

Indexes:

 Indexing is a process of arranging the data in an order.

 Indexes are always created on top of database tables.

 There are two types of indexes:-

1. Primary index 2. Secondary index.

Primary index:

 Primary index is created by sap itself on top of primary key field.

 As a developer we can create only a secondary index and it can be created on non-
primary key fields.
Secondary indexes are of two types:

1. Unique. 2. Non-unique.

Unique Secondary Index:

Whenever a unique secondary index is created on a field we can t maintain duplicate


values for that field. Whenever a unique secondary index is created on client dependent
tables, client field (MANDT) should be part of indexed fields.

Non-Unique Secondary Index:

Whenever a non-unique secondary index is created on a field, it is possible to maintain


duplicate values for that field.

Views:

A view is a reusable dictionary object which doesn t exist physically i.e. it is virtual table
(IMAGINARY TABLE). The data in the view will be populated only in the runtime. i.e a view
doesn t hold any data by default. Views are used for hiding the original table names, hiding field
names, restricting the access to table data, to read data from one or more tables. Views are
created on top of database tables.

They are 4 types of views.

i. Database view

ii. Projection view

iii. Maintenance view

iv. Help view

Database view:

 It can be created either on single table or multiple tables.

 It supports both projection and selection

 Projection is a process of selecting only required fields and selection is a process of


imposing conditions on accessing the table data.

 A database view created on single table can be Read only (or) Read and Change . I.e.
the changes made to the data at the view level will automatically reflect the
corresponding base table and vice versa.

 A database view created on multiple tables is always Read only .

 We cannot generate table maintenance for db views.


 Whenever we create any view based on multiple tables, we must provide the join
conditions by comparing with logically related fields, otherwise it will lead to Cartesian
product (No. of entries of one table * No of resultant values of other table)

 Whenever we create database view on multiple tables with join conditions, it


constructs the resultant values based on inner join.

Example: Database view on single table


Example: Database view on multiple tables
Projection view:

 It is always created on single table

 It supports only projection but not selection.

 We go for projection view, whenever we need to share complete data of the base
table but with limited fields.

 Maintenance status can be Read (or) Read and Change.


Note:

For both database and projection view s we can t generate Table Maintenance.

Foreign key relationship between tables:

We create foreign key relationship between two tables to maintain data consistency. i.e
the data of one table is based on data of other table.

In foreign key relationship, two tables are involved.

A) Check table b) Foreign key table

Check table: is a parent table where we maintain the key data.

To create a foreign key relationship between two tables, the two tables must
contain at least one field which is having common domain and in one of the table
the common field should be a primary key field and this table is considered as check
table as it maintains unique values for that common field.

On the other table common field, we create foreign key which is called as foreign
key table.

Once a foreign key relationship is created, it maintains referential integrity.


According to this, in the foreign key table we can enter only those values for the
common field which needs to be available in check table common field.

I.E. We need to insert a child row (record in the foreign key table) only when there
is a corresponding record in parent record (records in parent table->check table).

Example:

Department table: (z830_dept)

Fields:

Deptno(PK) zdept_no zdept_no int4

Dname zdname ydname char20

Loc zloc zloc char15

Deptno s:- 10,20,30

Employee table (z830_empl)

Fields:

empno zemp_num
ename zename

empdesig zempdesig

dno zdnum zdept_no int4

Note: Create foreign key on dno field

Maintenance view:

 This is always created on single table, based on the foreign key table selected, SAP
proposes join condition.

 We can generate table maintenance for maintenance view

 Its support both selection and projection.


View cluster: - is a collection of views which are grouped together and it simplifies the
maintenance of complex cross-client data (across the tables)

Material tables:

MARA (MATERIAL MASTER DATA) --> MANDT, MATNR

MARC (MATERIAL PLANT DATA) --> MANDT, MATNR, WERKS

MARD (MATERIAL STORAGE LOCATION DATA) --> MANDT,MATNR,WERKS,LGORT

Relationship:- Each Material of MARA table can contain zero / one /more plants in MARC.
EACH Material plant of MARC can contain zero / one / more storage
locations in MARD.

1. Create Maintenance view on MARA table


2. Generate Table maintenance for above maintenance view

3. Create maintenance view on MARC table


4. Generate table maintenance for above view

5. Create maintenance view for MARD table


6. Generate Table maintenance for above view
7. Create the view cluster(se54)

Se54  click on edit view cluster (appl.toolbar),

Provide view cluster name (z830viewcluster), click on create/change,

Pro ide des ription …… in header entr …


Provide object structure as follows:

Select each entry, click on field dependen ies …


Come back to header entry, and click on activate.

Save and activate, test

Working with Currency and Quantity Fields:

Whenever a table field or structure field contains curr (currency) or Quan (quantity) fields, we
must specify reference table and reference field.

The reference table can be same table (or) external table and reference field can be same table
field (or) external table field.

The reference data type for (curr) currency is cuky and reference data type for (quan) quantity
is unit .

TCURC  Table for Currency Codes

TOO6  Table for units of measurement

Scenario 1: Reference table  Same table


Scenario 2: Reference table  External table
Table types: is the reusable dictionary object

Table types are the internal tables created at database level.

A Table type can refer to a direct data type / line type (structure)/ reference type (class or
interface)

Example 1: Table Type Creation:

Scenario 1: Table Type referring to direct data type (single field)

Example: Using above table type in executable programs

report z830_usettype1.
data gt_ttype type z830ttype1. "internal table
data gs_ttype like line of gt_ttype."work area/structure

gs_ttype = '10'.
append gs_ttype to gt_ttype.
gs_ttype = '20'.
append gs_ttype to gt_ttype.
gs_ttype = '30'.
append gs_ttype to gt_ttype.

loop at gt_ttype into gs_ttype.


write :/ gs_ttype.
endloop.

Scenario 2: Table Type referring to line type (structure)


Example: Using above table type in executable programs

report z830_usettype2.

data gt_emp type z830ttype2. "internal table without header


*gt_emp-empno = 8. "syntax error as internal table doesn't have header

*data gs_emp like line of gt_emp. "(or)


data gs_emp type z830ltype.

gs_emp-empno = 5.
gs_emp-ename = 'ravi'.
gs_emp-empdesig = 'ceo'.
append gs_emp to gt_emp.

gs_emp-empno = 15.
gs_emp-ename = 'ramu'.
gs_emp-empdesig = 'ceo'.
append gs_emp to gt_emp.

gs_emp-empno = 3.
gs_emp-ename = 'krishna'.
gs_emp-empdesig = 'director'.
append gs_emp to gt_emp.

*loop at gt_emp. "syntax error


loop at gt_emp into gs_emp.
write :/ gs_emp-empno,
gs_emp-ename,
gs_emp-empdesig.
endloop.

Standard table types: LVC_T_FCAT, LVC_T_ROW, LVC_T_COL…..

Example 2: Table Type Creation:


Using Table Type in Executable program:

Report 1: Table type referred with Header line

REPORT ZUSEDBVIEW2 line-size 120.

data t_dbview type zemp_dept WITH HEADER LINE.

select * from zdataview


into table t_dbview.
if sy-subrc eq 0.
write :/ 'No of records retrieved :',sy-dbcnt.
loop at t_dbview.
write :/ t_dbview-empno,
t_dbview-ename,
t_dbview-empdesig,
t_dbview-dno,
t_dbview-deptno,
(25) t_dbview-dname,
t_dbview-loc.
endloop.
else.
write :/ 'No data'.
endif.

Report 2: Table type referred without Header line

REPORT ZUSEDBVIEW3 line-size 120.

data t_dbview type zemp_dept. "internal table without header


*data wa_dbview like zemp_dept. "syntax error
*data wa_dbview type zdataview. "(or)
data wa_dbview like line of t_dbview.

select * from zdataview


into table t_dbview.
if sy-subrc eq 0.
write :/ 'No of records retrieved :',sy-dbcnt.
loop at t_dbview into wa_dbview.
write :/ wa_dbview-empno,
wa_dbview-ename,
wa_dbview-empdesig,
wa_dbview-dno,
wa_dbview-deptno,
(25) wa_dbview-dname,
wa_dbview-loc.
endloop.
else.
write :/ 'No data'.
endif.

Lock Objects:

1. They are used for performing row-level locking of the table data

2. By Default, Object level locking (Repository / Dictionary objects) is taken care by SAP
itself. i.e only one user can edit an object at any point of time, other users can only read
the object.

3. Lock Objects names must start with EZ (or) EY and locking is done based on primary
key field/s

4. Whenever a Lock object is created, SAP creates 2 Function modules

a) ENQUEUE_<LOCK OBJECT NAME> - used for locking the row


b) DEQUEUE_<LOCK OBJECT NAME> - used for releasing the lock
Types of Lock Modes:

1. Exclusive / Write Lock  In this, only one user can read or edit the locked record. If
other users request for the Exclusive lock, his request will be rejected but the request is
stored in the queue. Once the first user releases the exclusive lock, the exclusive lock
access is given to other user in the queue.

2. Shared / Read Lock: In this, multiple users can read the locked record and if a user
modifies the locked record, the modified data is not accessible to other users.

3. Exclusive but not cumulative: It is similar to Exclusive lock, but other users request is
not stored in the queue, but instead the others users have to send the fresh request.
LOCK OBJECTS CREATION AND USAGE

Lock Object Creation:

1. Create Lock object in SE11

2. In Tables tab, provide table name as KNA1


3. In Lock parameter tab, SAP proposes Lock parameters based on key fields

Activate, SAP generates 2 function modules, check them using go to menu  lock modules
Using Lock objects in Executable programs:

report zlockcustomer.

*PARAMETERS p_kunnr(10) type c. "not recommended

*PARAMETERS p_kunnr type kunnr. "(or)


parameters p_kunnr type kna1-kunnr.

data : gv_name1 type kna1-name1,


gv_ort01 type kna1-ort01.

*set pf-status 'abc'. "invalid as status name should be in upper case


set pf-status 'ABC'.

* Lock the customer


call function 'ENQUEUE_EZLOCKCUSTOMER'
exporting
mode_kna1 = 'E'
mandt = sy-mandt
kunnr = p_kunnr
exceptions
foreign_lock =1
system_failure =2
others = 3.

if sy-subrc eq 1.
message 'Customer No is Locked' type 'E'.
endif.

select single name1 ort01


from kna1
into (gv_name1,gv_ort01)
where kunnr = p_kunnr.
if sy-subrc eq 0.
write :/ 'Customer name :',gv_name1,
/ 'Customer city :',gv_ort01.
else.
write :/ 'Customer not found'.
endif.

at user-command.
case sy-ucomm.
when 'FC2'.
leave program.
when 'FC1'.
* Release the lock
call function 'DEQUEUE_EZLOCKCUSTOMER'
exporting
mode_kna1 = 'E'
mandt = sy-mandt
kunnr = p_kunnr.
endcase.

Note: To test Lock object functionality, run the above two programs in 2 sessions and provide
customer no in one session, execute, displays output. In another session, provide same
customer no, it says the record is locked. Now, in the first session unlock the record by clicking
on the user defined button release lock in the application toolbar and execute the same
customer in the second session, now it displays data.

Note: Set pf-status <status name> is used for creating user-defined GUI status and using this
we can invoke the menu painter tool (SE41) where we can manage the menu bar, standard
toolbar and application toolbar. Whenever we define our custom GUI status, SAP looses
functionality of some of the std.toolbar buttons , in order to enable them, assign a function
code and implement the logic in the at user-command event.When the user interacts with
menu bar items / std.toolbar buttons / appl. Toolbar buttons, SAP triggers AT USER-
COMMAND button and the corresponding function code will be captured in the system field
SY-UCOMM (function code is always captured in upper case).To Invoke the Menu painter tool,
double click on GUI status name in the set pf-status statement.

Application toolbar buttons in the GUI status ABC :


Assigning function code for the back button in the GUI status for enabling it:
SEARCH HELPS:

It is a reusable dictionary object used for providing list of values as input help to the user.

It is triggered when the user presses F4 key in the Input Field.

Once a Search help is created, we can associate the search help at 3 different levels:

1. Data element level

2. Selection-Screen input field level

3. Module Pool (Dialog screen) input field level

There are 2 types of Search helps:

1. Elementary Search Help  provides single input path for list of values

2. Collective Search Help  collection of elementary search helps  provides


multiple input paths for list of values

Elementary Search Help creation 1:

Create the following table:


Create the Elementary search help:

Elementary Search Help creation 2:

Create the following table:

Create the Elementary search help:


Collective Search help creation:
Assign parameter to the parameter of elementary search helps:
Attaching search help at the data element level:
Executable program: Attaching search help to the selection screen input field

report zattachsearchhelp.

parameters p_name type zabap_team-emp_name matchcode object zcolsp.

*PARAMETERS p_name type zemploy_name MATCHCODE OBJECT zelesp1.

Executable program: Attaching search help to the module pool screen input field properties:

Search Help Selection Method: As part of creating Elementary Search Help, We need to provide
the selection method. This selection method can be either a database table or database view or
help view. We go for database table when we need to get the entries of search help (f4 values)
from a single table. We go for views when we need to get the entries of search help (f4 values)
from multiple tables. In case of database view created on multiple tables, it implements inner
join and in case of help view created on multiple tables, it implements left outer join.

Example 2: To explain selection method of search help

Table 1: ztest_emp
Table 1 entries:

Table 2-> ztest_dept


Table 2 entries:
Foreign key relationship between above 2 tables:

Scenario 1: Database view  multiple tables


Elementary Search Help Selection method  Database view
Select required parameters and then execute  displays 4 records

Scenario 2: Help View Multiple Tables


Elementary Search Help Selection method  Help view
Select required parameters and then execute  displays 7 records

Using Views in Select Queries:

Database view  multiple tables


Report 1:

REPORT ZUSEDBVIEW.

types : begin of ty_dbview.


include type zdataview.
types end of ty_dbview.

data : t_dbview type table of ty_dbview,


wa_dbview type ty_dbview.

select * from zdataview


into table t_dbview.
if sy-subrc eq 0.
write :/ 'No of records retrieved :',sy-dbcnt.
loop at t_dbview into wa_dbview.
write :/ wa_dbview-empno,
wa_dbview-ename,
wa_dbview-empdesig,
wa_dbview-dno,
wa_dbview-deptno,
wa_dbview-dname,
wa_dbview-loc.
endloop.
else.
write :/ 'No data'.
endif.

Report 2: Formatted Output

REPORT ZUSEDBVIEW1 line-size 120.

types : begin of ty_dbview.


include type zdataview.
types end of ty_dbview.

data : t_dbview type table of ty_dbview,


wa_dbview type ty_dbview.

select * from zdataview


into table t_dbview.
if sy-subrc eq 0.
write :/ 'No of records retrieved :',sy-dbcnt.
loop at t_dbview into wa_dbview.
write :/ wa_dbview-empno,
wa_dbview-ename,
wa_dbview-empdesig,
wa_dbview-dno,
wa_dbview-deptno,
(25) wa_dbview-dname,
wa_dbview-loc.
endloop.
else.
write :/ 'No data'.
endif.
Authorization group purpose

Data Class
Differences between dbview/prjview/mntncview

Foreign key relationships


Header and item data

Including global structures

Inner Joins
Left Outer Join

Lock Objects
Locking-Object Level

Maintanance type one step and two step


Search help Usage

Table Creation minimum settings


Usage type groups

View Cluster

search helps --> associate custom f4 help

elementary search help ---> selection method (table / view)

selection method ---> table --> to get f4 values from single table

selection method ---> view (database view / proj.view / help view)-->


database view --> multiple tables (inner join)

help view --> multiple tables (left outer join)

ZTEST_EMP->7 ZTEST_DEPT->3

DNO DEPTNO

10 10

10 20

20 50

20

30

30

40

DATABASE VIEW--> 4 rec

10

10

20

20

help view ---> 7 rec

10

10

20

20

30 0 space space

30 0 space space

40 0 space space
Select-options:

It generates a selection-screen for reading ranges of input values. It is an internal table created
in the run time by SAP based on the select-option field. It contains following structure:

a) Sign  Possible values are ͚I͛ (Inclusive) / ͚E͛ (exclusive)

Default value is ͚I͛

 ͚I͛  considers values from lower limit to upper limit

 ͚E͛  considers values before lower limit and after upper limit

b) Option  Possible values are ͚BT͛(between), <, >,<=,>=

 Default value is ͚BT͛

c) Low  holds lower limit of the range

d) High  holds upper limit of the range

Syntax for declaring select-option:

Select-options <variable> for <target field>.

Note: In the above syntax, if the target field is referring to dictionary structure field,
then target dictionary structure should be declared explicitly using ͚tables͛ keyword.

͚Tables͛ KEYWORD will create work area with all the fields of the dictionary structure
which is a performance issue. Because of this reason, it is recommended not to declare
select-option referring to dictionary structure.

The Recommended declaration is to declare a local variable referring to dictionary


structure field and then declare the select-options referring to local variable.

We can use the addition ͚no-extension͛ as part of select-option declaration to restrict


the user to enter only single range in the run-time.

Ranges:

It is used for holding range of values. It is an internal table created in the run time based on the
field. It contains same structure as that of select-options:

a) Sign  Possible values are ͚I͛ (Inclusive) / ͚E͛ (exclusive)

b) Option  Possible values are ͚BT͛(between), <, >,<=,>=

c) Low  holds lower limit of the range

d) High  holds upper limit of the range


Syntax for declaring Range:

Ranges <variable> for <target field>.

Order by Clause: We can use order by clause in select query to retrieve the data in sorted order
of the specified order by field. It is recommended not to user order by clause, because it
performs sorting at the time of retrieving data from database which increases load on DB server
which degrades the performance. We can avoid by using sort statement on internal table as it
gets executed on application server.

Tables keyword work area creation


Select option internal table dynamic creation

Reading range of input values

Example: Select Options (Default values using ͚Default͛ keyword)

REPORT Z930_PROG58.

*tables kna1. "creates work area based on KNA1 structure


*select-OPTIONS so_kunnr for kna1-kunnr. "not recommended

data gv_kunnr type kna1-kunnr.


*select-OPTIONS so_kunnr for gv_kunnr DEFAULT '2000' to '2010'.
select-OPTIONS so_kunnr for gv_kunnr DEFAULT '2000' to '2010' no-EXTENSION.

types : BEGIN OF ty_kna1,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
ort01 type kna1-ort01,
end of ty_kna1.

data : t_kna1 type table of ty_kna1,


wa_kna1 type ty_kna1.
select kunnr land1 name1 ort01
from kna1
into table t_kna1
where kunnr in so_kunnr.
if sy-subrc eq 0.
write :/ 'No of records :',sy-dbcnt.
loop at t_kna1 into wa_kna1.
write :/ wa_kna1-kunnr,
wa_kna1-land1,
wa_kna1-name1,
wa_kna1-ort01.
endloop.
else.
write :/ 'No data'.
endif.

Example: Select Options (Default values using ͚Initialization͛ Event, Order by Clause)

REPORT Z930_PROG59.

data gv_kunnr type kna1-kunnr.


select-OPTIONS so_kunnr for gv_kunnr.

types : BEGIN OF ty_kna1,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
ort01 type kna1-ort01,
end of ty_kna1.

data : t_kna1 type table of ty_kna1,


wa_kna1 type ty_kna1.

INITIALIZATION.
so_kunnr-low = '2000'.
so_kunnr-high = '2010'.
append so_kunnr.

so_kunnr-sign = 'I'.
so_kunnr-option = 'BT'.
so_kunnr-low = '3000'.
unpack so_kunnr-low to so_kunnr-low.

so_kunnr-high = '3010'.
unpack so_kunnr-high to so_kunnr-high.
append so_kunnr.

START-OF-SELECTION.
select kunnr land1 name1 ort01
from kna1
into table t_kna1
where kunnr in so_kunnr.
* order by kunnr DESCENDING. "not recommended as it increases burden on db server
if sy-subrc eq 0.
write :/ 'No of records :',sy-dbcnt.
sort t_kna1 by kunnr DESCENDING.
loop at t_kna1 into wa_kna1.
write :/ wa_kna1-kunnr,
wa_kna1-land1,
wa_kna1-name1,
wa_kna1-ort01.
endloop.
else.
write :/ 'No data'.
endif.

Example: Ranges keyword

REPORT Z930_PROG60.

ranges r_kunnr for kna1-kunnr.

types : BEGIN OF ty_kna1,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
ort01 type kna1-ort01,
end of ty_kna1.

data : t_kna1 type table of ty_kna1,


wa_kna1 type ty_kna1.

START-OF-SELECTION.
r_kunnr-sign = 'I'.
r_kunnr-option = 'BT'.
r_kunnr-low = '0000002000'.
r_kunnr-high = '0000002010'.
append r_kunnr.
r_kunnr-sign = 'I'.
r_kunnr-option = 'BT'.
r_kunnr-low = '0000003000'.
r_kunnr-high = '0000003010'.
append r_kunnr.

select kunnr land1 name1 ort01


from kna1
into table t_kna1
where kunnr in r_kunnr.
if sy-subrc eq 0.
write :/ 'No of records :',sy-dbcnt.
loop at t_kna1 into wa_kna1.
write :/ wa_kna1-kunnr,
wa_kna1-land1,
wa_kna1-name1,
wa_kna1-ort01.
endloop.
else.
write :/ 'No data'.
endif.

Differences between select option and ranges


Reports:

It is a process of retrieving the data from the database based on the user input, processing the
retrieved data, and displaying the data in summarized format so that the user can analyze the
data based on which business decisions are taken.

Types of Reports:

1. Simple Report  Single / Multiple Tables (Joins)

2. Hierarchical Report

3. Control Break Report

4. Interactive Classical Report

5. Logical Database reporting (Hr-ABAP)

Hierarchical Reports:

In this, the data is displayed in the form of parent(header data) and child(item data).

Vbak -> Sales Document Header data Fields  vbeln , erdat , erzet , ernam

Vbap-> Sales Document Item data  Fields  vbeln , posnr , matnr

Each sales document of VBAK table can contain zero or one or more sales items in VBAP table.

Whenever we retrieve the data using select statement into an internal table which is already
containing data, then the existing contents of the internal table will be over written with the
latest retrieved data. We can avoid this by using appending corresponding fields into table (or)
appending table keyword as part of select statement.

FOR ALL ENTRIES:

Using Select statements inside loop-endloop will degrade the performance because the no. of
select statements execution depends on no. Of times the loop is iterated.

This can be avoided by using for all entries keyword as part of select statement. To use FOR
ALL ENTRIES in select queries there should be one logically related field between the target DB
table and source internal table and this field should be compared using where clause as part of
select query using for all entries .

Before using for all entries , check whether source internal table contains at least one entry.

Controls break reports:

As part of this, we use control break events which are also called as AT events. These events
are used only in loop- endloop.
At first: - This event is triggered when we are processing the 1st row of the internal table. This
event can be handled to provide heading for the report before displaying the data.

Syntax:

At first.

Statements.

Endat.

At new:-

This event is triggered at the beginning of a first row combination whenever a unique value is
encountered for the specified field. This event can be handled to generate sub heading at the
beginning of every unique value.

Syntax:

At new <field name>.

Statements.

Endat.

At end of:

This event is triggered at the end of the last row combination of every unique value for the
specified field. This event can be handled to generate subtotals at the end of every unique
value.

Syntax:

At end of <field name>.

Statements.

Endat.

At last:

This event is triggered at the end of the last row of the internal table. This event can be
handled to generate footer for the report like grand total.

Syntax:

At last .

Statement.

Endat.
Sum statement:

Sum statement can be used as part of at end of and at last event. This statement will do the
sum of numeric fields of the corresponding rows and stores the sum value with in the same
field. This sum value can be accessed within the same events. i.e. the sum value will be
destroyed once a control comes out of the event.

On change of:

It is similar to at new event, but on change of event can be used in any of the looping
statements like while – endwhile. do enddo, select – endselect, loop-endloop whereas at new
can be used only inside loop-endloop.

Note:

The field specified in at new and at end of event should be at the beginning of the internal
table otherwise, these 2 events are triggered for every record of the internal table.

Select-options:

It generates a selection-screen for reading range of input values. It is an internal table created
in the run time based on the field. It contains following structure:

a) Sign  Possible values are I (Inclusive) / E (exclusive)

Default value is I

 I  considers values from lower limit to upper limit

 E  considers values before lower limit and after upper limit

b) Option  Possible values are BT (between), <, >,<=,>=

 Default value is BT

c) Low  holds lower limit of the range

d) High  holds upper limit of the range

Syntax for declaring select-option:

Select-options <variable> for <target field>.

Note: In the above syntax, if the target field is referring to dictionary structure field, then target
dictionary structure should be declared explicitly using tables keyword. Tables KEYWORD will
create work area with all the fields of the dictionary structure which is a performance issue.
Because of this reason, it is recommended not to declare select-option referring to dictionary
structure. The Recommended declaration is to declare a local variable referring to dictionary
structure field and then declare the select-options referring to local variable. We can use the
addition no-extension as part of select-option declaration to restrict the user to enter only
single range on the selection screen.

Ranges:

It is used for holding range of values. It is an internal table created in the run time based on the
field. It contains same structure as that of select-options:

e) Sign  Possible values are I (Inclusive) / E (exclusive)

f) Option  Possible values are BT (between), <, >,<=,>=

g) Low  holds lower limit of the range

h) High  holds upper limit of the range

Syntax for declaring Range:

Ranges <variable> for <target field>.

Select..EndSelect: is a open SQL statement used for retrieving multiple records from the
database. It is a looping statement, where in, for each select statement execution, it retrieves
single record, and the no. of times the select query execution depends on the no. of records
satisfying the condition. If there are more select queries, it increases network traffic and
thereby decreases performance. Because of this reason, it is recommended to minimize the
usage of select..endselect and instead use select into table statement and retrieve the
required no. of records using one select statement execution and store the retrieved data into
an internal table.

Order by clause: is used in select query and it retrieves the data from database in sorted order
of the specified field. By default, it retrieves in ascending order, to retrieve in descending
order, we need to use the addition descending along with order by clause.

Interactive Classical reporting:

This is generated based on the user interaction in the runtime.

In classical interactive reporting: we can generate up to 21 lists. The first list is called as basic
list and the remaining 20 are called as secondary list.

SY-LSIND is the system field which stores the index OF NEXT LIST (secondary list). For the
basic list, index is zero and the secondary lists indexes ranges from 1 to 20.

As part of this we use following events.

1. At line-selection: This event is triggered when the user double clicks on a list value or a
single click on a hotspot list value. In this case, the line content where the user has
done the interaction is captured in the system field SY-LISEL and the line number is
captured in SY-LINNO .
2. Top-of-page: This event is triggered in the basic list and it can be handled to generate
the heading for the basic list.

3. Top-of-page during line-selection: This event is triggered in the secondary lists and it
can be handled to generate the heading for secondary list.

4. End-of-page: This event might be triggered in every list whenever the end of page is
reached. This event can be handled to generate the footer for the list pages.

Note:-

End-of-page event is triggered only when the end of page is reached, for this, we need
to control the number of lines per page. This is done by using line-count option as part
of report statement.

Note: If the no. of lines reserved for the page is consumed by TOP-OF-PAGE event or
TOP-OF-PAGE DURING LINE-SELECTION event itself, it leads to runtime error list page
overflow as the content cannot be fitted on the page.

No standard page heading: is the option used as part of report keyword which
suppresses the default page heading.

SY-LISEL - stores entire line content where the user has done the interaction.

Hotspot on: is an option used as part of write statement to display a column value as
hotspot (link to other).

Hide statement:

It is used after the write statement and it writes the value of a variable to the hide
memory area (invisible memory area).

This hide memory area gets refreshed whenever the at line-selection event is triggered
and it maintains only one value where the user has done the interaction. Based on this
value, we can get the content for the next list.

Get cursor field: It is used for identifying the field name and field value on the list where
the user has done the interaction..

Set parameter id:

It is used for setting the value of a parameter id in the global SAP memory. This value
can be retrieved by using get parameter id statement.

Joins:

Joins are used for retrieving data from multiple tables using one select query.

Joins are of two types:


i. Inner join

ii. Left outer join

For retrieving data from multiple tables using joins, the compared fields between two tables
must have the same property i.e. data types and size must be same. The field names need not
be same.

i. Inner join:

In this, the left hand side table is compared with right hand side table.

As part of this comparison, the value of the compared field from the left hand side row will be
compared with all the rows of the right hand side table. If any matching row is found it picks the
rows from left hand side and right hand side tables. If no matching row is found in the right
hand side table, SAP ignores the left hand side row also.

ii. left outer join:

It is similar to inner join but instead of ignoring the deficiency row, it picks the row from the
left hand side and the right hand side row fields is filled with 0 s and nulls(space) according
to data type.

Note: Instead of using joins in the select statement, it is recommended to create the views
on the corresponding tables and specify the view name as part of the select query.

By default the database view follows inner join.

Note: Line-size is the option as used as part of report statement to control the no. of
characters per line.

Sequence of events execution in Module Pool:

1. PBO

2. After User interaction in the runtime (enter key in input field, clicking a
button, selecting/deselecting a checkbox, selecting a radio button, selecting a value in
the dropdown)

a) PAI

b) PBO

3. Runtime --> f4 key in input field ---> POV

3. Runtime --> f1 key on screen element --> POH

Sequence of events execution in Selection Screen:


1. Initialization, at selection-screen output  Before selection screen is displayed for first
time

2. After User interaction in the runtime

Case 1: Enter key in input field  at selection-screen on <field>,at selection-screen, at


selection-screen output

Case 2: Clicking a button  at selection-screen, at selection-screen output

Case 3: Selecting/Deselecting a checkbox  at selection-screen, at selection-screen


output

Case 4: Selecting a radio button in radio button group  at selection-screen on radio


button group <group name>, at selection-screen, at selection-screen output

Sequence of events execution in L.P.S (List Processing screen):

Scenario 1: No selection-screen available

1. Load-of-program  used for initializing global variables

2. Top-of-page (if available)

3. Initialization (if available)

4. Start-of-selection

5. End-of-selection

Scenario 2: selection-screen available

1. Load-of-program

2. Top-of-page

3. Initialization

4. At selection-screen output  Selection screen displayed

On click of execute button of selection screen appl.toolbar

1. At selection-screen

2. Start-of-selection

On interaction of selection screen elements like button

1. At selection-screen

2. At selection-screen output
Logical Databases:

Standard LDB s:- responsible for retrieving data from HR Database Tables.

A LDB is associated with 2 programs

1. Selection Program (Include Program) Responsible for generating the selection screen
for reading the user input (contains parameter and select-options declarations)

2. Database Program (Report Program) Responsible for retrieving data from DB tables
(contains select queries)

A LDB can be associated with an executable program as part of program attributes.

LDB s are created / displayed using Logical Database Builder (SE36).

A LDB is collection of nodes. A Node represents a dictionary Object.

If a node is referring to a database table, then node name should be same as that of DB table.

Background Scheduling of Reports:

Foreground execution of reports:

1. Execute --> displays selection screen --> input values --> execute

2. Output in the form of List

Background scheduling of reports:

Advantages:

1. Automatic execution without user interaction

2. Should be executed automatically on a periodic basis

Procedure:

1. Identify the program name (Report) which needs to be scheduled in the background.

2. Check whether the program contains selection screen, if it contains selection screen,
create one or more variants

Variant is an object which is associated with input values of selection screen.

1. Create the Background job (SM36)

a) job name --> 845JOB1

b) job classification (priority) --> A


c) start condition --> IMMEDIATE

d) define step

i) program name --> Z845_REP15

ii) variant name --> VAR1

e) save the job --> job gets released

Note: Once the job is released , job gets executed depending on the job start
condition

2. Check the job execution status (SM37)

Note: Once the job is executed, the output associated with the job will be stored as a
spool request which can be viewed through 'SP01' /
Business workplace

Spool request is an object which is associated with output list

To schedule the job dynamically, 3 F.M's are used

1. job_open

2. job_submit

3. job_close
Hierararchial Report- for all entires

Example: Hierarchical Report (Item Internal table data overwritten by select query in the
loop)

report z830rep1.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak,


vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak type ty_vbak.

types : begin of ty_vbap,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
end of ty_vbap.
data : t_vbap type table of ty_vbap,
wa_vbap type ty_vbap.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform getsalesitems.
if t_vbap is not initial.
perform displaysalesdata.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Orders' type 'I'.
endif.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form getsalesitems .
loop at t_vbak into wa_vbak.
select vbeln posnr matnr
from vbap
into table t_vbap
where vbeln = wa_vbak-vbeln.
endloop.
endform. " GETSALESITEMS

form displaysalesdata .
loop at t_vbak into wa_vbak. "header internal table
format color 3.
write :/ wa_vbak-vbeln,
wa_vbak-erdat,
wa_vbak-erzet,
wa_vbak-ernam.
format color off.
loop at t_vbap into wa_vbap where vbeln = wa_vbak-vbeln. "item internal table
format color 7.
write :/5 wa_vbap-vbeln,
wa_vbap-posnr,
wa_vbap-matnr.
format color off.
endloop.
endloop.
endform. " DISPLAYSALESDATA

Example: Hierarchical Report (Select inside loop-Performance issue)

report z830rep2.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak,


vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak type ty_vbak.

types : begin of ty_vbap,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap type ty_vbap.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform getsalesitems.
if t_vbap is not initial.
perform displaysalesdata.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Orders' type 'I'.
endif.
form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form getsalesitems .
loop at t_vbak into wa_vbak.
select vbeln posnr matnr
from vbap
appending table t_vbap
where vbeln = wa_vbak-vbeln.
endloop.
endform. " GETSALESITEMS

form displaysalesdata .
loop at t_vbak into wa_vbak. "header internal table
format color 3.
write :/ wa_vbak-vbeln,
wa_vbak-erdat,
wa_vbak-erzet,
wa_vbak-ernam.
format color off.
loop at t_vbap into wa_vbap where vbeln = wa_vbak-vbeln. "item internal table
format color 7.
write :/5 wa_vbap-vbeln,
wa_vbap-posnr,
wa_vbap-matnr.
format color off.
endloop.
endloop.
endform. " DISPLAYSALESDATA

Example: Hierarchical Report (For all Entries-To avoid select inside loop)

report z830rep3.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak,


vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak type ty_vbak.

types : begin of ty_vbap,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap type ty_vbap.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform getsalesitems.
if t_vbap is not initial.
perform displaysalesdata.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Orders' type 'I'.
endif.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form getsalesitems .
* loop at t_vbak into wa_vbak.
* select vbeln posnr matnr
* from vbap
* appending table t_vbap
* where vbeln = wa_vbak-vbeln.
* endloop. "not recommended to write select inside loop
select vbeln posnr matnr
from vbap
into table t_vbap
for all entries in t_vbak
where vbeln = t_vbak-vbeln.
endform. " GETSALESITEMS

form displaysalesdata .
loop at t_vbak into wa_vbak. "header internal table
format color 3.
write :/ wa_vbak-vbeln,
wa_vbak-erdat,
wa_vbak-erzet,
wa_vbak-ernam.
format color off.
loop at t_vbap into wa_vbap where vbeln = wa_vbak-vbeln. "item internal table
format color 7.
write :/5 wa_vbap-vbeln,
wa_vbap-posnr,
wa_vbap-matnr.
format color off.
endloop.
endloop.
endform. " DISPLAYSALESDATA
Example: Control Break Events

report z830rep4 no standard page heading.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4970' to '4975' no-extension.

types : begin of ty_vbap,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
netwr type vbap-netwr,
end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap type ty_vbap.

start-of-selection.
perform getsalesitems.
if t_vbap is not initial.
perform displaysalesitems.
else.
message 'No Sales Items for given range' type 'I'.
endif.

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
where vbeln in so_vbeln.

endform. " GETSALESITEMS

form displaysalesitems .
sort t_vbap by vbeln.
loop at t_vbap into wa_vbap.

at first.
write :/15 'SALES DOCUMENT ITEMS WITH PRICES' color 3.
uline.
endat.

at new vbeln.
format color 7.
write :/ 'Sales Document No :',wa_vbap-vbeln.
format color off.
endat.

format color 2.
write :/5 wa_vbap-posnr,
wa_vbap-matnr,
wa_vbap-netwr.
format color off.

at end of vbeln.
format color 1.
sum.
write :/ 'Sum of ',wa_vbap-vbeln,' is',wa_vbap-netwr under wa_vbap-netwr.
format color off.
endat.

at last.
format color 3.
sum.
write :/ 'Grand Total is ',wa_vbap-netwr under wa_vbap-netwr.
format color off.
endat.

endloop.
endform. " DISPLAYSALESITEMS

Example: Control Break Events-On Change of event instead of AT New event

report z830rep5 no standard page heading.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4970' to '4975' no-extension.

types : begin of ty_vbap,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
netwr type vbap-netwr,
end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap type ty_vbap.
start-of-selection.
perform getsalesitems.
if t_vbap is not initial.
perform displaysalesitems.
else.
message 'No Sales Items for given range' type 'I'.
endif.

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
where vbeln in so_vbeln.

endform. " GETSALESITEMS

form displaysalesitems .
sort t_vbap by vbeln.
loop at t_vbap into wa_vbap.

at first.
write :/15 'SALES DOCUMENT ITEMS WITH PRICES' color 3.
uline.
endat.

* at new vbeln.
on change of wa_vbap-vbeln.
format color 7.
write :/ 'Sales Document No :',wa_vbap-vbeln.
format color off.
endon.
* endat.

format color 2.
write :/5 wa_vbap-posnr,
wa_vbap-matnr,
wa_vbap-netwr.
format color off.

at end of vbeln.
format color 1.
sum.
write :/ 'Sum of ',wa_vbap-vbeln,' is',wa_vbap-netwr under wa_vbap-netwr.
format color off.
endat.

at last.
format color 3.
sum.
write :/ 'Grand Total is ',wa_vbap-netwr under wa_vbap-netwr.
format color off.
endat.

endloop.
endform. " DISPLAYSALESITEMS

Example: Control Break events – At new <field name> (Not the First Field of the internal
table)

report z830rep6 no standard page heading.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4970' to '4975' no-extension.

types : begin of ty_vbap,


posnr type vbap-posnr,
vbeln type vbap-vbeln,
matnr type vbap-matnr,
netwr type vbap-netwr,
end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap type ty_vbap.

start-of-selection.
perform getsalesitems.
if t_vbap is not initial.
perform displaysalesitems.
else.
message 'No Sales Items for given range' type 'I'.
endif.

form getsalesitems .
select posnr vbeln matnr netwr
from vbap
into table t_vbap
where vbeln in so_vbeln.
endform. " GETSALESITEMS

form displaysalesitems .
sort t_vbap by vbeln.
loop at t_vbap into wa_vbap.

at first.
write :/15 'SALES DOCUMENT ITEMS WITH PRICES' color 3.
uline.
endat.

at new vbeln.
format color 7.
write :/ 'Sales Document No :',wa_vbap-vbeln.
format color off.
endat.

format color 2.
write :/5 wa_vbap-posnr,
wa_vbap-matnr,
wa_vbap-netwr.
format color off.

at end of vbeln.
format color 1.
sum.
write :/ 'Sum of ',wa_vbap-vbeln,' is',wa_vbap-netwr under wa_vbap-netwr.
format color off.
endat.

at last.
format color 3.
sum.
write :/ 'Grand Total is ',wa_vbap-netwr under wa_vbap-netwr.
format color off.
endat.

endloop.
endform. " DISPLAYSALESITEMS
Example: Select-EndSelect to retrieve multiple records

report z830rep7.

types : begin of ty_kna1,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
end of ty_kna1.

data wa_kna1 type ty_kna1.

*select kunnr land1 name1


* from kna1
* into table wa_kna1
* up to 100 rows. "syntax error

select kunnr land1 name1


from kna1
into wa_kna1
up to 100 rows.
write :/ wa_kna1-kunnr,
wa_kna1-land1,
wa_kna1-name1.
endselect.
hide memory area

interactive classical reporting flow

interactive classical reporting


static vs interactive reporting

Example: Interactive Classical Reporting (End-of-page event not triggered)

report z830rep8 no standard page heading.

data gv_kunnr type kna1-kunnr.


select-options so_kunnr for gv_kunnr default '0000001000' to '0000001010'.

types : begin of ty_customers,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
end of ty_customers.

data : t_customers type table of ty_customers,


wa_customers type ty_customers.

types : begin of ty_salesorders,


vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_salesorders.

data : t_salesorders type table of ty_salesorders,


wa_salesorders type ty_salesorders.
types : begin of ty_salesitems,
vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
netwr type vbap-netwr,
end of ty_salesitems.

data : t_salesitems type table of ty_salesitems,


wa_salesitems type ty_salesitems.

data : gv_fname type string,


gv_fvalue type matnr.

start-of-selection.
perform getcustomers.
if t_customers is not initial.
perform displaycustomers.
else.
message 'No Customers' type 'I'.
endif.

top-of-page.
write :/15 'CUSTOMER MASTER DATA' color 7.

top-of-page during line-selection.


case sy-lsind.
when 1.
write :/15 'SALES ORDERS' color 7.
when 2.
write :/15 'SALES ITEMS' color 7.
endcase.

end-of-page.
uline.
write :/15 'GENSOFT TECHNOLOGIES' color 3.
write :/20 'Page no :',sy-pagno color 1.

at line-selection.
case sy-lsind.
when 1.
* message 'Hi' type 'I'.
* write :/ 'Content of selected line is ',sy-lisel.
clear gv_kunnr.
gv_kunnr = sy-lisel+0(15). "offset logic-extracting portion of string
if gv_kunnr is not initial.
* unpack gv_kunnr to gv_kunnr. "(or)
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = gv_kunnr
importing
output = gv_kunnr.

perform getsalesorders.
if t_salesorders is not initial.
perform displaysalesorders.
else.
message 'No Sales Orders for selected customer' type 'I'.
endif.
endif.
when 2.
perform getsalesitems.
if t_salesitems is not initial.
perform displaysalesitems.
else.
message 'No Sales items' type 'I'.
endif.
when 3.
get cursor field gv_fname value gv_fvalue.
if gv_fname = 'WA_SALESITEMS-MATNR'.
set parameter id 'MAT' field gv_fvalue.
call transaction 'MM03'.
else.
message 'Please select only Material No' type 'I'.
endif.
endcase.

form getcustomers .
select kunnr land1 name1
from kna1
into table t_customers
where kunnr in so_kunnr.
endform. " GETCUSTOMERS

form displaycustomers .
uline.
format color 2.
write :/(16) 'Customer No',(7) 'Country','Customer Name'.
format color off.
uline.
format color 3.
loop at t_customers into wa_customers.
write :/(15) wa_customers-kunnr hotspot on,
sy-vline,
(6) wa_customers-land1,
sy-vline,
wa_customers-name1.
endloop.
format color 3.
endform. " DISPLAYCUSTOMERS

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_salesorders
where kunnr = gv_kunnr.
endform. " GETSALESORDERS

form displaysalesorders .
loop at t_salesorders into wa_salesorders.
write :/ wa_salesorders-vbeln,
wa_salesorders-erdat,
wa_salesorders-erzet,
wa_salesorders-ernam.
hide wa_salesorders-vbeln.
endloop.
endform. " DISPLAYSALESORDERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_salesitems
where vbeln = wa_salesorders-vbeln.
endform. " GETSALESITEMS

form displaysalesitems .
loop at t_salesitems into wa_salesitems.
write :/ wa_salesitems-vbeln,
wa_salesitems-posnr,
wa_salesitems-matnr,
wa_salesitems-netwr.
endloop.
endform. " DISPLAYSALESITEMS

Example: Interactive Classical Reporting (End-of-page event triggered)

report z830rep9 no standard page heading


line-count 10(3).

data gv_kunnr type kna1-kunnr.


select-options so_kunnr for gv_kunnr default '0000001000' to '0000001010'.

types : begin of ty_customers,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
end of ty_customers.

data : t_customers type table of ty_customers,


wa_customers type ty_customers.

types : begin of ty_salesorders,


vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_salesorders.

data : t_salesorders type table of ty_salesorders,


wa_salesorders type ty_salesorders.

types : begin of ty_salesitems,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
netwr type vbap-netwr,
end of ty_salesitems.

data : t_salesitems type table of ty_salesitems,


wa_salesitems type ty_salesitems.

data : gv_fname type string,


gv_fvalue type matnr.

start-of-selection.
perform getcustomers.
if t_customers is not initial.
perform displaycustomers.
else.
message 'No Customers' type 'I'.
endif.

top-of-page.
write :/15 'CUSTOMER MASTER DATA' color 7.

top-of-page during line-selection.


case sy-lsind.
when 1.
write :/15 'SALES ORDERS' color 7.
when 2.
write :/15 'SALES ITEMS' color 7.
endcase.

end-of-page.
uline.
write :/15 'GENSOFT TECHNOLOGIES' color 3.
write :/20 'Page no :',sy-pagno color 1.

at line-selection.
case sy-lsind.
when 1.
* message 'Hi' type 'I'.
* write :/ 'Content of selected line is ',sy-lisel.
clear gv_kunnr.
gv_kunnr = sy-lisel+0(15). "offset logic-extracting portion of string
if gv_kunnr is not initial.
* unpack gv_kunnr to gv_kunnr. "(or)
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = gv_kunnr
importing
output = gv_kunnr.

perform getsalesorders.
if t_salesorders is not initial.
perform displaysalesorders.
else.
message 'No Sales Orders for selected customer' type 'I'.
endif.
endif.
when 2.
perform getsalesitems.
if t_salesitems is not initial.
perform displaysalesitems.
else.
message 'No Sales items' type 'I'.
endif.
when 3.
get cursor field gv_fname value gv_fvalue.
if gv_fname = 'WA_SALESITEMS-MATNR'.
set parameter id 'MAT' field gv_fvalue.
call transaction 'MM03'.
else.
message 'Please select only Material No' type 'I'.
endif.
endcase.

form getcustomers .
select kunnr land1 name1
from kna1
into table t_customers
where kunnr in so_kunnr.
endform. " GETCUSTOMERS

form displaycustomers .
uline.
format color 2.
write :/(16) 'Customer No',(7) 'Country','Customer Name'.
format color off.
uline.
format color 3.
loop at t_customers into wa_customers.
write :/(15) wa_customers-kunnr hotspot on,
sy-vline,
(6) wa_customers-land1,
sy-vline,
wa_customers-name1.
endloop.
format color 3.
endform. " DISPLAYCUSTOMERS

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_salesorders
where kunnr = gv_kunnr.
endform. " GETSALESORDERS

form displaysalesorders .
loop at t_salesorders into wa_salesorders.
write :/ wa_salesorders-vbeln,
wa_salesorders-erdat,
wa_salesorders-erzet,
wa_salesorders-ernam.
hide wa_salesorders-vbeln.
endloop.
endform. " DISPLAYSALESORDERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_salesitems
where vbeln = wa_salesorders-vbeln.
endform. " GETSALESITEMS

form displaysalesitems .
loop at t_salesitems into wa_salesitems.
write :/ wa_salesitems-vbeln,
wa_salesitems-posnr,
wa_salesitems-matnr,
wa_salesitems-netwr.
endloop.
endform. " DISPLAYSALESITEMS

Example: Interactive Classical Reporting (Run Time error)

report z830rep9 no standard page heading


line-count 5(3).

data gv_kunnr type kna1-kunnr.


select-options so_kunnr for gv_kunnr default '0000001000' to '0000001010'.

types : begin of ty_customers,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
end of ty_customers.
data : t_customers type table of ty_customers,
wa_customers type ty_customers.

types : begin of ty_salesorders,


vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_salesorders.

data : t_salesorders type table of ty_salesorders,


wa_salesorders type ty_salesorders.

types : begin of ty_salesitems,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
netwr type vbap-netwr,
end of ty_salesitems.

data : t_salesitems type table of ty_salesitems,


wa_salesitems type ty_salesitems.

data : gv_fname type string,


gv_fvalue type matnr.

start-of-selection.
perform getcustomers.
if t_customers is not initial.
perform displaycustomers.
else.
message 'No Customers' type 'I'.
endif.

top-of-page.
write :/15 'CUSTOMER MASTER DATA' color 7.
uline.

top-of-page during line-selection.


case sy-lsind.
when 1.
write :/15 'SALES ORDERS' color 7.
when 2.
write :/15 'SALES ITEMS' color 7.
endcase.

end-of-page.
uline.
write :/15 'GENSOFT TECHNOLOGIES' color 3.
write :/20 'Page no :',sy-pagno color 1.

at line-selection.
case sy-lsind.
when 1.
* message 'Hi' type 'I'.
* write :/ 'Content of selected line is ',sy-lisel.
clear gv_kunnr.
gv_kunnr = sy-lisel+0(15). "offset logic-extracting portion of string
if gv_kunnr is not initial.
* unpack gv_kunnr to gv_kunnr. "(or)
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = gv_kunnr
importing
output = gv_kunnr.

perform getsalesorders.
if t_salesorders is not initial.
perform displaysalesorders.
else.
message 'No Sales Orders for selected customer' type 'I'.
endif.
endif.
when 2.
perform getsalesitems.
if t_salesitems is not initial.
perform displaysalesitems.
else.
message 'No Sales items' type 'I'.
endif.
when 3.
get cursor field gv_fname value gv_fvalue.
if gv_fname = 'WA_SALESITEMS-MATNR'.
set parameter id 'MAT' field gv_fvalue.
call transaction 'MM03'.
else.
message 'Please select only Material No' type 'I'.
endif.
endcase.

form getcustomers .
select kunnr land1 name1
from kna1
into table t_customers
where kunnr in so_kunnr.
endform. " GETCUSTOMERS

form displaycustomers .
format color 2.
write :/(16) 'Customer No',(7) 'Country','Customer Name'.
format color off.
uline.
format color 3.
loop at t_customers into wa_customers.
write :/(15) wa_customers-kunnr hotspot on,
sy-vline,
(6) wa_customers-land1,
sy-vline,
wa_customers-name1.
endloop.
format color 3.
endform. " DISPLAYCUSTOMERS

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_salesorders
where kunnr = gv_kunnr.
endform. " GETSALESORDERS

form displaysalesorders .
loop at t_salesorders into wa_salesorders.
write :/ wa_salesorders-vbeln,
wa_salesorders-erdat,
wa_salesorders-erzet,
wa_salesorders-ernam.
hide wa_salesorders-vbeln.
endloop.
endform. " DISPLAYSALESORDERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_salesitems
where vbeln = wa_salesorders-vbeln.
endform. " GETSALESITEMS

form displaysalesitems .
loop at t_salesitems into wa_salesitems.
write :/ wa_salesitems-vbeln,
wa_salesitems-posnr,
wa_salesitems-matnr,
wa_salesitems-netwr.
endloop.
endform. " DISPLAYSALESITEMS
Transport management:
Every object that an ABAP consultant develops must be transported (moved) from
development client to quality client and then to production client.
For this, we need to store the object inside a transportable package, so that the object is
assigned to Transport request / Change Request.
A Transport request is a collection of one or more tasks.
Every task can be associated with one or more objects.
Every user should create their own task/s under main request for storing their respective
objects.
For Creating/Managing transport requests/tasks, we use Transport Organizer tool (SE09 /
SE10).
There are two types of transport requests:
 Workbench Request Captures the changes made to repository objects (executable
programs, include programs / su routine pool…. / di tionary o je ts ta les, sear h
helps…..
 Customizing Request Captures configuration changes / data related changes.
Status of the tasks:
 Unclassified: The task which is not associated with any objects.
 Development/Correction: It is a task which is under development i.e it contains atleast
one object.
Once the development is done i.e once all the objects assigned to us are finished with
the development, we need to release our task and send the screenshot of the same to
the owner of the request.
A Task can be released only when all the objects inside that task are in active state.
Once all the tasks are released, the owner of the request will release the main request
which indicates that the request is ready for transportation.

Copying Task from one request to other Request:


For this, create another request with a task and ensure atleast one object is stored in
this new task (atleast dummy object) or change the status of the new task from
unclassified to development/correction MANUALLY.
Now, In SE09, double click on the source task , copy the objects from source task and
paste the same in the target task. Once copied, delete the objects from the source task
and then delete the source task.
Version Management:
It is a process of comparing multiple versions of the objects to identify the similarities
and differences so that at any point of time, we can retrieve back the older versions.
Whenever we retrieve the older version, the current version will be overwritten with
the new version and gets stored in the new request.
The version comparisons can be between the same client or across the clients.

transport request and task

Transport Requests:

objects ---> save ===> local object ($tmp) --> default package provided by SAP
--> will not be assigned to change request
(transport request)
--> cannot be transported
---> package ---> assigned to change request

5 abap const --> development


5 user ids ---> assigned to dev.client (800)

sapuser
gensoft
abc
xyz
lmn
1. WORKBENCH REQUEST --> CAPTURES CHANGES MADE TO CROSS-CLIENT
TABLES
(CLIENT INDEPENDENT)
REPOSITORY OBJECTS & DICTIONARY OBJECTS

2. CUSTOMIZING REQUEST --> CAPTURES CHANGES MADE TO CLIENT SPECIFIC


TABLES
(CLIENT DEPENDENT)
--> CONFIGURATION RELATED DATA CHANGES
SPRO--> DEFINE MAT.TYPE (TRAINING) --> Configuration

Copying tasks from one request to another


Merge request
MODULE POOL PROGRAMMING (DIALOG PROGRAMMING):

PURPOSE:

1. Design new SAP Transactions which are specific to customers

2. Enhancing Existing SAP transactions (used along with enhancements)  cross-apps

Dialog Programming  Screen painter tool (SE51)

Screen painter tool  Contains 4 sections

1. Attributes  Description, Type of screen (Normal , Subscreen, Dialog box)


2. Layout  Design the Transaction with different elements
3. Flowlogic  Implement the events in the corresponding module definitions
4. Element List  SAP internal use  contains elements information placed on the screen
layout

Note: A module pool program can be created either with or without TOP include
program.
TOP include program can be used for declaring global variables, subroutine definitions
and module definitions.
A TOP include program must end with TOP .
A Module pool program cannot be executed directly; it needs to be associated with a
transaction code.

Procedure for developing Module pool Programs:

1. Create a module pool program in object navigator (SE80) (with top include-
recommended)
2. Create the initial screen using screen painter tool and provide the description and
choose the type of screen in Attributes tab
3. Design the screen layout with different elements (textfields, i/o fields,
che k o es,radio utto s,ta le o trol….) a d also set the appropriate properties for
each of the elements
4. Implement the events in the flowlogic by defining the corresponding modules
5. Repeat the steps 2,3,4 for each of the screens
6. Create the t-code for the module pool program by associating with the initial screen
of the transaction

Events in Dialog programming:

1. PBO 2. PAI 3. POV 4. POH


PBO (Process before output): This event functionality is similar to At Selection-screen
output event in case of selection screen. This event is triggered in the following cases:
a) Whenever the screen is displayed for the first time
b) After PAI event
This event can be handled for the following cases:
1. To initialize the screen elements with the default values
2. To Refresh the screen appearance after the user interaction in the
runtime

PAI (Process after Input): This event functionality is similar to At selection-screen


event in case of selection-screen. This event is triggered in the following cases:
a) When the user presses enter key in the input field
b) When the user selects/deselects a checkbox or when the user selects a radio
button
c) When the user selects a value in the dropdown list box
d) When the user scrolls in the table control
e) When the user clicks on the pushbutton
This event can be handled to provide an action whenever a user performs an
action in/on a screen element in the runtime

POV (Process on value-request): This event functionality is similar to At selection-


screen on value-request event in case of selection-screen. This event is triggered in the
following case:
a) When the user presses f4 key in the input field
This event can be handled to provide custom F4 values whenever a user presses F4 key
in the screen input field.

POH (Process on help-request): This event functionality is similar to At selection-screen


on help-request event in case of selection-screen. This event is triggered in the
following case:
a) When the user presses f1 key in/on the screen element.

This event can be handled to provide custom F1 help whenever a user presses F1 key
in/on the screen element.

Note: Whenever we need to refer to the screen element inside the program, we need to
declare a variable with the same name and type as that of screen element.

TABSTRIP CONTROL: A tabstrip control is a collection of TAB Buttons. Each Tab button
should be associated with a subscreen. A subscreen cannot be placed directly on top of
normal screen; it should be placed on top of a subscreen area. We can use same /
different subscreen areas for each tab.
A Subscreen area is a collection of subscreens.
Note: Whenever a normal screen/subscreen layout contains tabstrip control, it should
be declared explicitly by using controls keyword., otherwise it leads to runtime error
control not found .

The datatype for tabstrip control is tabstrip .

Syntax for Declaring Tabstrip control:

Controls <tabstrip name> type tabstrip.

Note: By Default, The first tab will be active in the Tabstrip control. We can use the
property ACTIVETAB of tabstrip control to activate a specific tab button in tabstrip
control. Each Tab should be associated with a subscreen. Since Subscreen cannot be
placed on top of normal screen, we need to place subscreen area in each tab and then
in the runtime, the subscreen will sit on TOP OF subscreen area. We can use
same/different subscreen area s FOR each tab. The no. of calls to CALL SUBSCREEN
statement depends on the no. of subscreen areas.

Note: Subscreens should be called from the flowlogic section.

Syntax for calling subscreens:

Call subscreen <subscreen area> including <subscreen program name> <subscreen


no>.

TABLE CONTROL:

It is used for displaying the data in the form of rows and columns.

Note: Whenever a screen / subscreen contains table control component and when we
do syntax check, it gives error as loop endloop is required in both PBO and PAI.

In order to avoid this error in the design time, initially provide loop and endloop in both
PBO and PAI events.

Note: Whenever a screen/subscreen layout contains table control, it should be declared


explicitly by using controls keyword. The data type for table control is tableview . If it
not declared, it leads to runtime error control not found .

Syntax for declaring Table control:

Controls <table control name> type tableview using screen <screen no>.
By default, Table control vertical scrolling property is disabled. To enable it, we need to
set the LINES property of table control.

Validating Module pool transactions:

1. Automatic Field validations: In this, the validations are performed by SAP itself based
on the properties of the screen field (transaction field) set at screen level(frontend) or
properties of the field maintained at dictionary level (database level). In this, the
validation messages are provided by SAP itself.

Validation messages:
1. If mandatory field value is not entered  message will be provided by SAP  fill in
all the required fields
2. If i valid ou tr ke / la guage ke / u its of easure e t … is e tered 
message will be provided by SAP  Invalid values (entry doesn t e ist i …..)
3. If invalid date is entered  message will be provided by SAP  invalid date

Eg:- Mandatory fields, Invalid values, Invalid date format

2. Flow logic validations: In this, the validations are performed by SAP itself based on the
values maintained for the field at the flow logic level. In this, the validation messages
are provided by SAP itself.

Flowlogic section:
Eg: field lfa1-land1 values ( AF , AR , IN )
Field mara-mtart values ( COUP , FGTR , ROH )

Eg:- field emp-empsal values between 10000 and 20000

Note: If any of the screen field fails the flow logic validations, the other fields on the
screen will be disabled and doesn t allow the user to input the values in the other fields.
This can be avoided by grouping the logically related fields using chain-endchain
statement.
Eg:-
Flowlogic section:

Chain.
Field lfa1-lifnr.
Field lfa1-land1 values ( AF , AR , IN ).
Endchain.

chain.
field mara-matnr.
field mara-mtart values ('COUP','FGTR','ROH').
endchain.

3. Module pool validations: These validations are used for performing field specific
validations. In this, the validation messages must be provided by developer itself.

Syntax:

Flowlogic section:

Field <field name> module <module name>.

Note: Define the module with validation logic and validation message in any of the
include programs.

At Exit-command module

Note: If a screen field fails any of the above validations, the user cannot exit the
transaction unless the validation is correct or in some cases user may require to
forcefully exit the transactions. For forceful exit, we need to consider a button whose
functionality should be similar to that of cancel button. For this, we need to set an
additional property for the button i.e FCTTYPE to E (function type to exit command)
along with the function code. Apart from this additional property, there should be
corresponding at exit-command module in the PAI event. As part of this module
definition, we need to implement the logic to exit the transaction forcefully. This at
exit-command module is executed only when the user clicks on the button whose
function type is set to E .

Syntax for at exit-command:

PAI event:

Module <module name> at exit-command.

As part of module definition, implement the logic to exit the transaction (leave
program).

start execution of module pool :-

before displaying the screen ---> PBO event triggered

Displays screen ---> user will perform actions (click button,press enter key in i/o field,

press enter in dropdown,

select/deselect checkbox, select radiobutton.....)

---> based on action ---> SAP Triggers PAI event first and then
again triggers PBO event.

sequence of module pool events execution

2nd jan requirement

Transaction design and enhancement


SMARTFORMS

Every Business contains Business Documents like Enquiry, Quotation, Purchase Order, Sales
Order, Invoice, Delivery Schedule....

To Design these Business Documents Templates, We use word processing tools like SAP Scripts,
Smartforms, ADOBE Forms.

SAP Scripts ---> Form Painter tool (T-code 'SE71')

SMARTFORMS ---> Smartforms tool (T-code 'SMARTFORMS')

ADOBE Forms ---> Form Builder tool (T-code 'SFP')

SMARTFORMS:

SMARTFORMS --> used for Designing layouts (templates) of Business Documents

a) Design layout --> SMARTFORMS tool (T-code 'SMARTFORMS')

--> Activate smartform --> Generates F.M dynamically

--> F.M will act as driver program/print program --> directly executed for testing

(or) b) Executable program --> Call smartform F.M

T-code for SMARTFORMS is ͚SMARTFORMS͛.

1. General Settings

a) Form Attributes --> Provide Description and it contains administration information


(username, date, time, package....)

b) Form Interface --> In this, we declare the parameters which needs to be passed to the
smartform while calling it (import, export, tables...)

c) Global definitions ---> In this, we declare the global variables (individual variables, work area,
internal table, types declaration...), provide select
statements

2. Pages and Windows --> In this, we design the pages layout and windows

Note: As part of driver program, it is recommended not to directly call the smartform F.M as
this F.M name depends on the client numbering formats of each client, so when we transport
the smartform to quality/production clients and when we activate the smartform there, it
generates new F.M whose name depends on the numbering sequence of that particular client.
So it is recommended to get the smartform F.M name dynamically and it is done by calling the
std.F.M 'SSF_FUNCTION_MODULE_NAME' which takes smartform name as input and returns
the associated smartform F.M name which is specific to that particular client.
Note: To skip the print dialog box while calling the smartform from driver program, we need to
prepare and pass the control parameters while calling the smartform F.M.

dynamic generation of smartform function module

smartform creation and execution


Windows

Requirement 1- Displaying Static Text


Requirement 2 -Passing Parameters to smartforms

Example: SMARTFORMS with Text Object containing static text


Activate the smartform, it generates a function module dynamically

Executable program: Driver Program / Print Program

REPORT ZCALLSMFORM.

*CALL FUNCTION '/1BCDWB/SF00000351'. "not recommended

* get the smartform function module name dynamically


data gv_fname type RS38L_FNAM.
CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
EXPORTING
FORMNAME = 'ZSMFORM1'
IMPORTING
FM_NAME = gv_fname
EXCEPTIONS
NO_FORM =1
NO_FUNCTION_MODULE =2
OTHERS = 3.

if sy-subrc eq 0.
* call the smartform
* call function gv_fname. "will not skip print dialog box

data gv_ctrl_param type SSFCTRLOP.


gv_ctrl_param-no_dialog = 'X'.
gv_ctrl_param-preview = 'X'.

call function gv_fname


EXPORTING
CONTROL_PARAMETERS = gv_ctrl_param. "skips print dialog box

elseif sy-subrc eq 1.
message 'No Form exists' type 'I'.
elseif sy-subrc eq 2.
message 'No function module exists for smartform' type 'I'.
elseif sy-subrc eq 3.
message 'Unknown error' type 'I'.
endif.

Example: Passing parameters to Smart forms

For this, we need to specify the parameters in Form interface of smartforms and pass the value
for this parameter while calling the smartform F.M from driver program.
Requirement:

1. Pass sales doc as input value to smartforms

2. Based on this sales doc received, smartform should retrieve corresponding header
data(vbak) and item data(vbap) of the sales document and display the same

Table 1: VBAK (Sales Document Header data)

Primary key fields: mandt (client no),

vbeln (sales doc no)

Table 2: VBAP (Sales Document Item data)

Primary key fields: mandt (client no), vbeln (sales doc no),

Posnr (sales doc item no)

Relationship: Each Sales Doc of vbak table can contain one or more sales items in VBAP table

Eg:-

4969(sales doc) of vbak table contains 1 item in vbap table

4970(sales doc) of vbak table contains 4 items in vbap table


Driver Program for above Smartform:

REPORT ZCALLSMFORM2.

PARAMETERS p_vbeln type vbak-vbeln.

* get the smartform function module name


data gv_fname type RS38L_FNAM.

CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'


EXPORTING
FORMNAME = 'ZSMFORM2'
IMPORTING
FM_NAME = gv_fname.

* call the smartform function module


*call function gv_fname. "runtime error as mandatory parameter missing

* prepare control parameters to skip print dialog box


data gv_ctrl_param type SSFCTRLOP.
gv_ctrl_param-no_dialog = 'X'.
gv_ctrl_param-preview = 'X'.
call function gv_fname
EXPORTING
CONTROL_PARAMETERS = gv_ctrl_param
i_vbeln = p_vbeln.

smartform tables
smartforms requirement-exercise

TABLES IN SMARTFORMS

1. Create 4 windows

main window (default) --> SalesItems

3 secondary windows

a) window 1 --> SalesHeader

b) window 2 --> Logo

b) window 3 --> Footer


2. Declare the required parameters for smartform

form interface :-

import :- ls_vbak type zcvbak

tables :- lt_vbap like zcvbap


3. Adjust the windows accordingly in the form painter
4. Upload the logo(.bmp image) using se78 and create graphics object as part of logo window.

Provide the name of the logo

5. As part of header window, create text element and provide the following

6. As part of footer window, create text element and provide the following page
no : &sfsy-page&
7. As part of SalesItems window (main window), create table object

Note: Table object creates header, main area, footer sections

a) Define 2 table lines (TABLE tab)

At table level, by default sap provides line type (%ltype1), rename this to meaningful
name(linetype1)

Draw 4 cells as part of linetype1

Right click on linetype1, create emptyline underneath, sap provides line type, rename it to
linetype2

linetype1 --> 4 cells, linetype2 --> 1 cell


b) Provide the internal table for the table object

Note : declare a work area as part of global definitions 'global data' tab

ls_vbap type zcvbap

'DATA' tab in tables object:-


internal table

lt_vbap into ls_vbap

c) At the table level, create the table line as part of header

table line --> linetype1

SAP creates 4 cells based on linetype1


Create text element as part of each cell and provide some static text

cell 1 --> text element --> sales doc

cell 2 --> text element --> item no

cell 3 --> text element --> material

cell 4 --> text element --> net value

d) At the table level, create the table line as part of main area

table line --> linetype1

SAP creates 4 cells based on linetype1

Create text element as part of each cell and provide the symbol fields appropriately

cell 5 --> text element --> &ls_vbap-vbeln&

cell 6 --> text element --> &ls_vbap-posnr&

cell 7 --> text element --> &ls_vbap-matnr&

cell 8 --> text element --> &ls_vbap-netwr&


e) Declare a variable 'lv_total' type I (integer) as part of global declarations 'global data' tab

Note: Specify variable 'lv_total' as part of initialization in the output parameter so that
'warning' 'lv_total͛ has no defined value is suppressed.
f) Specify the Calculation as part of table level

Calculation tab at table object level:-

Operation fieldname target fieldname time

total ls_vbap-netwr lv_total after loop

g) At the table level, create the table line as part of footer area

table line --> linetype2

SAP creates 1 cell based on linetype2

Create text element as part of the cell and provide the symbol fields appropriately

cell 9 --> text element -->Total value is : &lv_total&


Save and activate the smartform

Driver Program.

REPORT ZCALLSMFORM3.

PARAMETERS p_vbeln type vbak-vbeln OBLIGATORY.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data wa_vbak type ty_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data t_vbap type table of ty_vbap.

* get the smartform F.M dynamically


data gv_fname type rs38l_fnam.
CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
EXPORTING
FORMNAME = 'ZSMFORM3'
IMPORTING
FM_NAME = gv_fname.
if gv_fname is not INITIAL.
* get sales document header data
select single vbeln erdat erzet ernam
from vbak
into wa_vbak
where vbeln = p_vbeln.
if sy-subrc eq 0.
* get sales items data
select vbeln posnr matnr netwr
from vbap
into table t_vbap
where vbeln = p_vbeln.
if sy-subrc eq 0.
* prepare control parameters to skip print dialog
data wa_ctrl_param type SSFCTRLOP.
wa_ctrl_param-no_dialog = 'X'.
wa_ctrl_param-preview = 'X'.

* call the smartform F.M


call function gv_fname
EXPORTING
CONTROL_PARAMETERS = wa_ctrl_param
LS_VBAK = wa_vbak
TABLES
lt_vbap = t_vbap.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Document header data' type 'I'.
endif.
endif.
Converting smartform to PDF

select options and control break rep in smartforms


Example: Passing select-options as parameters to smart forms and implementing control
break events functionality in Smart Forms

Requirement:

Displaying sales documents item data based on the range of sales documents passed to
smartforms

1. Create dictionary structure

Create dictionary structure in SE11 :- zsalesdocselect

fields :

2. Create the smartform

Form interface :-

tables parameters :

t_sdoc like zsalesdocselect


Global definitions :-

types tab :

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

global data tab:

t_vbap type table of ty_vbap

wa_vbap type ty_vbap

initialization tab :-

input parameters output parameters

t_sdoc t_vbap

select vbeln posnr matnr netwr from vbap

into table t_vbap

where vbeln in t_sdoc.


Create loop object as part of main window

loop object -> specify internal table and work area

t_vbap wa_vbap

under loop object --> create text element and place the symbol fields from work area wa_vbap

---- end of scenario 1---

Example 2: For control break report functionality, observe the changes

Global data tab in Global definitions:


Initialization tab in Global definition:

Loop object:
Text object in Event on Sort Begin:

Code Object under Loop:


Text Object under loop to display other fields:
Text Object under event on sort end:

Code Object under event on sort end:


Text object after loop:

Driver program: To Pass select-options as parameters to smartforms

REPORT ZCALLSMFORM4.

data gv_vbeln type vbak-vbeln.


SELECT-OPTIONS so_vbeln FOR gv_vbeln DEFAULT '4980' to '4985'.

* get the smartform f.m name


data gv_fname type rs38l_fnam.
CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
EXPORTING
FORMNAME = 'ZSMFORM4'
IMPORTING
FM_NAME = gv_fname.

if gv_fname is not INITIAL.

* prepare control parameters to skip print dialog box


data wa_ctrl_param type SSFCTRLOP.
wa_ctrl_param-no_dialog = 'X'.
wa_ctrl_param-preview = 'X'.
* call the smartform F.M
call function gv_fname
EXPORTING
CONTROL_PARAMETERS = wa_ctrl_param
TABLES
T_SDOC = so_vbeln.

endif.

Example: Converting above Smart Form to PDF

REPORT ZCALLSMFORM4_PDF.

data gv_vbeln type vbak-vbeln.


SELECT-OPTIONS so_vbeln FOR gv_vbeln DEFAULT '4980' to '4985'.

* get the smartform f.m name


data gv_fname type rs38l_fnam.
CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
EXPORTING
FORMNAME = 'ZSMFORM4'
IMPORTING
FM_NAME = gv_fname.

if gv_fname is not INITIAL.

* prepare control parameters to skip print dialog box and preview


data wa_ctrl_param type SSFCTRLOP.
wa_ctrl_param-no_dialog = 'X'.
wa_ctrl_param-preview = ' '.
wa_ctrl_param-getotf = 'X'.

data wa_job_out_info type SSFCRESCL.


data t_otf type table of ITCOO.

* call the smartform F.M


call function gv_fname
EXPORTING
CONTROL_PARAMETERS = wa_ctrl_param
IMPORTING
JOB_OUTPUT_INFO = wa_job_out_info
TABLES
T_SDOC = so_vbeln.
* extract OTF content from the import parameter
t_otf[] = wa_job_out_info-OTFDATA[].

* Convert the OTF Format to Target Format


data t_lines type table of TLINE.
data gv_fsize type i.
CALL FUNCTION 'CONVERT_OTF'
EXPORTING
FORMAT = 'PDF'
IMPORTING
BIN_FILESIZE = gv_fsize
TABLES
OTF = t_otf
LINES = t_lines.

if t_lines is not INITIAL.


* download the target content to local file
CALL FUNCTION 'GUI_DOWNLOAD'
EXPORTING
BIN_FILESIZE = gv_fsize
FILENAME = 'd:\630sform2.pdf'
FILETYPE = 'BIN'
TABLES
DATA_TAB = t_lines.
endif.
endif.
command object

standard text inclusion


Example: Standard Text Creation and Including in Smart forms, Conditional Page break in
smart forms using ͚COMMAND͛ object

Standard Text Creation in ͚SO10͛:


Including Standard Text in Smart Forms:

Command Object Usage to achieve Conditional Page break in Smart Forms:

Parameter to Smart form: (Customer no)

Types Declarations:
Global variable declarations:

Global Data:

Initialization Tab:
Input Parameters Output Parameters

I_KUNNR T_VBAK

GV_SNO GV_SNO

GV_TOTPAGES GV_TOTPAGES

GV_REM GV_REM

Select Query: (Also, logic for generating count of no. of pages dynamically)

select vbeln erdat erzet ernam


from vbak
into table t_vbak
where kunnr = i_kunnr.
if sy-subrc eq 0.
gv_sno = 0.
gv_totpages = sy-dbcnt / 10.
gv_rem = sy-dbcnt mod 10.
if gv_rem ne 0.
gv_totpages = gv_totpages + 1.
endif.
endif.

Table object in main window with line type 1 containing 5 cells (Table tab)

Table object ͚DATA͛ tab


Create table line for header referring to table line ͚line type 1͛  5 cells are created  create
individual text elements in each cell for displaying headings

Create table line for Main area referring to table line ͚line type 1͛  5 cells are created 
create individual text elements in each cell for displaying data from work area ͚wa_vbak͛
In main area cell1, create program line (code object) for calculating serial no and marking the
reach of 10th record in each page

Create page 2 (right click on page 1  create page)


Create command object in main area of table object (in page 1) and specify the condition in
conditions tab

General attributes tab of command object


Copy main window from page 1 and paste the same in page 2

Driver program: To Call above smartform


REPORT ZCALLSMFORM5.

PARAMETERS p_kunnr type kna1-kunnr.


* get the smartform F.M
data gv_fname type rs38l_fnam.
CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
EXPORTING
FORMNAME = 'ZSMFORM5'
IMPORTING
FM_NAME = gv_fname.

* prepare the control parameters to skip print dialog box


data wa_ctrl_param type SSFCTRLOP.
wa_ctrl_param-no_dialog = 'X'.
wa_ctrl_param-preview = 'X'.

* call the smartform F.M


call function gv_fname
EXPORTING
CONTROL_PARAMETERS = wa_ctrl_param
i_kunnr = p_kunnr.

Standard Text Creation Dynamically

Creating and Reading Standard Text Dynamically


Note: Whenever we write the content to a non-existing standard text using the function
module ͚SAVE_TEXT͛, SAP creates the standard text and writes the content to it.

Note: Whenever we write the content to an existing standard text using the function module
͚SAVE_TEXT͛, SAP overwrites the standard text content with the new content.

Note: For Reading the standard text dynamically, we need to use the function module
͚READ_TEXT͛.

Note: For including the standard text in the smart form, we need to create a text object of type
͚Include Text͛ and provide the standard text information.

Transporting Standard Text

By Default, whenever we create Standard Text in ͚SO10͛, it is not captured as part of Change
Request as it will not prompt for any package at the time of creating it. So we need to assign
the standard text manually to a change request so that it can be transported. For this, we need
to run the standard program ͚RSTXTRAN͛, the pre-requisite for executing this standard report is
we need to create a task of type ͚CORRECTION͛ and provide the same at the time of executing
the standard report ͚RSTXTRAN͛. For this, first create a Workbench Request and a task in
Transport Organizer (SE09) and make the sure the task type is changed to
Development/Correction. For this, select the task, choose the menu ͚Request/Task͛ - change
type  Development/Correction.

Example: Creating Standard Text Dynamically

REPORT Z7AM_CREATE_STDTEXT.

PARAMETERS p_land1 type kna1-land1.

types : begin of ty_customer,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
end of ty_customer.

data : t_customer type table of ty_customer,


wa_customer type ty_customer.

select kunnr land1 name1


from kna1
into table t_customer
where land1 = p_land1.
if sy-subrc eq 0.
* Prepare Header text for standard text
data wa_header type thead.
wa_header-tdobject = 'TEXT'.
wa_header-tdname = 'Z7AMSTEXT_CUSTOMERS'.
wa_header-tdid = 'ST'.
wa_header-tdspras = sy-langu.

* prepare content for Standard Text


data : t_lines type table of tline,
wa_lines like line of t_lines.

loop at t_customer into wa_customer.


clear wa_lines.
wa_lines-tdformat = '*'.
CONCATENATE wa_customer-kunnr
wa_customer-land1
wa_customer-name1
into wa_lines-tdline
SEPARATED BY '@'.
append wa_lines to t_lines.
endloop.

if t_lines is not INITIAL.


* write the data to standard text
CALL FUNCTION 'SAVE_TEXT'
EXPORTING
CLIENT = SY-MANDT
HEADER = wa_header
TABLES
LINES = t_lines.
endif.
else.
message 'No customers' type 'I'.
endif.

Example: Reading and Appending data to Standard Text Dynamically

REPORT Z7AM_CREATE_APPEND_STDTEXT.

PARAMETERS p_land1 type kna1-land1.

types : begin of ty_customer,


kunnr type kna1-kunnr,
land1 type kna1-land1,
name1 type kna1-name1,
end of ty_customer.

data : t_customer type table of ty_customer,


wa_customer type ty_customer.

select kunnr land1 name1


from kna1
into table t_customer
where land1 = p_land1.
if sy-subrc eq 0.
* Read the data from standard text
data wa_header type thead.
data : t_lines type table of tline,
wa_lines like line of t_lines.
CALL FUNCTION 'READ_TEXT'
EXPORTING
CLIENT = SY-MANDT
ID = 'ST'
LANGUAGE = sy-langu
NAME = 'Z7AMSTEXT_CUSTOMERS'
OBJECT = 'TEXT'
IMPORTING
HEADER = wa_header
TABLES
LINES = t_lines.

if t_lines is not INITIAL.


* prepare new content for Standard Text

loop at t_customer into wa_customer.


clear wa_lines.
wa_lines-tdformat = '*'.
CONCATENATE wa_customer-kunnr
wa_customer-land1
wa_customer-name1
into wa_lines-tdline
SEPARATED BY '@'.
append wa_lines to t_lines.
endloop.
* append new data to standard text
CALL FUNCTION 'SAVE_TEXT'
EXPORTING
CLIENT = SY-MANDT
HEADER = wa_header
TABLES
LINES = t_lines.
else.
message 'Data not read from standard text' type 'I'.
endif.
else.
message 'No customers' type 'I'.
endif.

template in smartforms

Example: Alternative Object in Smart form

Alternative Object is used for condition check. We need to provide condition as part of
alternative object. Whenever an alternative object is created, SAP creates two sub nodes (true
and false). We can create relevant objects as part of true and false sub nodes. If the alternative
condition is satisfied, the objects associated with subnode ͚true͛ will be executed, otherwise the
objects associated with subnode ͚false͛ will be executed.
Initialization Tab:
Input Parameters:
I_kunnr wa_customer
Gv_cnt t_sales
Gv_cnt
Driver Program:

REPORT ZCALLSMFORM6.

SELECTION-SCREEN begin of block bk1 with FRAME title t1.

SELECTION-SCREEN begin of line.


SELECTION-SCREEN comment 6(18) lb1.
PARAMETERS p_kunnr type kna1-kunnr OBLIGATORY.
SELECTION-SCREEN end of line.

PARAMETERS : p_r1 RADIOBUTTON GROUP grp1 USER-COMMAND fc1,


p_r2 RADIOBUTTON GROUP grp1,
p_r3 RADIOBUTTON GROUP grp1 DEFAULT 'X'.
SELECTION-SCREEN end of block bk1.

data gv_fname type rs38l_fnam.


data wa_ctrl_param type SSFCTRLOP.
data gv_sel type c.

INITIALIZATION.
t1 = 'Select an Option'.
lb1 = 'Customer No'.
perform get_smartform_fm.
if gv_fname is not INITIAL.
* prepare control parameters
wa_ctrl_param-no_dialog = 'X'.
wa_ctrl_param-preview = 'X'.
endif.

at SELECTION-SCREEN on RADIOBUTTON GROUP grp1.


case sy-ucomm.
when 'FC1'.
if p_r1 = 'X'.
gv_sel = 'X'.
perform call_smartform.
elseif p_r2 = 'X'.
gv_sel = space.
perform call_smartform.
endif.
endcase.

FORM GET_SMARTFORM_FM .
CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
EXPORTING
FORMNAME = 'ZSMFORM6'
IMPORTING
FM_NAME = gv_fname.
ENDFORM. " GET_SMARTFORM_FM

FORM CALL_SMARTFORM .
call function gv_fname
EXPORTING
CONTROL_PARAMETERS = wa_ctrl_param
i_kunnr = p_kunnr
i_flag = gv_sel.
ENDFORM. " CALL_SMARTFORM
Scripts (SE71)

- It is a word processing tool used for designing the business documents.

- As part of every business there are different documents exchanged on a daily basis.

- Some of the business documents are enquiry, quotation, purchase order, sales order,
invoice, shipping, delivery etc..

- By using SAP Scripts we can design new documents and modify the documents provided
by SAP.

- Form Painter is Tool used for designing the templates.

- Once the template is designed we require a driver program or a print program to


invoke/call the SAP Script.

- This print program is usually an executable program, as part of this we use the following
function modules.

a. Open_form.

b. Write _form.

c. Close_from.

d. Start_form

e. End_form

Open_form:

Is used for opening the form, it contains the following parameters.

a. Form : it holds the name of the form.

b. Language: it holds the language key in which the form NEEDS to be opened.

Write_form:

It is used for passing the data and invoking the windows in the form .

a. Element: it holds the name of the element.


b. Window : it holds the window name.

Close_form:

It is used for closing the form.

Note: If the F.M close_form is not called, form will be displayed and closed automatically. i.e
no preview will be available

Sap script is language dependent and client dependent.

By default the text in the script windows will be displayed twice.

To eliminate this repetition we need to define text elements .

The number of calls to the function module ͞write_form͟ depends upon number of elements,
number of windows in the form.

Types of symbols in SAP Scripts

As part of repository objects we use system fields which represent some values.

As part of scripts we can use 4 types of symbols.

1. System symbols.

2. Standard symbols.

3. Program symbols.

4. Text symbols.

System symbols

These symbols and values exist in the table ͞TTXSY͟.

Standard symbols

These symbols and values exist in the table ͞TTDTG͟.

Note: System symbols, Standard symbols, Program symbols are enclosed between ͞&<symbol
name>&͟
Text symbols: These are the variables defined as part of layout and they are also represented
by control commands.
Program Symbols: are used for passing parameters to SAP scripts from driver program. The
program symbol names in the layout and in the driver program must be same.

To Display images in SAP Scripts, we need to first upload the .bmp images using ͚SE78͛ and then
in order to display the image in the layout we need to create either Graphic object on the
layout or use the ͚BITMAP͛ control command in the window to include the bitmap image (insert
menu  graphics)

Text elements:

To identify individual sections of the window and to avoid repetition of data.

Calling Multiple Forms from a Single Driver Program:

Driver program --> calling single form

open_form --> form name

write_form ---> element name, window name

write_form

close_form

Driver program --> calling multiple forms

open_form

start_form ---> form 1

write_form ---> element name, window name

write_form

end_form

-----

start_form ---> form n

write_form ---> element name, window name

write_form
end_form

close_form

Script Language Translation:

͚SE76͛ is the t-code used for translating scripts in to different languages. As part of this
translation, we can translate

a) Descriptions
b) Titles
c) Text in the windows

Note: Once the script is translated into different languages, as part of driver program, we
need to provide the system field ͚sy-langu͛ as part of language parameter in open_form
F.M..

Depending on the logon language, the appropriate language form is displayed. If the form
is not maintained in that language, then parent language form will be displayed.
Adobe Forms:

It is used for designing the template of Business Documents. Tool used is ͚Form Builder͛ (͚SFP͛ T-
code).

Software Requirements: (Apart from SAP Software)

1. ADOBE Life Cycle Designer


2. ADS (ADOBE Document Services)

Different Tools for designing business documents:

1. SAP Scripts --> Form Painter tool --> SE71 (supports only static forms, interaction is
not possible in runtime)

Procedure:

1. Layout design --> SE71

2. Driver/Print program --> executable program (SE38)

--> f.m's --> open_form, write_form, close_form

2. Smartforms --> smartforms (supports only static forms, interaction is not possible in runtime)

Procedure:

1. Layout design --> smartforms --> activate --> generates f.m --->execute

2. Driver Program / Print Program  Executable program --> call smartform f.m which
will act as driver for calling the smartform

3. Adobe forms --> (supports both static and interactive forms)

Procedure:

1. Create ADOBE Interface --> ͚SFP͛ T-code

a) Declare parameters

b) Declare global variables

c) Select statements for data retrieval

2. Create Adobe form (͚SFP͛ T-code) ---> Based on adobe interface


a) Map the parameters and variable Declarations, adobe system
fields from adobe interface context to adobe form context

b) Design the layout for the adobe form based on the adobe form
context

c) Activate --> generates f.m --> execute and test

3. Calling the adobe forms externally from driver program.

i) Executable program --> call Adobe Form F.M which will act as
driver for calling the adobe form

Procedure:

1. Start the job --> using the F.M ͚FP_JOB_OPEN͛

2. Get the adobe form f.m dynamically-->using the F.M ͚FP_FUNCTION_MODULE_NAME͛

3. Call the adobe form f.m

4. Close the job --> using the F.M ͚FP_JOB_CLOSE͛

ii) webdynpro application ---> integrate the adobe form as part of 'interactiveformuielement'
(property 'templatesource' --> name of adobe form)

Adobe interface ---> 3 types

a) abap dictionary based interface --> can refer to ddic objects


(structures /db tables/ data elements .....)

b) smartforms compatable interface --> used when smartform is migrated to


adobe form

c) xml schema based interface --> can be used for interactive adobe form

adobe forms ---> 2 types

a) offline --> static

b) online --> interactive


1st March Requirement

Requirement

Example 1: to Display static text in ADOBE Forms

1. Create ADOBE Interface (ZAINTF1) without any parameters and declarations


(SFP T-code)
Activate the adobe interface

2. Create ADOBE FORM (ZAFORM2) referring to ADOBE Interface(ZAINTF2) (SFP T-code)

Map the adobe system fields (data and time) from adobe interface context to adobe
form context
3. Design the layout for the adobe form in the layout tab

Drag and drop the system fields (date and time) from adobe form context to adobe
layout
Place the text field on the adobe form layout and provide static text (Palettes  Library
 Standard text control)

4. Activate the adobe form , generates F.M execute and test

Calling above ADOBE form from executable driver program:

REPORT ZCALLADOBEFORM1.

* prepare output parameters for bypassing the print dialog box


data ls_outparams type SFPOUTPUTPARAMS.
ls_outparams-nodialog = 'X'.
ls_outparams-preview = 'X'.
* open the job
CALL FUNCTION 'FP_JOB_OPEN'
CHANGING
IE_OUTPUTPARAMS = ls_outparams.
* get the ADOBE Form F.M
data lv_fname type FUNCNAME.
CALL FUNCTION 'FP_FUNCTION_MODULE_NAME'
EXPORTING
I_NAME = 'ZAFORM1'
IMPORTING
E_FUNCNAME = lv_fname.
* call the ADOBE Form F.M
call function lv_fname.
* close the job
CALL FUNCTION 'FP_JOB_CLOSE'.

Example 2: Passing parameters to ADOBE Forms

1. Create ADOBE Interface (ZAINTF2)

Import parameters:
Types declaration:

Global Data declaration:


Select Queries:

Activate the adobe interface

2. Create the ADOBE form (ZAFORM2)based on ADOBE interface (ZAINTF2)

Map the import parameters and Global declarations from adobe interface context to
adobe form context
3. Design the layout for adobe form

Drag and drop the parameters i_vbeln, gs_vbak , gt_vbap from adobe form context on
to the layout, also provide the static text through text control

4. Executable program for calling the above adobe form

REPORT ZCALLADOBEFORM2.

parameters p_vbeln type vbak-vbeln.

* prepare output parameters for bypassing the print dialog box


data ls_outparams type SFPOUTPUTPARAMS.
ls_outparams-nodialog = 'X'.
ls_outparams-preview = 'X'.

* open the job


CALL FUNCTION 'FP_JOB_OPEN'
CHANGING
IE_OUTPUTPARAMS = ls_outparams.

* get the ADOBE Form F.M


data lv_fname type FUNCNAME.
CALL FUNCTION 'FP_FUNCTION_MODULE_NAME'
EXPORTING
I_NAME = 'ZAFORM2'
IMPORTING
E_FUNCNAME = lv_fname.

* call the ADOBE Form F.M


*call function lv_fname. "runtime error as mandatory parameter i_vbeln is not passed

call function lv_fname


exporting
i_vbeln = p_vbeln.

* close the job


CALL FUNCTION 'FP_JOB_CLOSE'.
BDC (Batch Data communication): used for migrating data from legacy
system to SAP System. Legacy system can be a text/excel file. Legacy system file
can be on a local system (Presentation server) or can be on a server (Application
server).

BDC Techniques:

1. Direct Input method


2. Batch Input method

a) Call Transaction method b) Session method

Procedure for using BDC techniques


a) Identify the format (type) of the data

b) Identify the base table/s in SAP

c) Identify the no. of fields per record

d) Identify the sequence, delimiter and corresponding fields in SAP

e) Identify the BDC technique which needs to be used for data transfer

i) Direct input method

ii) Batch input method (Call transaction or Session method)

Working with Files on Presentation Server (Local System):


To Read (Upload) data from Local text file to internal table, we can use the
following F.M͛s

a) GUI_UPLOAD (Recommended)
b) WS_UPLOAD (Deprecated)
c) UPLOAD (Deprecated)

To Write (Download) data from internal table to Local text file, we can use the
following F.M͛s
a) GUI_DOWNLOAD (Recommended)
b) WS_DOWNLOAD (Deprecated)
c) DOWNLOAD (Deprecated)

To Read data from Local excel file to internal table, we can use the following F.M's

1. ALSM_EXCEL_TO_INTERNAL_TABLE (or)
2. TEXT_CONVERT_XLS_TO_SAP

Working with Files on Application server:


Syntax for opening Application Server File:

open dataset <path> for <file opening mode> in <text mode> / <binary mode>
encoding default [message <msg variable>].

Note: If the file is successfully opened, sy-subrc is set to 0 otherwise 4.

File opening modes:

1. input --> for reading

2. output --> for writing

3. appending --> for appending data to end of file

4. update --> for read / write

Note:

1. In 'text' mode, we can perform read/write line by line, In 'binary' mode, we


can perform read/write character by character (byte by byte).
2. If the file is not opened, the operating system message is captured in
message VARIABLE specified as part of Open dataset statement.
3. If an existing file is opened in Output mode, it deletes the previous contents
of the file and places the file pointer at the beginning of the file for writing
new content.
4. If a non-existing file is tried to open in Output mode, it creates the file and
places the file pointer at the beginning of the file for writing the content.
5. If an existing file is opened in Appending mode, it places the file pointer at
the end of the file for appending new content.
6. If a non-existing file is tried to open in Appending mode, it creates the file
and places the file pointer at the beginning of the file for writing new
content.

Syntax for Reading a line from Application Server File:

read dataset <path> into <target variable>.

Note: If the line is successfully read, sy-subrc is set to 0 otherwise 4.

Syntax for Writing a line to Application Server File:

Transfer <variable> to <path>.

Note: Transfer can transfer only string content.

Syntax for Closing a Application Server File:

Close dataset <path>.

Syntax for Deleting a Application Server File:

Delete dataset <path>.

Syntax to Get the position of the file pointer in Application Server File:

Get dataset <path> position <integer variable>.

Syntax to Set the file pointer at desired position in Application Server File:

Set dataset <path> position <integer variable>.


Data transfer using Call transaction method:
Syntax for call transaction:-

call transaction <transaction code>

[using <bdcdata internal table>]

[mode <processing mode>]

[update <update mode>]

[messages into <bdcmsgcoll internal table>].

BDCDATA Structure: It is a dictionary structure provided by SAP based on


which we need to create an internal table. As part of this ͚BDCDATA͛ internal
table, we need to map the internal table data which is read from legacy system
and also it holds the Module pool program information (Transaction information-
Module pool program name, Module pool Screen No, Screen Field names).

Processing Modes:

3 types of processing modes:

1. ͚A͛ (Display All)  Foreground (default)  All Records are displayed and
error records are validated after the user interaction on the screen.
2. ͚E͛ (Display Errors)  All Records are displayed and error records are
validated as when they are displayed on the screen (explicit user
interaction not required).
3. ͚N͛ (Background, No Display)

Update Modes:

3 types of update modes:

1. ͚A͛ (Asynchronous)  default  Doesn͛t wait for any updates


2. ͚S͛ (Synchronous)  waits for update and then processes next record
3. ͚L͛ (Local Update)  uses same process to update the data.

Note: Performance wise Asynchronous update mode is faster than


Synchronous update mode as Asynchronous update mode doesn͛t wait for
any updates.

BDCMSGCOLL Structure: It is a dictionary structure provided by SAP based


on which we need to create an internal table. As part of this ͚BDCMSGCOLL͛
internal table, SAP collects the messages that are populated during data
migration, based on this internal table we can generate the log related to data
migration using Call Transaction method.

Data transfer using Session method:


As part of this, we use 3 F.M͛s

1. BDC_OPEN_GROUP: To create and Open the session object. Important


parameters for this are

a) Client  client no where the session object needs to be created


b) Group  session object name
c) Holddate  holds the date till which the session object needs to be
locked
d) Keep  if set to ͚X͛, the session object will be retained after processing
for later analysis
e) Uname  holds the user name who is authorized to process the session
object

2. BDC_INSERT: To Map the BDCDATA internal table data to Session Object.


Important parameters for this are

a) Tcode  holds the t-code of the module pool transaction through which
the data is migrated
b) Dynprotab  holds the BDCDATA internal table

3. BDC_CLOSE_GROUP: To close the session Object.


Note: Once a session object is created, we can process the session object using
͚SM35͛. Once Session object is processed, a log will be generated automatically
which we can analyze.

Procedure for Recording the Transactions for Migrating data


from Legacy Systems to SAP:
1. Analyze the legacy system file for understanding type of data, no. of fields,
delimiter, and technical field names/table names in SAP.
2. By using ͚SHDB͛ T-code, Record the appropriate transaction by providing
the sample data for the fields available in the legacy system file.
3. Once the recording is completed, System displays the recorded details
mapped with ͚BDCDATA͛. In this screen, make a note of the field names for
which the sample data is provided. The purpose is we will get an idea
where we need to the changes in the recorded generated program.
4. In the recorded generated program, make the necessary changes to read
the data from our legacy system and replace the recorded field values with
the legacy system data.
5. After editing the program, execute the program and choose either session
technique or call transaction technique.
6. In case of session technique, provide the session name and select the check
box ͚keep session͛ so that we can analyze the processed session objects at
later point of time.
7. For processing session objects, go to t-code ͚SM35͛ and process it in
foreground / background. In both the cases, a log will be generated for
analyzing the processed session object.
8. In order to process the session objects without using ͚SM35͛ , collect the
QUEUE id of the session object from ͚SM35͛ and execute the standard
program ͚RSBDCBTC͛ which processes the session object in the background.
9. We can also use the standard program ͚RSBDCSUB͛ which takes a specific
session object as input / we can also provide the date range.

BDC using Table control:


In BDC using Table control, the field names of the table control depends on the
row id of the table control. i.e the field names are suffixed with the corresponding
row id. So, when we migrate the data to SAP Screen containing table control, the
field names of the table control should be dynamically generated based on the
row id of the table control.

Eg: - XK01 transaction (Vendor master data with bank details captured in table
control  Tables LFA1 and LFBK)

XD01 transaction (Customer master data with bank details captured in table
control  Tables KNA1 and KNBK)
Introduction:

Procedure oriented / structured programming / modular programming languages --->


C, PASCAL, COBOL

--> Importance is given to Functions

Object oriented --> ABAP, C++, JAVA, .Net

---> Importance is given to securing the data

Features of OOPS Oriented Programming Languages

1. Encapsulation --> binding data and member functions into single unit (class)

2. Data abstraction / Data hiding --> hiding the implementation details

3. Inheritance ---> reusability (inheriting the components of parent class into


child class)

4. Polymorphism--> many forms behavior

Procedure followed for Basic ABAP Report development:

1. Declare variables, work areas, internal tables...

2. Generate selection screen for reading user input (parameters/select-options)

3. Validate the user input

4. Execute select queries to read data from db into work area / internal table

5. Process the work area/ internal table to show the content (data) to the user

Types Declaration Vs class declaration

types : begin of <type name>, (ty_emp) similar to -------> class declaration

field 1, empno components

field 2, ename
----

end of <type name>. endclass.

ty_emp-empno = 1. (invalid)

data wa_emp1 type ty_emp. similar to --> object1 based on class

wa_emp1-empno = 1.

wa_emp1-ename = 'Raju'.

data wa_emp2 type ty_emp. --> object2 based on class

wa_emp2-empno = 4.

wa_emp2-ename = 'Ramesh'.

Class ---> user defined data type which is a collection of components

c++ class ---> data members + member functions

java class --> instance variables + methods

abap class ---> attributes + methods + events + interfaces + aliases + macros

ABAP ---> 2 types of classes

1. Local class--> local to an object (program) ---> ABAP editor (se38)

2. Global class --> global to all objects ----> class builder tool (se24)

---> stored inside class pool

Procedure for creating local class:

1. Definition of class

Syntax:

class <class name> definition [public] [protected] [private]


[deferred] [final] [load] [abstract].

declaration of components.

endclass.

Note: if class definition contains method declarations, then we need to implement the
class

2. Implementation of class

Syntax :

class <class name> implementation.

implementation of methods.

endclass.

Note: class definition and class implementation doesn't allocate any memory,
it only provides template of the class

Instantiate the class ---> creating the object for the class--> memory will be
allocated

Object creation --> 2 steps

1. Declare reference (alias) for the class

Syntax:

data <ref.name> type ref to <class name>.

Note: reference doesn't allocate any memory, it only provides alias.

2. Create object based on reference

Syntax:

create object <ref.name>. --> Memory will be allocated based on


components of class
Attribute: is like a variable which can be used to store the data.

Instance Attributes:

In local classes they are declared by using the keyword Data .

They are specific to object i.e. for every object, separate memory will be allocated for
each instance attribute.

They can be accessed only by using the Object.

Static Attributes:

In local classes they are declared by using the keyword class-data .

They are also called as Class Variables / Class attributes .

They are not specific to any object.

The memory for static attributes will be allocated whenever the class is loaded in to the
memory i.e. memory will be allocated only once which will be shared by all the objects
of the class.

They can be accessed either by using the object or by using the class name.

Constant Attributes:

In Local classes, they are declared by using the keyword constants . They must be
initialized at the time of declaration itself. The value of the constant attribute remains
same throughout the program.

They are not specific to any object.

The memory for them will be allocated whenever the class is loaded in to the memory
i.e. memory will be allocated only once which will be shared by all the objects of the
class.

They can be accessed either by using the object or by using the class name.

Note: We go for instance attributes whenever we need to maintain unique (different)


values for each object. We go for static attributes, whenever we need to maintain a
common (same) value for all the objects of the class. We go for constant attributes,
whenever we need to maintain a fixed value for all the objects of the class.

Types Attributes

In Local classes, they are declared by using the keyword Types . Types attribute
declaration only provides template, but doesn t allocated any memory. To make use of
Types attributes, we need to create references based on types attribute declaration.
These references can be either a normal data attribute / internal table / work area.

Methods:

- A method is a set of statements which is implemented only once and can be


called any no. of times.
- It is similar to subroutine / function module.
Subroutines: - 2 sections ---> definition ---> form...endform

Calling ---> perform <subroutine>.

Subroutine Parameters  keywords used  using, changing, tables

F.M's: 2 sections ---> definition --> function..endfunction (source code tab)

calling ---> call function <f.m>

Function Module Parameters  keywords used  importing, exporting, changing,


tables

Local class methods: 3 steps

Declaration (Method prototype declaration) --> Inside Class definition

Implementation --> Inside Class Implementation

Calling --> outside class / inside other method implementation

Method Parameters:

Types of parameters: importing, exporting, changing and returning.

By Default, Importing parameters are obligatory.


We can use the keyword optional as part of local class method parameters to
declare it as optional parameter and in case of global class methods, select the
checkbox optional

Exporting parameters are always optional.

Procedure for using Local class methods:

1. Declaration

syntax:

methods/class-methods <method name> [parameters list].

2. Implementation

syntax:

method <method name>.

statements.

endmethod.

3. Calling

syntax 1:

call method <method name> [parameters list]

syntax 2:

<method name>( [parameters list] ).

Method Returning Values:

- In case of ABAP a method can return any no. of values. The no. of return values
depends on no of Exporting/changing Parameters.
Returning Parameters:

- In general, a method can return any no. of parameters.


- To restrict a method to return exactly one value, we must use returning
parameter.
- If a method contains returning parameter it cannot contain exporting /changing
parameters at the same time or vice versa.
- A method can contain only one returning parameter
- Returning parameter is always passed by value.
- Returning parameters are always optional.
Instance methods:

In local classes they are declared by using the keyword Methods .

They can be accessed only by using the object.

They can access any kind of components of the class (instance / static / constant /
types).

Static methods:

In local classes they are declared by using the keyword class-Methods .

They can be accessed either by using the object or class name.

They can access only static components, constant attributes and types attributes.
i.e they cannot access instance components.

Note: In Local classes, the sequence of visibility sections (access specifiers) for the
class components should be in the order of public, protected, private sections.

Note: It is recommended to define and implement the local class at the beginning
of executable program and explicitly handle the event start-of-selection after
the class implementation to indicate the starting point of program execution.
Me keyword:

Me keyword refers to current object in execution i.e. as part of every instance


method execution (runtime), an implicitly created object (created by SAP) will be
available and it refers to the object which is currently executing the method.

Note: If a class contains both attributes and methods, it is recommended to


declare attributes under protected/private sections and methods under public
sections.

Since we cannot access protected/private components outside the class, we need


to access them through one of the public method and call the public method
outside the class.

Friend keyword:

In General outside the class, A Object can access only public components of the
class directly. i.e protected and private components of the class cannot be
accessed outside the class using an object of a class.

In order to enable the objects of the class to access all components of the class
outside the class irrespective of the visibility, then we can go for Friend classes.

In local classes Friend is a keyword used as part of class definition to consider


another class as friend.

Deferred Keyword:

As part of declaring local friend classes, we need to forward declare the friend
classes by using Deferred keyword. This deferred keyword indicates that the
class definition is provided somewhere else in the program and not at the
beginning of the program.

Note: In Global classes, we declare friend classes as part of FRIENDS tab.

Load keyword:

It is used to load the global classes explicitly in the executable program. This is
mandatory before the release 6.20 for accessing static components of the global
class before instantiating them.
From 6.20, it is not required, but in case, if we get any compilation error while
accessing the static components / any other components of global class, then we
can load the global class explicitly from the class library by using load keyword.

Constructor:

- It is special method used for initializing the attributes of the class i.e. whenever
an object is created, the attributes should be initialized with some initial values.
- It is special because it is executed/called automatically whenever an object is
created (instance const) or whenever a class is loaded in the memory (static
const).
- They are always declared in public section.
- They never return any value.
- There are two types of constructors
1. Instance constructor.
2. Static constructor.

Instance constructor

- They are declared by using the keyword Constructor .


- They can contain only importing parameters and exceptions.
- It is specific to object i.e. whenever a new object is created SAP executes
Instance constructor .

- Instance constructor is executed only once in the life time of every object.
Static constructor
- It is declared by using keyword class_constructor .
- It cannot contain any parameters or exceptions.
- It is not specific to any object.
- It is executed only once in the life time of every class. I.e. it is executed in either
of the following case.
- Case 1: When we access any static components of the class before creating any
objects for the class. (or)
- Case 2: when we create first object of the class before accessing any static
components of the class.
Note:

If a class contains static and instance Constructor and if we instantiate first object
before accessing any static components, than SAP first executes Static
Constructor and then the Instance Constructor will be executed on behalf of that
first object, from the second object onwards only instance constructor will be
executed.

If an instance constructor contains any mandatory importing parameters, we


must pass the values to those parameters while creating objects itself.

INHERITANCE

It is a process of using the properties (components) of one class inside other


class.

The main aim of Inheritance is Reusability of the components i.e. a component


declared in one class can be accessed by other class.

In Inheritance, two classes are involved (super class/base class and sub
class/derived class).

The class which gives properties is called as super class / base class.

The class which takes the properties is called as sub-class/derived class.

Only Public and Protected components can be inherited i.e. Private Components
cannot be inherited.

Types of inheritance:

1. SINGLE INHERITANCE: A Class acquiring properties from only one class.


2. MULTIPLE INHERITANCE: A class acquiring properties from more than one entity
(interface).
Note: In ABAP, Multiple inheritance can be implemented using the combination
of class and interfaces.
3. MULTILEVEL INHERITANCE: A class acquiring the properties from another sub-
class.
Inheriting from – is a keyword used as part of local class definition for inheriting
another class.

A class declared as Final cannot be inherited i.e. it cannot have subclass. In case
of local classes, we use the keyword final as part of class definition to declare a
final class.

Polymorphism

Poly -> many,

Morph-> forms,

Ism-> behaviour

It is a process of making an entity behaving in multiple forms.

In this case, the entity is a method

Example:

Method overloading, Method Overriding.

Method Overloading:

It is similar to function overloading in C++.

It is a process of overloading the same method by passing different Number and


different types of parameters.

Eg: methods m1.

Methods m1 importing x type i.

Methods m1 importing x type c.

Methods m1 importing x type I y type i.

ABAP does not support method overloading.


Method Overriding:

- If a subclass redefines a super class method it is called as Method Overriding.


- Whenever a local subclass wants to redefine the super class method, the sub
class as to re-declare super class method by using redefinition keyword.
- Whenever the super class method is redefined in subclasses, we cannot change
the visibility / category.
- Only public and protected instance methods can be redefined.
- Whenever a subclass redefines super class method, it is always recommended to
call the super class method implementation in the subclass and this is done by
using super keyword.
- Super keyword is always used in subclass method implementations (inside
redefined super class method) to refer to super class method implementation.
- A class declared as final cannot be inherited.
- Static methods cannot be redefined

- Instance public / Instance protected methods declared as final can be inherited


but cannot be redefined.

- A static public/static protected methods cannot be declared as final because by


default, static methods cannot be redefined.
Hierarchy of constructor execution-scenario 1

- If a super class contains static and instance constructor and subclass without any
constructors, and if we instantiate first object of super class/sub class before
accessing any static components of super/sub class ,then SAP first executes static
constructor of super class and then instance constructor of super class and from
second object of super class/sub class only instance constructor of super class will
be executed.

Hierarchy of constructor execution-scenario 2


- If a super class contains static and instance constructor and subclass only with
static constructor, and if we instantiate first object of sub class before accessing
any static components of super/sub class and also before creating any objects for
super class, then SAP first executes static constructors from super class to sub
class and then instance constructor of super class and from second object
onwards, only instance constructor of super class will be executed.
Hierarchy of constructor execution-scenario 3
- If a super class contains static and instance Constructor and subclass also with
static and instance constructor, then it is mandatory for sub class instance
constructor to call the super class instance constructor explicitly by using super
keyword.
- In this case, if we instantiate first object of sub class before accessing any static
components of super/sub class and before creating any objects for super class,
then SAP first executes static constructors from super class to sub class (top to
bottom) and then instance constructors from sub class to super class (bottom to
top) and from second object of sub class, only instance constructors will be
executed from sub class to super class.
Hierarchy of constructor execution-scenario 4
If a super class contains instance constructor with mandatory parameters and sub
class also contains instance constructor with mandatory parameters and
whenever we instantiate the sub class, make sure that you pass values for the
parameters of sub class instance constructors and from sub class instance
constructor implementation we need to call super class instance constructor by
passing values for parameters of super class instance constructor.

Hierarchy of constructor execution-scenario 5


If a super class contains instance constructor with mandatory parameters and sub
class without any instance constructor and whenever we instantiate the sub
class, make sure that you pass values for the parameters of super class instance
constructors and from sub class instance constructor implementation we need to
call super class instance constructor by passing same values for parameters of
super class instance constructor.
Visibility at Class Level - Public (default), protected, private and abstract
Public classes:
- The default visibility at class level is public.

- Public class can be instantiated anywhere (within same class/ inside subclasses
/outside classes).
- Public class can be inherited.
- The subclass inheriting the super public class is also created as public by default.
- The sub class inheriting the super public class can be created as explicit
protected/private.
Protected classes:
- Create protected is the keyword used as part of local class definition to create
the protected classes.
- Protected class can be inherited.
- Protected classes cannot be instantiated outside the classes but they can be
instantiated inside same classes as well as inside subclass methods.
- The subclass inheriting protecting class is also created as protected by default.
- The subclass inheriting protected class can be created as explicit public class (or)
private class.

- Private classes:
- Create private is keyword used for creating the private classes.

- Private class can be inherited.


- Private class cannot be instantiated outside the classes and inside subclasses, but
they can be instantiated within the same class. In order to instantiate private
classes inside subclasses or inside any other independent class, the private super
class should consider sub class / independent class as friend.

- The subclass inheriting the private class is also created as private by default.
- By default, the subclass inheriting the private class cannot be created as explicit
public class / explicit protected class. This can be made possible if the super
private class considers subclass as friend.
Friend keyword:

In local classes Friend is a keyword used as part of class definition to consider


another class as friend.
In this case friend class should be forward declared by using Deferred keyword.
This deferred keyword indicates that the class is defined somewhere else in the
program and not at the beginning of the program.
ABSTRACT CLASS:

Abstract is a class which contains one or more Abstract methods.

- An abstract method is a method which is just declared but not implemented.


- We declare a method as abstract when we are not sure about the
implementation.
- The implementation for the abstract methods can be provided as part of
subclasses.

- In local classes, abstract methods are declared by using a keyword abstract .


- If a class contains an abstract method, the class also should be declared as
abstract.
- Abstract methods are declared only in public and protected sections.

- Abstract methods are also called as non-concrete methods.


- Static methods cannot be declared as abstract as they cannot be redefined inside
subclasses
- Constructors cannot be declared as abstract as they cannot be redefined inside
subclasses
- The subclass whichever is inheriting the abstract class must implement all the
abstract methods of the abstract super class otherwise the subclass also should
be declared as abstract.
- We cannot create the objects for abstract classes because they are not
implemented completely. But once abstract methods are implemented inside
subclass, we can instantiate the subclass and assign subclass object to abstract
super class reference which is called as narrow casting.

- Whenever narrow casting is done, by using super class object we can access
methods of super class only, in order to access direct methods of subclass using
super class object, we need to call the subclass method using dynamic calling
approach.
INTERFACES

- An interface is a pure abstract class i.e. by default all the methods of interface are
abstract.
- Interface components doesn t contain any explicit visibility section, by default all
the components are public.
- Interfaces cannot contain method implementations, it contains only method
declarations.
- A local class whichever want to implement an interface(local/global) , the class
must declare the interface in the public section by using interfaces keyword and
the class must implement all the interface methods, Otherwise the class should
be declared as abstract and also the methods which are not implemented
should be flagged (declared) as abstract. In these cases, we must consider
another class inheriting the abstract class and provide the implementation for the
abstract methods.
- The class which ever implements the interface is called as implementation class.

- Interface is always implemented in public section of local class.


- By using interfaces we can implement the concept of multiple inheritances.
- I.e. a class can implement any number of interfaces.
- Whenever we refer to interface components outside the interface, the
component of the interface must be prefixed with the name of the interface.

- Interfaces cannot contain constructors


- If a class implements any interface and if that implemented interface contains
any included interfaces, then class must also implement all the methods of the
included interfaces.
- If a global class has to implement one or more global interfaces, then global class
must declare those interfaces in the interfaces tab.
Aliases

Aliases are the alternative names provided for interface components .i.e.
whenever we refer to the interface components outside the interface, it must be
prefixed with the name of the interface. This lengthy naming representation can
be avoided by declaring aliases for interface components.
- Aliases can be declared in any of the visibility sections inside implementation
class
- Aliases declared inside interfaces are always public
- Aliases can be declared either in interfaces / in the implementation class.
- If the aliases as to be declared in the interface it can be declared only for included
interfaces components and that alias will be created as component of interface.
Note: The included interfaces can be referred directly in the implementation
class .i.e. the interface which is included in other interface can be directly
referred in the implementation class.

Note: As Part of global classes, If a global class Includes any interface in the
interfaces tab and the checkbox final is selected, it indicates that these interface
methods cannot be further implemented (re-defined) in other classes.
class and object creation in different prog languages

oops syllabus
visibility sections of class components

Memory allocation for instance, static, and const attributes


difference between instance and static attributes

Example: Instance Vs Static Vs Constant Attributes

report z730oops1.

class lcl_abc definition.


public section.
data x type i. "instance attr
class-data y type i. "static attr
constants z type i value 10. "const attr
endclass.

*class lcl_abc IMPLEMENTATION. "not required as class doesn't have methods


*endclass.

*write :/ x,y,z. "syntax error

*write :/ lcl_abc->x. "syntax error


*write :/ lcl_abc->y. "syntax error
*write :/ lcl_abc->z. "syntax error
*write :/ lcl_abc=>x. "syntax error
write :/ 'Static and const attr.accessed using class name....'.
write :/ lcl_abc=>y.
write :/ lcl_abc=>z.

uline.
write :/ 'Static attr.accessed using class name....'.
lcl_abc=>y = 5.
write :/ lcl_abc=>y.
*lcl_abc=>z = 15. "syntax error

uline.
write :/ 'First object ob1....'.
data ob1 type ref to lcl_abc. "reference
*ob1->x = 45. "runtime error
create object ob1. "object
*write :/ ob1=>x. "syntax error
write :/ ob1->x,ob1->y,ob1->z.
ob1->x = 12.
ob1->y = 7.
*ob1->z = 15. "syntax error
write :/ ob1->x,ob1->y,ob1->z.
write :/ 'Static attr.accessed using class name....'.
write :/ lcl_abc=>y.

uline.
write :/ 'Second object ob2....'.
data ob2 type ref to lcl_abc.
create object ob2.
write :/ ob2->x,ob2->y,ob2->z.
ob2->x = 22.
write :/ ob2->x,ob2->y,ob2->z.
Memory allocation for objects ob1 and ob2

Example: Local class with instance attributes and instance methods, ME Keyword

REPORT Z730OOPS2.

*class lcl_emp DEFINITION.


* data : empno type i,
* ename(20) type c.
* methods : set,
* display.
*endclass. "syntax error

*class lcl_emp DEFINITION.


* PROTECTED SECTION.
* data : empno type i,
* ename(20) type c.
* PUBLIC SECTION.
* methods : set,
* display.
*endclass. "syntax error

class lcl_emp DEFINITION.


PUBLIC SECTION.
methods : set,
display.
PROTECTED SECTION.
data : empno type i,
ename(20) type c.
endclass.

class lcl_emp IMPLEMENTATION.


method display.
write :/ empno,ename. "(or)
* write :/ me->empno,me->ename.
endmethod.

method set.
empno = 5. "(or)
* me->empno = 5.
ename = 'Ravi'. "(or)
* me->ename = 'Ravi'.
endmethod.
endclass.

START-OF-SELECTION.

*call method display. "syntax error


*call method lcl_emp=>display. "syntax error

write :/ 'First object ob1....'.


data ob1 type ref to lcl_emp.
create object ob1.

*write :/ ob1->empno,ob1->ename. "syntax error

call method ob1->display.


call method ob1->set.
call method ob1->display.

write :/ 'Second object ob2....'.


data ob2 type ref to lcl_emp.
create object ob2.
call method ob2->display.
memory allocation for objects

Example: Local class methods with importing parameters

report z730oops3.

class lcl_emp definition.


public section.
methods set importing i_empno type i
i_ename type c optional.
protected section.
methods display.
data : empno type i,
ename(20) type c.
endclass.

class lcl_emp implementation.


method set.
empno = i_empno. "(or)
* me->empno = i_empno.
ename = i_ename. "(or)
* me->ename = i_ename.
call method display. "(or)
* call method me->display.
endmethod.
method display.
write :/ empno,ename. "(or)
* write :/ me->empno,me->ename.
endmethod.
endclass.

start-of-selection.
write :/ 'First Object ob1....'.
data ob1 type ref to lcl_emp.
create object ob1.

*call method ob->set. "syntax error

parameters : p_empno type i,


p_ename(20) type c.

call method ob1->set


exporting
i_empno = p_empno.

*call method ob1->display. "syntax error

uline.
write :/ 'Second Object ob2....'.
data ob2 type ref to lcl_emp.
create object ob2.
call method ob2->set
exporting
i_empno = p_empno
i_ename = p_ename.

call method ob2->set


exporting
i_empno = 100
i_ename = 'Ramu'.

ob2->set( i_empno = 200 i_ename = 'Rakesh' ).

ob2->set( exporting i_empno = 300 i_ename = 'Rajesh' ).


Example: Local class methods with importing and exporting parameters, types
attributes

report z730oops4.

class lcl_sales definition.


public section.
types : begin of ty_vbak,
vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_vbak.

methods getsalesdata importing i_vbeln type vbak-vbeln


exporting e_vbak type ty_vbak.

endclass.

class lcl_sales implementation.


method getsalesdata.
select single vbeln erdat erzet ernam
from vbak
into e_vbak
where vbeln = i_vbeln.
endmethod.
endclass.

start-of-selection.
data ob1 type ref to lcl_sales.
create object ob1.
format color 1.
write :/ 'First Object ob1....'.
parameters p_vbeln type vbak-vbeln.

call method ob1->getsalesdata


exporting
i_vbeln = p_vbeln.

uline.
data ob2 type ref to lcl_sales.
create object ob2.
format color 3.
write :/ 'Second Object ob2....'.
*data wa_vbak type ty_vbak. "syntax error
data wa_vbak type lcl_sales=>ty_vbak.

call method ob2->getsalesdata


exporting
i_vbeln = p_vbeln
importing
e_vbak = wa_vbak.
write :/ 'Sales Document Header data....'.
write :/ 'Sales Document no :',wa_vbak-vbeln,
/ 'Creation Date :',wa_vbak-erdat,
/ 'Creation Time :',wa_vbak-erzet,
/ 'Created by :',wa_vbak-ernam.
uline.
format color 7.
data ob3 type ref to lcl_sales.
create object ob3.
write :/ 'Third Object ob3....'.
clear wa_vbak.
ob3->getsalesdata( exporting i_vbeln = '0000004985' importing e_vbak = wa_vbak ).
write :/ 'Sales Document Header data....'.
write :/ 'Sales Document no :',wa_vbak-vbeln,
/ 'Creation Date :',wa_vbak-erdat,
/ 'Creation Time :',wa_vbak-erzet,
/ 'Created by :',wa_vbak-ernam.
diff between instance and static methods

Example: Method returning multiple values (Multiple exporting parameters)

report z730oops5.

class lcl_sales definition.


public section.
types : begin of ty_vbak,
vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_vbak.

types : begin of ty_vbap,


vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
end of ty_vbap.

types gt_vbap type table of ty_vbap.

methods getsalesdata importing i_vbeln type vbak-vbeln


exporting e_vbak type ty_vbak
e_vbap type gt_vbap.

endclass.
class lcl_sales implementation.
method getsalesdata.
select single vbeln erdat erzet ernam
from vbak
into e_vbak
where vbeln = i_vbeln.
if sy-subrc eq 0.
select vbeln posnr matnr
from vbap
into table e_vbap
where vbeln = i_vbeln.
endif.
endmethod.
endclass.

start-of-selection.
data ob1 type ref to lcl_sales.
create object ob1.
format color 1.
write :/ 'First Object ob1....'.
parameters p_vbeln type vbak-vbeln.

call method ob1->getsalesdata


exporting
i_vbeln = p_vbeln.

uline.
data ob2 type ref to lcl_sales.
create object ob2.
format color 3.
write :/ 'Second Object ob2....'.
*data wa_vbak type ty_vbak. "syntax error
data wa_vbak type lcl_sales=>ty_vbak.

call method ob2->getsalesdata


exporting
i_vbeln = p_vbeln
importing
e_vbak = wa_vbak.
write :/ 'Sales Document Header data....'.
write :/ 'Sales Document no :',wa_vbak-vbeln,
/ 'Creation Date :',wa_vbak-erdat,
/ 'Creation Time :',wa_vbak-erzet,
/ 'Created by :',wa_vbak-ernam.

uline.
format color 7.
data ob3 type ref to lcl_sales.
create object ob3.

write :/ 'Third Object ob3....'.


clear wa_vbak.
data : t_vbap type lcl_sales=>gt_vbap,
wa_vbap type lcl_sales=>ty_vbap.

ob3->getsalesdata( exporting i_vbeln = '0000004985' importing e_vbak = wa_vbak


e_vbap = t_vbap ).

write :/ 'Sales Document Header data....'.


write :/ 'Sales Document no :',wa_vbak-vbeln,
/ 'Creation Date :',wa_vbak-erdat,
/ 'Creation Time :',wa_vbak-erzet,
/ 'Created by :',wa_vbak-ernam.
uline.
write :/ 'Sales Document Item data...'.
loop at t_vbap into wa_vbap.
write :/ wa_vbap-vbeln,
wa_vbap-posnr,
wa_vbap-matnr.
endloop.

Example: Method with returning parameter

report z730oops6.

class lcl_customer definition.


public section.
methods getcustomer importing i_kunnr type kna1-kunnr
returning value(r_name2) type kna1-name2.
endclass.
class lcl_customer implementation.
method getcustomer.
select single name2
from kna1
into r_name2
where kunnr = i_kunnr.
endmethod.
endclass.
start-of-selection.
data ob type ref to lcl_customer.
create object ob.
parameters p_kunnr type kna1-kunnr.
data gv_name2 type kna1-name2.
call method ob->getcustomer
exporting
i_kunnr = p_kunnr
receiving
r_name2 = gv_name2.
write :/ 'Customer Second Name :',gv_name2.

Example: Global class (Global Types and Global methods)


Types editor: (In the Types tab, click on -- button )

types:
begin of ty_vbap,
vbeln type vbap-vbeln,
posnr type vbap-posnr,
matnr type vbap-matnr,
end of ty_vbap .
types:
gt_vbap type table of ty_vbap .
types:
begin of ty_vbak,
vbeln type vbak-vbeln,
erdat type vbak-erdat,
erzet type vbak-erzet,
ernam type vbak-ernam,
end of ty_vbak .
Method Implementation:

method getsalesdata.
select single vbeln erdat erzet ernam
from vbak
into e_vbak
where vbeln = i_vbeln.
if sy-subrc eq 0.
select vbeln posnr matnr
from vbap
into table e_vbap
where vbeln = i_vbeln.
endif.
endmethod.

Executable program:

report z730oops7.

*START-OF-SELECTION. "optional
data ob type ref to z730class1.
create object ob.

parameters p_vbeln type vbak-vbeln.

data : wa_vbak type z730class1=>ty_vbak,


t_vbap type z730class1=>gt_vbap,
wa_vbap type z730class1=>ty_vbap.

call method ob->getsalesdata


exporting
i_vbeln = p_vbeln
importing
e_vbak = wa_vbak
e_vbap = t_vbap.

write :/ 'Sales Document Header data....'.


write :/ 'Sales Document no :',wa_vbak-vbeln,
/ 'Creation Date :',wa_vbak-erdat,
/ 'Creation Time :',wa_vbak-erzet,
/ 'Created by :',wa_vbak-ernam.

write :/ 'Sales Document Item data...'.


loop at t_vbap into wa_vbap.
write :/ wa_vbap-vbeln,
wa_vbap-posnr,
wa_vbap-matnr.
endloop.

Example: Instance Vs static methods

report z730oops8.

class lcl_abc definition.


public section.
methods m1.
class-methods m2.
protected section.
data x type i value 30.
class-data y type i value 10.
constants z type i value 5.
types ty_m type i.
endclass.

class lcl_abc implementation.


method m1.
data m type ty_m value 12.
write :/ 'inside instance method m1..'.
write :/ y.
write :/ z.
write :/ m.
write :/ x.
endmethod.

method m2.
data m type ty_m value 18.
write :/ 'inside static method m2..'.
write :/ y.
write :/ z.
write :/ m.
* write :/ x. "syntax error
endmethod.
endclass.

start-of-selection.
write :/ 'Accessing methods using class name....'.
* call method lcl_abc=>m1. "syntax error
call method lcl_abc=>m2.

uline.
write :/ 'Accessing methods using object name....'.
data ob type ref to lcl_abc.
create object ob.

call method ob->m1.


call method ob->m2.
Example: Local Friend classes (Friend and Deferred keyword)

report z730oops9.

*class lcl_xyz DEFINITION.


* PUBLIC SECTION.
* methods m5.
*endclass. "not recommended

class lcl_xyz definition deferred. "Forward declaration of class


*class lcl_pqr DEFINITION deferred. "Forward declaration of class

*class lcl_abc DEFINITION FRIENDS lcl_xyz lcl_pqr.


class lcl_abc definition friends lcl_xyz.
public section.
methods m1.
protected section.
methods m2.
private section.
methods m3.
endclass.

class lcl_abc implementation.


method m1.
write :/ 'Inside public method m1 of abc...'.
endmethod.

method m2.
write :/ 'Inside protected method m2 of abc...'.
endmethod.

method m3.
write :/ 'Inside private method m3 of abc...'.
endmethod.
endclass.

class lcl_pqr definition.


public section.
methods m4.
endclass.
class lcl_pqr implementation.
method m4.
write :/ 'inside public method m4 of pqr ....'.
* call method m1."syntax error
data k type ref to lcl_abc.
create object k.
call method k->m1.
* call method k->m2. "syntax error
* call method k->m3. "syntax error
endmethod.
endclass.

class lcl_xyz definition.


public section.
methods m5.
endclass.

class lcl_xyz implementation.


method m5.
write :/ 'inside public method m5 of xyz ....'.
data k type ref to lcl_abc.
create object k.
call method k->m1.
call method k->m2.
call method k->m3.
endmethod.
endclass.

start-of-selection.
write :/ 'using object of pqr class...'.
data ob type ref to lcl_pqr.
create object ob.
call method ob->m4.

uline.
write :/ 'using object of xyz class...'.
data m type ref to lcl_xyz.
create object m.

call method m->m5.


Example: Global Friend classes

Global class 1: z730abc

Implementation for methods:

method m1.
write :/ 'Inside public method m1 of abc...'.
endmethod.

method m2.
write :/ 'Inside protected method m2 of abc...'.
endmethod.

method m3.
write :/ 'Inside private method m3 of abc...'.
endmethod.

Global class 2: z730pqr


Global class 1 (z730abc) considering Global class 2 (z730pqr) as friend:
Implementation for method M4 of z730abc class:

method m4.
write :/ 'inside public method m4 of pqr class...'.
data k type ref to z730abc.
create object k.
call method k->m1.
call method k->m2.
call method k->m3.
endmethod.

Executable program:

report z730oops10.

data ob type ref to z730pqr.


create object ob.

call method ob->m4.

Example: LOAD Keyword

Global class: z730class2


Implementations for methods:

method m1.
write :/ 'inside instance method m1..'.
endmethod.

method m2.
write :/ 'inside static method m2..'.
endmethod.

Executable program:

report z730oops11.

*class z730class2 DEFINITION load. "absolete

z730class2=>x = 10.
call method z730class2=>m2.
initializing constructors

constructor purpose

Example: Instance Constructor initializing attributes

report z730oops12.

class lcl_emp definition.


public section.
methods : constructor,
display.
protected section.
* methods : constructor. "syntax error
data : empno type i,
ename(20) type c.
endclass.

class lcl_emp implementation.


method constructor.
empno = 4.
ename = 'Raju'.
endmethod.

method display.
write :/ empno,ename.
endmethod.
endclass.

start-of-selection.
write :/ 'First object ob1....'.
data ob1 type ref to lcl_emp.
create object ob1.

* call method ob1->constructor. "syntax error

call method ob1->display.

Example: Parameters to Instance Constructor

report z730oops13.

class lcl_emp definition.


public section.
methods : constructor importing i_empno type i
i_ename type c optional,
display.
protected section.
data : empno type i,
ename(20) type c.
endclass.

class lcl_emp implementation.


method constructor.
empno = i_empno.
ename = i_ename.
endmethod.

method display.
write :/ empno,ename.
endmethod.
endclass.

start-of-selection.
parameters : p_empno type i,
p_ename(20) type c.

write :/ 'First object ob1....'.


data ob1 type ref to lcl_emp.
* create object ob1. "syntax error
create object ob1
exporting
i_empno = p_empno
i_ename = p_ename.

call method ob1->display.

uline.
write :/ 'Second object ob2....'.
data ob2 type ref to lcl_emp.
create object ob2
exporting
i_empno = p_empno.

call method ob2->display.

Example: Instance Vs Static Constructor

report z730oops14.

class lcl_abc definition.


public section.
* methods constructor importing i_x type i exporting e_z type i. "syntax error
methods constructor.
* class-methods class_constructor importing i_x type i. "syntax error
class-methods class_constructor.
class-data x type i.
endclass.

class lcl_abc implementation.


method constructor.
write :/ 'inside instance const..'.
endmethod.

method class_constructor.
write :/ 'inside static const..'.
endmethod.
endclass.

start-of-selection.
* lcl_abc=>x = 10. "also check by uncommenting

write :/ 'First object ob1....'.


data ob1 type ref to lcl_abc.
create object ob1.

uline.
write :/ 'Second object ob2....'.
data ob2 type ref to lcl_abc.
create object ob2.

uline.
write :/ 'Third object ob3....'.
data ob3 type ref to lcl_abc.
create object ob3.
Inheritance

Inheritance example
diff between public,protected,private at component level

Example: Inheritance – Local Classes

report z730oops15.

*class lcl_vehicle DEFINITION final. "cannot be inherited


class lcl_vehicle definition.
public section.
methods display.
protected section.
data : wheels type i,
brakes type i.
endclass.

class lcl_vehicle implementation.


method display.
write :/ wheels,brakes.
endmethod.
endclass.

class lcl_cycle definition inheriting from lcl_vehicle.


public section.
methods setcycle.
protected section.
data color(20) type c.
endclass.

class lcl_cycle implementation.


method setcycle.
wheels = 2.
brakes = 2.
color = 'Green'.
write :/ 'Color of Cycle is ',color.
endmethod.
endclass.

class lcl_bike definition inheriting from lcl_cycle.


public section.
methods setbike.
protected section.
data gears type i.
endclass.

class lcl_bike implementation.


method setbike.
wheels = 2.
brakes = 1.
color = 'Red'.
gears = 5.
write :/ 'Color of bike :',color.
write :/ 'No of gears of bike :',gears.
endmethod.
endclass.

start-of-selection.
write :/ 'Object of cycle class ...'.
data ob1 type ref to lcl_cycle.
create object ob1.

call method : ob1->setcycle,


ob1->display.

uline.
write :/ 'Object of bike class ...'.
data ob2 type ref to lcl_bike.
create object ob2.

call method : ob2->setbike,


ob2->display.

Example: Inheritance – Global Classes

Global class: ZCL_VEHICLE


method display.
write :/ wheels,brakes.
endmethod.

Class: ZCL_CYCLE inheriting from ZCL_VEHICLE


method setcycle.
wheels = 2.
brakes = 2.
color = 'Green'.
write :/ 'Color of Cycle is ',color.

endmethod.

Class: ZCL_BIKE inheriting from ZCL_CYCLE


method setbike.
wheels = 2.
brakes = 1.
color = 'Red'.
gears = 5.
write :/ 'Color of bike :',color.
write :/ 'No of gears of bike :',gears.
endmethod.

Executable Program: To Access global Inherited classes

report z730oops16.

write :/ 'Object of cycle class ...'.


data ob1 type ref to zcl_cycle.
create object ob1.

call method : ob1->setcycle,


ob1->display.

uline.
write :/ 'Object of bike class ...'.
data ob2 type ref to zcl_bike.
create object ob2.

call method : ob2->setbike,


ob2->display.
Method overriding

Example: Method Overloading (Not Supported in ABAP)

report z730oops17.

class lcl_abc definition.


public section.
methods m1.
methods m1 importing x type i.
methods m1 importing x type c.
methods m1 importing x type i y type i.
endclass.

Example: Method Overriding (Local classes)

report z730oops18.

class lcl_vehicle definition.


public section.
methods display.
methods m1 final.
class-methods m2.
* class-methods m3 final. "syntax error
protected section.
data : wheels type i,
brakes type i.
endclass.

class lcl_vehicle implementation.

method m1.
write :/ 'inside instance method m1 of vehicle class...'.
endmethod.

method m2.
write :/ 'inside static method m2 of vehicle class...'.
endmethod.

method display.
write :/ wheels,brakes.
endmethod.
endclass.

class lcl_cycle definition inheriting from lcl_vehicle.


public section.
methods setcycle.
methods display redefinition.
* methods m1 REDEFINITION. "syntax error
* class-methods m2 redefinition. "syntax error
protected section.
data color(20) type c.
endclass.

class lcl_cycle implementation.


method setcycle.
wheels = 2.
brakes = 2.
color = 'Green'.
endmethod.

method display.
* call method super->display. "(or)
super->display( ).
write :/ color.
endmethod.
endclass.

class lcl_bike definition inheriting from lcl_cycle.


public section.
methods setbike.
methods display redefinition.
protected section.
data gears type i.
endclass.

class lcl_bike implementation.


method setbike.
wheels = 2.
brakes = 1.
color = 'Red'.
gears = 5.
endmethod.

method display.
super->display( ).
write :/ gears.
endmethod.
endclass.
start-of-selection.
write :/ 'Object of cycle class ...'.
data ob1 type ref to lcl_cycle.
create object ob1.

call method : ob1->setcycle,


ob1->display.
uline.
write :/ 'Object of bike class ...'.
data ob2 type ref to lcl_bike.
create object ob2.

call method : ob2->setbike,


ob2->display.
Example: Method Overriding (Global classes)

Global class 1: YCL_SUPER

Instance Method M2 declared as Final (Detailed View button)


Implementations:

method m1.
write :/ 'inside public instance method m1 of super class'.
endmethod.

method m2.
write :/ 'inside public instance final method m2 of super class'.
endmethod.

method m3.
write :/ 'inside public static method m3 of super class'.
endmethod.

Class: YCL_SUB Inheriting YCL_SUPER

Inherited Method M1 redefined: (Click on Redefine button  right hand corner)

Redefined Method M1 Implementation:

method m1.
call method super->m1.
write :/ 'inside public redefined instance method m1 of super class'.
endmethod.
Executable Program: For calling Redefined Global method

report z730oops19.

data ob type ref to ycl_sub.


create object ob.

call method ob->m1.

Example: Hierarchy of constructor execution – Scenario 1

report z730oops20.

class lcl_super definition.


public section.
methods constructor.
class-methods class_constructor.
class-data x type i.
endclass.

class lcl_super implementation.


method constructor.
write :/ 'inside super class instance constructor...'.
endmethod.

method class_constructor.
write :/ 'inside super class static constructor...'.
endmethod.
endclass.

class lcl_sub definition inheriting from lcl_super.


endclass.

start-of-selection.
*lcl_super=>x = 10.
*lcl_sub=>x = 12.

* write :/ 'First object of super class...'.


* data ob type ref to lcl_super.
* create object ob.
uline.
write :/ 'First object of sub class...'.
data ob1 type ref to lcl_sub.
create object ob1.

uline.
write :/ 'Second object of sub class...'.
data ob2 type ref to lcl_sub.
create object ob2.

uline.
write :/ 'Third object of sub class...'.
data ob3 type ref to lcl_sub.
create object ob3.

Example: Hierarchy of Constructor Execution – Scenario 2

report z730oops21.

class lcl_super definition.


public section.
methods constructor.
class-methods class_constructor.
class-data x type i.
endclass.

class lcl_super implementation.


method constructor.
write :/ 'inside super class instance constructor...'.
endmethod.

method class_constructor.
write :/ 'inside super class static constructor...'.
endmethod.
endclass.

class lcl_sub definition inheriting from lcl_super.


public section.
class-methods class_constructor.
class-data y type i.
endclass.
class lcl_sub implementation.
method class_constructor.
write :/ 'inside sub class static constructor...'.
endmethod.
endclass.

start-of-selection.
*lcl_super=>x = 10.
*lcl_sub=>x = 10.
*lcl_super=>y = 10. "syntax error
*lcl_sub=>y = 10.

* write :/ 'First object of super class...'.


* data ob type ref to lcl_super.
* create object ob.

uline.
write :/ 'First object of sub class...'.
data ob1 type ref to lcl_sub.
create object ob1.

uline.
write :/ 'Second object of sub class...'.
data ob2 type ref to lcl_sub.
create object ob2.

uline.
write :/ 'Third object of sub class...'.
data ob3 type ref to lcl_sub.
create object ob3.

Example: Hierarchy of Constructor Execution – Scenario 3

report z730oops22.

class lcl_super definition.


public section.
methods constructor.
class-methods class_constructor.
class-data x type i.
endclass.

class lcl_super implementation.


method constructor.
write :/ 'inside super class instance constructor...'.
endmethod.

method class_constructor.
write :/ 'inside super class static constructor...'.
endmethod.
endclass.

class lcl_sub definition inheriting from lcl_super.


public section.
methods constructor.
class-methods class_constructor.
class-data y type i.
endclass.

class lcl_sub implementation.


method class_constructor.
write :/ 'inside sub class static constructor...'.
endmethod.

method constructor.
write :/ 'inside sub class instance constructor...'.
call method super->constructor.
endmethod.
endclass.

start-of-selection.
*lcl_super=>x = 10.
*lcl_sub=>x = 10.
*lcl_super=>y = 10. "syntax error
*lcl_sub=>y = 10.

* write :/ 'First object of super class...'.


* data ob type ref to lcl_super.
* create object ob.
uline.
write :/ 'First object of sub class...'.
data ob1 type ref to lcl_sub.
create object ob1.

uline.
write :/ 'Second object of sub class...'.
data ob2 type ref to lcl_sub.
create object ob2.

uline.
write :/ 'Third object of sub class...'.
data ob3 type ref to lcl_sub.
create object ob3.

Example: Hierarchy of Constructor Execution – Scenario 4

report z730oops23.

class lcl_super definition.


public section.
methods constructor importing i_empno type i
i_ename type c.
protected section.
data : empno type i,
ename(20) type c.
endclass.

class lcl_super implementation.


method constructor.
empno = i_empno.
ename = i_ename.
endmethod.
endclass.

class lcl_sub definition inheriting from lcl_super.


public section.
methods display.
methods constructor importing i_empno type i
i_ename type c.
endclass.
class lcl_sub implementation.

method constructor.
call method super->constructor
exporting
i_empno = i_empno
i_ename = i_ename.
endmethod.

method display.
write :/ empno,ename.
endmethod.
endclass.

start-of-selection.
parameters : p_empno type i,
p_ename(20) type c.

data ob type ref to lcl_sub.


create object ob
exporting
i_empno = p_empno
i_ename = p_ename.

call method ob->display.

Example: Hierarchy of Constructor Execution – Scenario 5

report z730oops24.

class lcl_super definition.


public section.
methods constructor importing i_empno type i
i_ename type c.
protected section.
data : empno type i,
ename(20) type c.
endclass.

class lcl_super implementation.


method constructor.
empno = i_empno.
ename = i_ename.
endmethod.
endclass.

class lcl_sub definition inheriting from lcl_super.


public section.
methods display.
endclass.

class lcl_sub implementation.


method display.
write :/ empno,ename.
endmethod.
endclass.

start-of-selection.
parameters : p_empno type i,
p_ename(20) type c.

data ob type ref to lcl_sub.


create object ob
exporting
i_empno = p_empno
i_ename = p_ename.

call method ob->display.

Example: Public classes

report z730oops25.

*class lcl_abc DEFINITION. "(or)


class lcl_abc definition create public.
public section.
methods m1.
endclass.

class lcl_abc implementation.


method m1.
data k type ref to lcl_abc.
create object k.
endmethod.
endclass.

class lcl_xyz definition inheriting from lcl_abc.


public section.
methods m2.
endclass.

class lcl_xyz implementation.


method m2.
data r type ref to lcl_abc.
create object r.
endmethod.
endclass.

class lcl_pqr definition create protected inheriting from lcl_abc.


endclass.

class lcl_lmn definition create private inheriting from lcl_abc.


endclass.

start-of-selection.
data ob type ref to lcl_abc.
create object ob.

data m type ref to lcl_xyz.


create object m.

Example: Protected classes

report z730oops26.

class lcl_abc definition create protected.


public section.
methods m1.
endclass.

class lcl_abc implementation.


method m1.
data k type ref to lcl_abc.
create object k.
endmethod.
endclass.

class lcl_xyz definition inheriting from lcl_abc.


public section.
methods m2.
endclass.

class lcl_xyz implementation.


method m2.
data r type ref to lcl_abc.
create object r.
endmethod.
endclass.

class lcl_pqr definition create public inheriting from lcl_abc.


endclass.

class lcl_lmn definition create private inheriting from lcl_abc.


endclass.

start-of-selection.
data ob type ref to lcl_abc.
*create object ob. "syntax error
*
data m type ref to lcl_xyz.
*create object m. "syntax error

Example: Private classes and second usage of Friend class

report z730oops27.

class lcl_xyz1 definition deferred.


class lcl_pqr1 definition deferred.
class lcl_lmn1 definition deferred.

class lcl_abc definition create private friends lcl_xyz1 lcl_pqr1 lcl_lmn1.


public section.
methods m1.
endclass.

class lcl_abc implementation.


method m1.
data k type ref to lcl_abc.
create object k.
endmethod.
endclass.

class lcl_xyz definition inheriting from lcl_abc.


public section.
methods m2.
endclass.

class lcl_xyz implementation.


method m2.
data r type ref to lcl_abc.
* create object r. "syntax error
endmethod.
endclass.

class lcl_xyz1 definition inheriting from lcl_abc.


public section.
methods m2.
endclass.

class lcl_xyz1 implementation.


method m2.
data r type ref to lcl_abc.
create object r. "syntax error
endmethod.
endclass.

*class lcl_pqr DEFINITION create public INHERITING FROM lcl_abc. "syntax error
*endclass.

class lcl_pqr1 definition create public inheriting from lcl_abc.


endclass.
*class lcl_lmn DEFINITION create protected INHERITING FROM lcl_abc. "syntax erro
*endclass.

class lcl_lmn1 definition create protected inheriting from lcl_abc.


endclass.

*
*START-OF-SELECTION.
data ob type ref to lcl_abc.
*create object ob. "syntax error
**
*data m type ref to lcl_xyz.
**create object m. "syntax error

abstract class example

Example: Local Abstract classes

report z730oops28.

class lcl_restaurant definition abstract.


public section.
methods : store,
display,
payment abstract.
* CLASS-METHODS m1 ABSTRACT. "syntax error
protected section.
data : tableno type i,
steward(20) type c.
endclass.

class lcl_restaurant implementation.


method store.
tableno = 1.
steward = 'ABC'.
endmethod.

method display.
write :/ tableno,steward.
endmethod.
endclass.

class lcl_cheque definition inheriting from lcl_restaurant.


public section.
methods payment redefinition.
methods display redefinition.
protected section.
data : cqno type i,
cqdate type d,
cqamt type i.
endclass.

class lcl_cheque implementation.


method payment.
cqno = 123.
cqdate = sy-datum.
cqamt = 1200.
endmethod.

method display.
call method super->display.
write :/ cqno,cqdate,cqamt.
endmethod.
endclass.
class lcl_creditcard definition inheriting from lcl_restaurant.
public section.
methods payment redefinition.
methods display redefinition.
protected section.
data : ccno type i,
ccexpdate type d,
ccamt type i.
endclass.

class lcl_creditcard implementation.


method payment.
ccno = 543.
ccexpdate = sy-datum.
ccamt = 236.
endmethod.

method display.
call method super->display.
write :/ ccno,ccexpdate,ccamt.
endmethod.
endclass.

start-of-selection.
data r type ref to lcl_restaurant.
* create object r. "syntax error
format color 3.
write :/ 'Cheque class object....'.
data cq type ref to lcl_cheque.
create object cq.

call method : cq->store,


cq->payment,
cq->display.
format color off.
uline.

format color 7.
write :/ 'Credit card class object....'.
data cc type ref to lcl_creditcard.
create object cc.

call method : cc->store,


cc->payment,
cc->display.
format color off.

Inheriting Abstract class

Example: Global Abstract Classes

Class: ZCL_RESTAURANT (Abstract class)


Method Payment declared as abstract (details view button)

Implementations for other 2 methods:

method STORE.
tableno = 1.
steward = 'ABC'.

endmethod.

method DISPLAY.
write :/ tableno,steward.
endmethod
Class: ZCL_CHEQUE Inheriting ZCL_RESTAURANT
Method Payment Redefined:

method PAYMENT.
cqno = 123.
cqdate = sy-datum.
cqamt = 1200.

endmethod.

Method Display Redefined:

method DISPLAY.
CALL METHOD SUPER->DISPLAY.
write :/ cqno,cqdate,cqamt.
endmethod.

Class: ZCL_CREDITCARD Inheriting ZCL_RESTAURANT


Method Payment Redefined:

method PAYMENT.
ccno = 543.
ccexpdate = sy-datum.
ccamt = 236.

endmethod.

Method Display Redefined:

method DISPLAY.
CALL METHOD SUPER->DISPLAY.
write :/ ccno,ccexpdate,ccamt.

endmethod.

Executable Program:

REPORT Z730OOPS29.

data r type ref to zcl_restaurant.


*create object r. "syntax error

uline.
format color 3.
write :/ 'Cheque class object....'.
data cq type ref to zcl_cheque.
create object cq.

call method : cq->store,


cq->payment,
cq->display.
format color off.

uline.
format color 7.
write :/ 'Cheque class object ---> Restaurant....'.
r = cq. "narrow casting or up casting
call method : r->store,
r->payment,
r->display.

uline.
format color 1.
write :/ 'Credit card class object....'.
data cc type ref to zcl_creditcard.
create object cc.

call method : cc->store,


cc->payment,
cc->display.
format color off.

uline.
format color 6.
write :/ 'Credit card class object ---> Restaurant....'.
r = cc. "narrow casting or up casting
call method : r->store,

r->payment,
r->display.

diff between abstract classes and interfaces


Example: Local Interfaces (Multiple Inheritance Implementation)

REPORT Z730OOPS30.

interface rectangle.
data : length type i,
breadth type i.
methods : area,
perimeter.
endinterface.

interface square.
data side type i.
methods : area,
perimeter.
endinterface.

class pqr DEFINITION.


endclass.

class lcl_impl DEFINITION INHERITING FROM pqr. "implementation class


PUBLIC SECTION.
interfaces : rectangle,
square.
methods constructor IMPORTING i_len type i OPTIONAL
i_brd type i OPTIONAL
i_side type i OPTIONAL.
methods area.
PROTECTED SECTION.
data res type i.
endclass.

class lcl_impl IMPLEMENTATION.

method constructor.
call method super->constructor.
rectangle~length = i_len.
rectangle~breadth = i_brd.
square~side = i_side.
endmethod.
method rectangle~area.
res = rectangle~length * rectangle~breadth.
write :/ 'Area of Rectangle is ',res.
endmethod.

method rectangle~perimeter.
res = 2 * ( rectangle~length + rectangle~breadth ).
write :/ 'Perimeter of Rectangle is ',res.
endmethod.

method square~area.
res = square~side * square~side.
write :/ 'Area of square is ',res.
endmethod.

method square~perimeter.
res = 4 * square~side.
write :/ 'Perimeter of square is ',res.
endmethod.

method area.
write :/ 'inside direct method area of impl. class...'.
endmethod.
ENDCLASS.

START-OF-SELECTION.
PARAMETERS : p_length type i,
p_brdth type i,
p_side type i.

data ob type ref to lcl_impl.


create object ob
EXPORTING
i_len = p_length
i_brd = p_brdth
i_side = p_side.

call method : ob->rectangle~area,


ob->rectangle~perimeter,
ob->square~area,
ob->square~perimeter,
ob->area.

Example: Global Interfaces

Global Interface: ZRECTANGLE


Global Interface: ZSQUARE
Implementation class: ZCL_IMPL implementing above 2 global interfaces
Parameters for Constructor method:
Implementations for Methods:

method ZRECTANGLE~AREA.
res = zrectangle~length * zrectangle~breadth.
write :/ 'Area of Rectangle is ',res.

endmethod.

method ZRECTANGLE~PERIMETER.
res = 2 * ( zrectangle~length + zrectangle~breadth ).
write :/ 'Perimeter of Rectangle is ',res.

endmethod.

method ZSQUARE~AREA.
res = zsquare~side * zsquare~side.
write :/ 'Area of square is ',res.

endmethod.

method ZSQUARE~PERIMETER.
res = 4 * zsquare~side.
write :/ 'Perimeter of square is ',res.

endmethod.

method CONSTRUCTOR.

zrectangle~length = i_len.
zrectangle~breadth = i_brd.
zsquare~side = i_side.

endmethod.

method M1.
write :/ 'inside direct method m1 of impl.class....'.
endmethod.
Executable Program:

REPORT Z730OOPS31.

PARAMETERS : p_len type i,


p_brd type i,
p_side type i.

format color 3.
write :/ 'Implementation class object ob....'.
data ob type ref to zcl_impl.
create object ob
EXPORTING
i_len = p_len
i_brd = p_brd
i_side = p_side.

CALL METHOD OB->ZRECTANGLE~AREA


.
CALL METHOD OB->ZRECTANGLE~PERIMETER
.
CALL METHOD OB->ZSQUARE~AREA
.
CALL METHOD OB->ZSQUARE~PERIMETER
.
call method ob->m1.
uline.
format color 7.
write :/ 'Implementation class object ----> Rectangle Reference.'.
data r type ref to zrectangle.
*create object r. "syntax error
r = ob. "narrow casting
call method : r->area,
r->perimeter.
* r->m1. "syntax error
* r->('M1'). "dynamic calling-runtime error

uline.
format color 1.
write :/ 'Implementation class object ----> Square Reference.'.
data s type ref to zsquare.
*create object s. "syntax error
s = ob. "narrow casting
call method : s->area,
s->perimeter.

Example: Implementing Local Interfaces Partially

REPORT Z730OOPS32.

interface intf1.
methods : m1,
m2,
m3.
ENDINTERFACE.

class lcl_impl1 DEFINITION ABSTRACT.


PUBLIC SECTION.
interfaces intf1 ABSTRACT METHODS m2 m3.
endclass.

class lcl_impl1 IMPLEMENTATION.


method intf1~m1.
write :/ 'Inside method m1 of interface intf1 implemented in class lcl_impl1..'.
endmethod.
endclass.

class lcl_impl2 DEFINITION INHERITING FROM lcl_impl1.


PUBLIC SECTION.
methods : intf1~m2 REDEFINITION,
intf1~m3 REDEFINITION.
methods m4.
endclass.

class lcl_impl2 IMPLEMENTATION.


method intf1~m2.
write :/ 'Inside method m2 of interface intf1 implemented in class lcl_impl2..'.
endmethod.

method intf1~m3.
write :/ 'Inside method m3 of interface intf1 implemented in class lcl_impl3..'.
endmethod.

method m4.
write :/ 'Inside direct method m4 of class lcl_impl2....'.
endmethod.

endclass.

START-OF-SELECTION.
format color 3.
write :/ 'Object of class lcl_impl2....'.
data ob type ref to lcl_impl2.
create object ob.

call method : ob->intf1~m1,


ob->intf1~m2,
ob->intf1~m3,
ob->m4.

uline.
format color 7.
write :/ 'Object of class lcl_impl2 assigned to class lcl_impl1....'.
data k type ref to lcl_impl1.
* create object k. "syntax error

k = ob. "narrow casting


call method : k->intf1~m1,
k->intf1~m2,
k->intf1~m3,
* k->m4. "syntax error
k->('M4'). "dynamic call

Example: Including a Local Interface inside other Local Interface

REPORT Z730OOPS33.

interface intf1.
methods : m1,
m2.
ENDINTERFACE.
INTERFACE intf2.
methods m3.
interfaces intf1.
ENDINTERFACE.

class lcl_impl DEFINITION.


PUBLIC SECTION.
interfaces intf2.
endclass.

class lcl_impl IMPLEMENTATION.


method intf2~m3.
write :/ 'inside method m3 of interface intf2...'.
endmethod.

method intf1~m1.
write :/ 'inside method m1 of interface intf1...'.
endmethod.

method intf1~m2.
write :/ 'inside method m2 of interface intf1...'.
endmethod.
endclass.

START-OF-SELECTION.
data ob type ref to lcl_impl.
create object ob.

call method : ob->intf1~m1,


ob->intf1~m2,
ob->intf2~m3.

Example: Aliases for Local Interface Components

REPORT Z730OOPS34.

interface intf1.
* data : length type i value 10,
* breadth type i value 5. "syntax error
constants : length type i value 10,
breadth type i value 5.
methods : area,
perimeter.
endinterface.

class lcl_impl DEFINITION.


PUBLIC SECTION.
interfaces intf1.
aliases : a1 for intf1~length,
a2 for intf1~breadth,
a3 for intf1~area.
PROTECTED SECTION.
aliases a4 for intf1~perimeter.
data res type i.
endclass.

class lcl_impl IMPLEMENTATION.


* method intf1~area. "(or)
method a3.
* res = intf1~length * intf1~breadth. "(or)
res = a1 * a2.
write :/ 'Area of rectangle is ',res.
* call method a4.
endmethod.
* method intf1~perimeter. "(or)
method a4.
* res = 2 * ( intf1~length + intf1~breadth ). "(or)
res = 2 * ( a1 + a2 ).
write :/ 'Perimeter of rectangle is ',res.
endmethod.
endclass.

START-OF-SELECTION.
data ob type ref to lcl_impl.
create object ob.

*call method : ob->intf1~area,


* ob->intf1~perimeter.

call method : ob->a3.


* ob->a4. "syntaax error
Example: Including a Global Interface inside other Global Interface, Global Aliases for
Global Interface Components

Global Interface 1: ZINTF1

Global Interface 2: ZINTF2 including above Global Interface 1


Implementing class : YCL_IMPL implementing the interface ZINTF2 (automatically
includes ZINTF1 )
Implementations for Interface methods:

method ZINTF1~M1.
write :/ 'Inside method m1 of interface intf1..'.
endmethod.

method ZINTF1~M2.
write :/ 'Inside method m2 of interface intf1..'.
endmethod.

method ZINTF2~M3.
write :/ 'Inside method m3 of interface intf2..'.
endmethod.

Executable Program:

REPORT Z730OOPS35.

data ob type ref to ycl_impl.


create object ob.

*CALL METHOD OB->ZINTF1~M1


* .
*CALL METHOD OB->ZINTF1~M2
* .
*CALL METHOD OB->ZINTF2~M3
* .

call method ob->a4.


call method ob->a5.
*call method ob->a6. "syntax error
Exception Handling in Methods

- An exception is a runtime error which is raised during the program execution.

- If the exception is not handled, the program will be terminated.

- Exception handling is a process of handling the Runtime Error s and continues the
program execution without termination.

- The exceptions which are raised by SAP are called as Standard Exceptions.

- These standard exceptions are raised from standard exception classes which start with
Naming convention CX___ .

- We can handle these exceptions by using TRY and CATCH blocks.

- Inside the TRY Block we need to keep those statements where the possible exceptions
might occur.

- The CATCH block is placed immediately after the Try Block; it is responsible for
handling the exceptions by providing appropriate exception handling statements which
can be system defined exception message / user-defined exception message.

- CX_ROOT is common for any exceptions i.e it is super class for all exception classes.

- As part of the catch block we need to provide the exception class name which is
responsible for raising the exception.

- If we are not sure about the exception class, we can give the exception class name as
CX_ROOT .

- CX_ROOT is super class for all the exception classes.

Note:

Whenever an exception is raised in a TRY block, SAP creates the object of the exception
class which is raising the exception and the control will jump to catch block.

As part of catch block, we need to receive the exception class object into our local reference
of exception class and using this referenced object we can access the appropriate methods
of Exception class to capture standard exception messages.

Whenever an exception is raised in try block, SAP ignores the rest of the statements in the
try block and the control will jump to catch block.

Standard Exceptions:

Declared, Raised  By SAP


Handling  Developer (using try and catch block)

Cleanup block:

Cleanup block is provided as part of try block to execute certain statements mandatorily
whenever an exception is raised in the try block. In general, whenever an exception is raised
in the try block, the control jumps to catch block ignoring the rest of the statements in the
try block. In these cases, there might be certain statements which we need to execute
whenever an exception is raised, these statements we can provide as part of cleanup block.
If a try block contains cleanup block, we cannot have catch block, so in order to handle the
exception, catch block should be provided as part of outer try block. As part of cleanup
block, we can perform cleanup activities. i.e clearing the variables, free internal tables, close
the files…….

We should not abruptly terminate the execution of cleanup block using the statements
stop, submit and call transaction statements.

User-defined exceptions in methods:

These exceptions are declared, raised and handled by developer.

Procedure

1. Declare the exception in the method declaration by using ͞exceptions͟ keyword

Syntax: exceptions <exception name>.

2. Raise the exception in the method implementation at the appropriate place.

Syntax: raise <exception name>.

3. Handle the exception while calling the method by checking the sy-subrc status.

Note: We can use raise keyword to raise any exceptions i.e system defined or user-defined.

Raising keyword:

Raising is a keyword used as part of local class method declaration to indicate that a
method might raise the exception but cannot handle the exception.

In these cases, the caller of the method should take the responsibility of handling the
exception.
The advantage of this approach is since a method can be called any no. of times at different
places in the object, at each place, we can handle the exception in different way (custom
defined exception messages in one place, std.exception messages in another place..)

Custom Exception classes

We create custom exception classes to store the repository of custom exception messages

Global custom exception classes starts with ZCX_.... / YCX_.... and it must be subclass of
CX_STATIC_CHECK / CX_DYNAMIC_CHECK / CX_NO_CHECK .

These exception classes can be created by referring to

1. OTR (Online text repository) /


2. Message class

Global Exception classes are associated with Texts tab.

As part of Texts tab we need to create exception id s.

Whenever exception id is created, SAP creates corresponding constant attribute with the same
name. This attribute needs to be accessed while raising the exception from these exception
classes.

Each Exception id must be associated either with OTR Text / with message of a message class.

In case of Exception classes using OTR, each exception id that we create must be associated
with short text / long text / both.

In case of Exception classes using message class, each exception id that we create must be
associated with message id of a message class which can be static / dynamic message.

In case of Dynamic message, we need to create corresponding attributes for mapping to the
place holder of dynamic message.

The values for these attributes associated with placeholders should be passed at the time of
raising the exception.

Note: A Try block can be associated with n of catch blocks, but the catch block exception
classes should be in the ascending order of exception classes i.e from sub class to super classes.

Singleton class:

It is a class for which only one object can be created. It uses Singleton Design pattern.
Persistence service

It is used for storing the state of object (values of the object) permanently in the database.

By default, the life time of the object is local to the program i.e. once a program execution is
completed, memory allocated for the object will be destroyed.

Persistence object means -> permanent object

Any database operation (CRUD operations) can be achieved by using persistent service .

Persistence service is implemented by creating persistence classes.

Persistence class is always created globally (class builder).

The naming standard of persistent class is ZCL_<classname> / YCL_<classname> .

Persistence class is always created as protected class.

Whenever a persistence class is created, SAP creates two more classes internally.

a. Base agent class: (abstract class) i.e. ZCB_<class name> .

b. Actor /agent class: (Private class) i.e. ZCA_<class name> .

Base agent class: is a friend of persistence class and it is super class of ACTOR class.

Actor class: is a subclass of Base agent class

By Default, Persistence class implements a std. interface IF_OS_STATE which is responsible for
storing the state of the object permanently in the database.

Persistence service can be implemented in two ways:

1. Business key identify.

2. GUID (Global Unique Identifier).

Persistence service using business key identity:

- In this, we need to consider a database table in which the primary key field of the table
is considered as Business key identity .

- This field is used for uniquely identifying the object.

Procedure for using persistence service using Business key


1. Consider a db table.

Table: z730emp

Fields:

Empno (PK) zempno int4 10

Ename zename char 20

Empdesig zempdesig char 15

2. Create the persistence class.

Persistence class: zcl_emp_pers

Base agent class: zcb_emp_pers

Actor/agent class: zca_emp_pers

Note: By default, Persistence class implements the interface if_os_state which is responsible
for storing the state of the object permanently.

3. Map the Persistence class with the Corresponding data base table. (goto persistence
representation)

Note:- We must Map all the fields of the db table to the persistence class (double click
on each field and click on set attribute values button)

Note: Once the mapping is done, all the fields of the table will be added as attributes of
the persistence class.

- Apart from this, SAP GENERATES GET_ Methods for all attributes and SET_ methods
for non-primary key fields.

- Getter method is used for reading the value of the attribute and Setter method is used
for setting the value to the attribute.

4. Activate the persistence class so that dependent classes also get activated.

5. As part of this activation, SAP generates the following methods as part of base agent
class.

1. Create _Persistent

2. Delete_Persistent.
3. Get_Persistent

To interact with the Persistent object we need to access above 3 methods:

- To access the above 3 instance Methods we require object of base agent class, but the
base agent class is created as Abstract class . So, it cannot be instantiated directly.

- The above 3 methods are public and they are inherited to sub class which is Actor Class
or Agent class.

- But, Actor class IS created as Private Class , so, it cannot be instantiated directly
outside.

- Actor class is created as Singleton class, so there is a possibility of creating one and only
one object. So in order to get the object of the Actor class we must follow the following
Procedure.

- As part of every Actor class, SAP Provides Static Public Attribute Agent . This attribute
is marked as Read only i.e this attribute will return a value whenever it is accessed.

- Whenever this attribute is accessed by using Actor class name , internally SAP Executes
Static Constructor of Actor class which is Responsible for creating singleton (single
object) of actor class, This object will be returned back to the static attribute agent, we
need to receive this returned object so that we can access the above 3 methods.

- COMMIT WORK statement will save changes permanently in the database.

Persistence Service Using GUID (global unique identifier):

- In this we need to consider a database table whose first field is GUID and the
corresponding data element should be OS_GUID . The value for this field GUID will
be dynamically generated by SAP itself.

- We need to map the persistence class with this database table. After Mapping, except
GUID field all the remaining fields will be added as attributes of the persistence class.

- Apart from this, SAP Generates Getter & Setter methods as part of persistence class
for all the fields except GUID .

- When we activate the persistence class, SAP generates the following 3 Methods as part
of BASE AGENT CLASS .

1. Create_Persistent.

2. IF_OS_CA_PERSISTENCY~GET_PERSISTENT_BY_OID

1. IF_OS_FACTORY~DELETE_PERSISTENT.

Procedure for creating Persistence service using GUID:


Step1: consider a database table with GUID as first field.

Table: Z8AMEMP

Fields:

GUID (PK) os_guid

EMPNO zeMPno

ENAME zename

EMPDESIG zempdesig

Step2: create the persistence class( zcl_8amemp)

Base agent class  zcb_8amemp

Actor class zca_8amemp

Step3: Map the persistence class with the above table.

In persistence service using GUID the uniqueness of the object is controlled based on
the GUID field.

GET_PERSISTENT_BY_OID:

This method takes GUID as input and returns the object of the object class. This object class in
the runtime points to persistence class, so we need to type cast the object class object to
persistence class object. Using the persistence class object access the required getter methods.

DELETE_PERSISTENT:

This method takes the object of the interface if_os_state as input value, but we cannot
directly create objects for interfaces, so we need to analyze what is the implementation class
which is implementing this particular interface. As per the analysis, it is the persistence class
(zcl_9am_empl) which is implementing the interface if_os_state , so we can pass the object of
this persistence class as a parameter value. In order to get the object of persistence class, first
of all we have to check whether the GUID is existing or not this is done by calling the instance
method Get_Persistence_By_Oid .This method returns object of the object class, this object
class object needs to be type cast to persistence class object and pass that object as parameter
to Delete_Persistent .

Transaction service ---> used for managing OO transactions


The main use of this service is we can mark the begin of and end of OO transaction, so that we
can either save (commit) the complete transaction or cancel (rollback) the complete
transaction. As part of this transaction service, we use the following class and interfaces.

1. cl_os_system --> class

2. if_os_transaction

3. if_os_transaction_manager

Persistence class--> zcl_emp_pers

actor/agent class --> zca_emp_pers

base agent class --> zcb_emp_pers

Procedure for using Transaction service:

1. Get the transaction manager object: This is done by calling the static method
'get_transaction_manager' of the class 'cl_os_system'

2. Using the above transaction manager object, get the transaction object. This is done
by calling the instance method 'create_transaction' of the interface
'if_os_transaction_manager'

3. Using the above transaction object, mark the start of OO Transaction. This is done by
calling the 'start' method of the interface 'if_os_transaction'

4. Perform the Operation (Create / Delete / Update persistent object)

5. Try to end the transaction by calling the instance method 'end' of the interface
'if_os_transaction'. If the transaction fails, cancel the transaction by calling the method 'undo'
of the interface 'if_os_transaction.

Note: The above steps are provided by SAP as part of interface documentation
IF_OS_TRANSACTION .
exception classes hierarchy

Example: Exception Handling (Custom Exception Messages)

report z730oops36.

parameters : p_x type i,


p_y type i.

data v_res type i.

write :/ 'Before calculation....'.


try.
v_res = p_x / p_y.
*catch cx_sy_zerodivide. "(or)
catch cx_root.
message 'Cannot divide by zero.....' type 'I'.
endtry.

write :/ 'Division is ',v_res.


write :/ 'End of program....'.

Example: Exception Handling (Standard Exception Messages)

report z730oops37.

parameters : p_x type i,


p_y type i.
data v_res type i.

*data k type ref to cx_sy_zerodivide.


data k type ref to cx_root.

data : v_str type string,


v_pname type sy-repid,
v_iname type sy-repid,
v_pos type i.

write :/ 'Before calculation....'.


try.
v_res = p_x / p_y.
*catch cx_sy_zerodivide into k.
catch cx_root into k.
* message 'Cannot divide by zero.....' type 'I'.
format color 3.
call method k->if_message~get_text
receiving
result = v_str.

write :/ 'Short exception message is ',v_str.

uline.
clear v_str.
format color 7.
call method k->if_message~get_longtext
receiving
result = v_str.

write :/ 'Long exception message is ',v_str.

uline.
format color 1.
call method k->get_source_position
importing
program_name = v_pname
include_name = v_iname
source_line = v_pos.

write :/ 'Program name ...',v_pname,


/ 'Include name ...',v_iname,
/ 'Line no ...',v_pos.
format color off.
endtry.

write :/ 'Division is ',v_res.


write :/ 'End of program....'.

Example: Exception Handling in Methods

report z730oops38.

class lcl_abc definition.


public section.
methods m1 importing i_x type i i_y type i
exporting e_z type i.
endclass.

class lcl_abc implementation.


method m1.
try.
write :/ 'Begin of method m1...'.
e_z = i_x / i_y.
write :/ 'End of method m1...'.
catch cx_sy_zerodivide.
format color 3.
write :/ 'Inside catch block...'.
write :/ 'Cannot divide by Zero...'.
format color off.
endtry.
endmethod.
endclass.

start-of-selection.
parameters : p_x type i,
p_y type i.

data gv_z type i.

data ob type ref to lcl_abc.


create object ob.

call method ob->m1


exporting
i_x = p_x
i_y = p_y
importing
e_z = gv_z.

write :/ 'Division is ',gv_z.


write :/ 'End of program...'.

Example: Cleanup Block

report z730oops39.

class lcl_abc definition.


public section.
methods m1 importing i_x type i i_y type i
exporting e_z type i.
endclass.

class lcl_abc implementation.


method m1.
try.
try.
write :/ 'Begin of method m1...'.
e_z = i_x / i_y.
cleanup.
format color 7.
write :/ 'Inside Cleanup block..'.
* stop. "syntax error
* submit z730oops38. "runtime error
write :/ 'End of method m1...'.
format color off.
endtry.
catch cx_sy_zerodivide.
format color 3.
write :/ 'Inside catch block...'.
write :/ 'Cannot divide by Zero...'.
format color off.
endtry.
endmethod.
endclass.

start-of-selection.
parameters : p_x type i,
p_y type i.
data gv_z type i.

data ob type ref to lcl_abc.


create object ob.

call method ob->m1


exporting
i_x = p_x
i_y = p_y
importing
e_z = gv_z.

write :/ 'Division is ',gv_z.


write :/ 'End of program...'.

Example: Raising Keyword

report z730oops40.

class lcl_abc definition.


public section.
methods m1 importing i_x type i i_y type i
exporting e_z type i
raising cx_sy_zerodivide.
endclass.

class lcl_abc implementation.


method m1.
write :/ 'Begin of method m1...'.
e_z = i_x / i_y.
write :/ 'End of method m1...'.
endmethod.
endclass.

start-of-selection.
parameters : p_x type i,
p_y type i.

data gv_z type i.

data ob type ref to lcl_abc.


create object ob.
try.
call method ob->m1
exporting
i_x = p_x
i_y = p_y
importing
e_z = gv_z.
catch cx_sy_zerodivide.
format color 3.
write :/ 'Inside catch block...'.
write :/ 'Cannot divide by zero..'.
format color off.
endtry.

write :/ 'Division is ',gv_z.

uline.
data k type ref to cx_sy_zerodivide.
data str type string.
try.
call method ob->m1
exporting
i_x = p_x
i_y = p_y
importing
e_z = gv_z.
catch cx_sy_zerodivide into k.
call method k->if_message~get_text
receiving
result = str.

format color 7.
write :/ 'Inside catch block....'.
write :/ 'Short exception message is ',str.
format color off.
endtry.
write :/ 'Division is ',gv_z.

uline.
try.
call method ob->m1
exporting
i_x = p_x
i_y = p_y
importing
e_z = gv_z.
catch cx_sy_zerodivide into k.
clear str.
call method k->if_message~get_longtext
receiving
result = str.

format color 1.
write :/ 'Inside catch block....'.
write :/ 'Long exception message is ',str.
format color off.
endtry.
write :/ 'Division is ',gv_z.

write :/ 'End of program...'.

Example: User Defined Exceptions, Raise Keyword

report z730oops41.

class lcl_abc definition.


public section.
methods m1 importing i_x type i i_y type i
exporting e_z type i
exceptions myexception.
endclass.

class lcl_abc implementation.


method m1.
write :/ 'Begin of method m1...'.
if i_y eq 0.
raise myexception.
else.
e_z = i_x / i_y.
endif.
write :/ 'End of method m1...'.
endmethod.
endclass.

start-of-selection.
parameters : p_x type i,
p_y type i.
data gv_z type i.

data ob type ref to lcl_abc.


create object ob.

call method ob->m1


exporting
i_x = p_x
i_y = p_y
importing
e_z = gv_z
exceptions
myexception = 1
others = 2.

if sy-subrc eq 0.
write :/ 'Division is ',gv_z.
elseif sy-subrc eq 1.
write :/ 'Cannot divide by zero...'.
else.
write :/ 'Unknown exception...'.
endif.
write :/ 'End of program...'.

Example: User defined Exceptions at Global class Method level


Implementation:

method m1.
write :/ 'Begin of method m1...'.
if i_y eq 0.
raise myexception.
else.
e_z = i_x / i_y.
endif.
write :/ 'End of method m1...'.
endmethod.

Executable program:

report z730oops42.

data ob type ref to zcl_abc.


create object ob.

parameters : p_x type i,


p_y type i.

data gv_z type i.

call method ob->m1


exporting
i_x = p_x
i_y = p_y
importing
e_z = gv_z
exceptions
myexception = 12
others = 17.

if sy-subrc eq 0.
write :/ 'Division is ',gv_z.
elseif sy-subrc eq 12.
write :/ 'Cannot divide by zero'.
elseif sy-subrc eq 17.
write :/ 'Unknown error'.
endif.

Example: Custom Exception classes referring to OTR


Create a global custom exception class inheriting one of the standard exception class
͚CX_STATIC_CHECK͛

Create Exception ID͛S ID1 and ID2 as part of texts tab

Attributes ID1 and ID2 got created automatically


Associate short exception messages for exception ids ID1 and ID2

Associate long exception message for exception id ID1


Save, Check and activate

Executable program: Raising exceptions from above custom exception class

report z730oops43.

data : k type ref to zcx_myexceptions,


str type string.

try.
*condition check
raise exception type zcx_myexceptions
exporting
textid = zcx_myexceptions=>id1.
catch zcx_myexceptions into k.
format color 3.
write :/ 'EXCEPTION ID id1....'.
call method k->if_message~get_text
receiving
result = str.

write :/ str.
clear str.
call method k->if_message~get_longtext
receiving
result = str.

write :/ str.
format color off.
endtry.

uline.
try.
format color 7.
raise exception type zcx_myexceptions
exporting
textid = zcx_myexceptions=>id2.
catch zcx_myexceptions into k.
call method k->if_message~get_text
receiving
result = str.

write :/ str.

clear str.
call method k->if_message~get_longtext
receiving
result = str.

write :/ str.
endtry.
Example: Custom Exception classes using Message classes

Note: First create a Message class in SE91 with static and Dynamic messages

Now, Create a exception class in SE24 by selecting the checkbox message classes and create
two exception ids as part of Texts tab. Also create 4 attributes ATTR1 to ATTR4 as part of
Attributes tab. Map the exception id ID1 with static message 000 of message class and Map
the exception id ID2 with dynamic message 001 of message class. While mapping to dynamic
message , provide the attributes to map them to place holders of dynamic message.
Activate the exception class

Executable program:

report z730oops44.

data : k type ref to ycx_myexceptions,


str type string.

try.
raise exception type ycx_myexceptions
exporting
textid = ycx_myexceptions=>id1.
catch ycx_myexceptions into k.
format color 3.
call method k->if_message~get_text
receiving
result = str.

write :/ 'Short text for id1 ...',str.

clear str.
call method k->if_message~get_longtext
receiving
result = str.

write :/ 'Long text for id1 ...',str.


format color off.
endtry.

uline.
try.
raise exception type ycx_myexceptions
exporting
textid = ycx_myexceptions=>id2
attr1 = 'Gensoft Technologies'
attr2 = 'SAP Technical Training'
attr3 = 'Hyderabad'
attr4 = sy-datum.
catch ycx_myexceptions into k.
format color 7.
call method k->if_message~get_text
receiving
result = str.

write :/ 'Short text for id2 ...',str.

clear str.
call method k->if_message~get_longtext
receiving
result = str.

write :/ 'Long text for id2 ...',str.


format color off.
endtry.

Example: Singleton class

report z730oops45.

class lcl_singleton definition create private.


public section.
class-methods class_constructor.
class-methods m2 returning value(m) type ref to lcl_singleton.

methods m1.
protected section.
class-data k type ref to lcl_singleton.
endclass.

class lcl_singleton implementation.


method class_constructor.
format color 3.
write :/ 'Object getting created in static const...'.
create object k.
format color off.
endmethod.

method m2.
format color 7.
write :/ 'Object getting assigned to return reference in static method...'.
m = k.
format color off.
endmethod.

method m1.
format color 1.
write :/ 'Inside instance method m1..'.
format color off.
endmethod.
endclass.

start-of-selection.
data ob type ref to lcl_singleton.
* create object ob. "syntax error

ob = lcl_singleton=>m2( ).
call method ob->m1.

The below summary is for above program

Custom Exception classes referring to msg classes

msg class (se91)---> container of messages

--> 1000 msg's (static msg (hardcoded msg) /

dynamic msg (msg constructed in runtime)

--> msg id ranges --> 000 to 999

otr ---> online (local to that particular exception class)


msg class ---> global to all exception classes

ycx_myexceptions ---> z730msg(000,001)

ycx_myexceptions2 ---> z730msg(000,005,006)

singleton class:- maximum of only one object --> singleton design pattern

static constructor

method class_constructor.

create object ob.

endmethod.

30th june summary

object state in db
persistent state

persistent operations using business key identity

Implementing Persistence service using business key identity:

Persistence class Creation:

1. Create / Consider a DB table


2. Create a Persistence class ZCL_EMP_PERS and map with above db table (Open
persistence class and choose the menu GOTO  Persistence representation (Map all
the fields of the db table as attributes of persistence class)
Example: Persistent object CRUD Operations using Persistence Service using Business Key
Identity

Persistence class: zcl_emp_pers, Base agent class: zcb_emp_pers

Actor/Agent class: zca_emp_pers, DB table: z730emp

report z730oops46.

selection-screen begin of block bk1 with frame title t1.

selection-screen begin of line.


selection-screen comment 8(20) lb1.
parameters p_empno type z730emp-empno.
selection-screen end of line.

selection-screen begin of line.


selection-screen comment 8(20) lb2.
parameters p_ename type z730emp-ename.
selection-screen end of line.
selection-screen begin of line.
selection-screen comment 8(20) lb3.
parameters p_desig type z730emp-empdesig.
selection-screen end of line.

selection-screen end of block bk1.

selection-screen begin of block bk2 with frame title t2.


parameters : p_r1 radiobutton group grp1 user-command fc1,
p_r2 radiobutton group grp1,
p_r3 radiobutton group grp1,
p_r4 radiobutton group grp1,
p_r5 radiobutton group grp1 default 'X'.
selection-screen end of block bk2.

data : actor type ref to zca_emp_pers,


pers type ref to zcl_emp_pers.

initialization.
t1 = 'Employee'.
lb1 = 'Employee No'.
lb2 = 'Employee Name'.
lb3 = 'Designation'.
t2 = 'Operations'.
perform get_actor_object.

at selection-screen on radiobutton group grp1.


case sy-ucomm.
when 'FC1'.
if p_r1 = 'X'.
perform create_persistent_object.
elseif p_r2 = 'X'.
perform read_persistent_object.
elseif p_r3 = 'X'.
perform update_persistent_object.
elseif p_r4 = 'X'.
perform delete_persistent_object.
endif.
endcase.

form get_actor_object .
actor = zca_emp_pers=>agent.
endform. " GET_ACTOR_OBJECT
form create_persistent_object .
try.
call method actor->create_persistent
exporting
i_empno = p_empno
receiving
result = pers.

if pers is not initial.


* set ename and empdesig
try.
call method pers->set_ename
exporting
i_ename = p_ename.
catch cx_os_object_not_found .
message 'Exception in setting ename' type 'I'.
endtry.

try.
call method pers->set_empdesig
exporting
i_empdesig = p_desig.
catch cx_os_object_not_found .
message 'Exception in setting empdesig' type 'I'.
endtry.

commit work.
endif.
catch cx_os_object_existing.
message 'Exception in creating persistent object' type 'I'.
endtry.

endform. " CREATE_PERSISTENT_OBJECT

form read_persistent_object .
try.
call method actor->get_persistent
exporting
i_empno = p_empno
receiving
result = pers.

if pers is not initial.


* read ename and empdesig
clear : p_ename,
p_desig.
try.
call method pers->get_ename
receiving
result = p_ename.

catch cx_os_object_not_found .
message 'Failed to read ename' type 'I'.
endtry.

try.
call method pers->get_empdesig
receiving
result = p_desig.

catch cx_os_object_not_found .
message 'Failed to read empdesig' type 'I'.
endtry.
endif.
catch cx_os_object_not_found .
message 'Failed to read persistent object' type 'I'.
endtry.

endform. " READ_PERSISTENT_OBJECT

form update_persistent_object .
* check for existence of persistent object
try.
call method actor->get_persistent
exporting
i_empno = p_empno
receiving
result = pers.

if pers is not initial.


* modify ename and empdesig
try.
call method pers->set_ename
exporting
i_ename = 'Pramod'.

catch cx_os_object_not_found .
message 'Failed to modify ename' type 'I'.
endtry.

try.
call method pers->set_empdesig
exporting
i_empdesig = 'ABAP Developer'.

catch cx_os_object_not_found .
message 'Failed to modify empdesig' type 'I'.
endtry.

commit work.
endif.
catch cx_os_object_not_found .
message 'Failed to read persistent object' type 'I'.
endtry.

endform. " UPDATE_PERSISTENT_OBJECT

form delete_persistent_object .
try.
call method actor->delete_persistent
exporting
i_empno = p_empno.

commit work.
catch cx_os_object_not_existing .
message 'Persistent object not found for deletion' type 'I'.
endtry.
endform. " DELETE_PERSISTENT_OBJECT

Persistent object:-storing the state of the object permenently

traditional abap:

insert emp from wa.

insert emp from table itab.

modify emp from wa.


select ...wa / itab

insert emp from object. (No syntax available)

select ... into object (No syntax available)

pers.class ---> zcl_emp_pers (protected)

---> automatically implements an interface 'if_os_state'

automatically creates 2 classes

1. Base agent class ---> zcb_emp_pers (abstract)

---> friend of pers.class

--> super class for agent class

2. Agent / Actor class ---> zca_emp_pers (private)(singleton class)

--> sub class for base agent class

persistence service can be implemented in 2 ways

1. Business key identity --> consider db table

empno (pk) --> business key identity

ename

empdesig

2. Global Unique Identifier (GUID)

LOOP AT ITAB INTO WA.

PERS->EMPNO = WA-EMPNO.

PERS->ENAME = WA-ENAME.

PERS->EMPDESIG = WA-EMPDESIG.

CALL CREATE_PERSISTENT
ENDLOOP.

SELECT SINGLE F1 F2 ...

FROM DBTABLE

INTO WA

WHERE <KEY FIELD> = ....

update dbtable set f1 = ... f2 = ...

where keyfield = ....

delete .... from db table where <keyfield>= ...

next oops class ---> monday ---> 7 am to 8:30 am

1st july Summary

Implementing Persistence service using GUID

Persistence class Creation:

1. Create / Consider a DB table


2. Create a Persistence class YCL_EMP_PERS and map with above db table (Open
persistence class and choose the menu GOTO  Persistence representation
Example: Persistent object CRUD Operations using Persistence Service using GUID (CREATE
and Read Persistent objects)

Persistence class: ycl_emp_pers, Base agent class: ycb_emp_pers

Actor/Agent class: yca_emp_pers, DB table: y730emp

report z730oops47.

selection-screen begin of block bk1 with frame title t1.

selection-screen begin of line.


selection-screen comment 8(20) lb1.
parameters p_guid type y730emp-guid.
selection-screen end of line.

selection-screen begin of line.


selection-screen comment 8(20) lb2.
parameters p_empno type y730emp-empno.
selection-screen end of line.

selection-screen begin of line.


selection-screen comment 8(20) lb3.
parameters p_ename type y730emp-ename.
selection-screen end of line.

selection-screen begin of line.


selection-screen comment 8(20) lb4.
parameters p_desig type y730emp-empdesig.
selection-screen end of line.

selection-screen end of block bk1.

selection-screen begin of block bk2 with frame title t2.


parameters : p_r1 radiobutton group grp1 user-command fc1,
p_r2 radiobutton group grp1,
p_r3 radiobutton group grp1,
p_r4 radiobutton group grp1,
p_r5 radiobutton group grp1 default 'X'.
selection-screen end of block bk2.

data : actor type ref to yca_emp_pers,


pers type ref to ycl_emp_pers.
initialization.
t1 = 'Employee'.
lb1 = 'Guid'.
lb2 = 'Employee No'.
lb3 = 'Employee Name'.
lb4 = 'Designation'.
t2 = 'Operations'.
perform get_actor_object.

at selection-screen on radiobutton group grp1.


case sy-ucomm.
when 'FC1'.
if p_r1 = 'X'.
perform create_persistent_object.
elseif p_r2 = 'X'.
perform read_persistent_object.
elseif p_r3 = 'X'.
perform update_persistent_object.
elseif p_r4 = 'X'.
perform delete_persistent_object.
endif.
endcase.

form get_actor_object .
actor = yca_emp_pers=>agent.
endform. " GET_ACTOR_OBJECT

form create_persistent_object .
try.
call method actor->create_persistent
receiving
result = pers.

if pers is not initial.


* set the values for non-key fields
try.
call method pers->set_empno
exporting
i_empno = p_empno.
catch cx_os_object_not_found .
message 'Exception in setting empno value' type 'I'.
endtry.

try.
call method pers->set_ename
exporting
i_ename = p_ename.
catch cx_os_object_not_found .
message 'Exception in setting ename value' type 'I'.
endtry.

try.
call method pers->set_empdesig
exporting
i_empdesig = p_desig.
catch cx_os_object_not_found .
message 'Exception in setting empdesig value' type 'I'.
endtry.

commit work.
endif.
catch cx_os_object_existing .
message 'Exception in creating persistent object' type 'I'.
endtry.
endform. " CREATE_PERSISTENT_OBJECT

form read_persistent_object .
data ob type ref to object.
try.
call method actor->if_os_ca_persistency~get_persistent_by_oid
exporting
i_oid = p_guid
receiving
result = ob.

* pers = ob. "syntax error


* WIDENING CAST
pers ?= ob.
if pers is not initial.
clear : p_empno,
p_ename,
p_desig.

try.
call method pers->get_empno
receiving
result = p_empno.
catch cx_os_object_not_found .
message 'Empno not found' type 'I'.
endtry.
try.
call method pers->get_ename
receiving
result = p_ename.
catch cx_os_object_not_found .
message 'Ename not found' type 'I'.
endtry.

try.
call method pers->get_empdesig
receiving
result = p_desig.
catch cx_os_object_not_found .
message 'Empdesig not found' type 'I'.
endtry.
endif.
catch cx_os_object_not_found .
message 'Object Not found exception' type 'I'.
catch cx_os_class_not_found .
message 'Class Not found exception' type 'I'.
endtry.
endform. " READ_PERSISTENT_OBJECT

form update_persistent_object .
endform. " UPDATE_PERSISTENT_OBJECT
form delete_persistent_object .
endform. " DELETE_PERSISTENT_OBJECT

Logical unit of work


Example: Delete and Update Persistent objects using GUID

report z730oops48.

selection-screen begin of block bk1 with frame title t1.

selection-screen begin of line.


selection-screen comment 8(20) lb1.
parameters p_guid type y730emp-guid.
selection-screen end of line.

selection-screen begin of line.


selection-screen comment 8(20) lb2.
parameters p_empno type y730emp-empno.
selection-screen end of line.

selection-screen begin of line.


selection-screen comment 8(20) lb3.
parameters p_ename type y730emp-ename.
selection-screen end of line.

selection-screen begin of line.


selection-screen comment 8(20) lb4.
parameters p_desig type y730emp-empdesig.
selection-screen end of line.

selection-screen end of block bk1.

selection-screen begin of block bk2 with frame title t2.


parameters : p_r1 radiobutton group grp1 user-command fc1,
p_r2 radiobutton group grp1,
p_r3 radiobutton group grp1,
p_r4 radiobutton group grp1,
p_r5 radiobutton group grp1 default 'X'.
selection-screen end of block bk2.

data : actor type ref to yca_emp_pers,


pers type ref to ycl_emp_pers.

initialization.
t1 = 'Employee'.
lb1 = 'Guid'.
lb2 = 'Employee No'.
lb3 = 'Employee Name'.
lb4 = 'Designation'.
t2 = 'Operations'.
perform get_actor_object.

at selection-screen on radiobutton group grp1.


case sy-ucomm.
when 'FC1'.
if p_r1 = 'X'.
perform create_persistent_object.
elseif p_r2 = 'X'.
perform read_persistent_object.
elseif p_r3 = 'X'.
perform update_persistent_object.
elseif p_r4 = 'X'.
perform delete_persistent_object.
endif.
endcase.

form get_actor_object .
actor = yca_emp_pers=>agent.
endform. " GET_ACTOR_OBJECT

form create_persistent_object .
try.
call method actor->create_persistent
receiving
result = pers.

if pers is not initial.


* set the values for non-key fields
try.
call method pers->set_empno
exporting
i_empno = p_empno.
catch cx_os_object_not_found .
message 'Exception in setting empno value' type 'I'.
endtry.

try.
call method pers->set_ename
exporting
i_ename = p_ename.
catch cx_os_object_not_found .
message 'Exception in setting ename value' type 'I'.
endtry.

try.
call method pers->set_empdesig
exporting
i_empdesig = p_desig.
catch cx_os_object_not_found .
message 'Exception in setting empdesig value' type 'I'.
endtry.

commit work.
endif.
catch cx_os_object_existing .
message 'Exception in creating persistent object' type 'I'.
endtry.
endform. " CREATE_PERSISTENT_OBJECT

form read_persistent_object .
data ob type ref to object.
try.
call method actor->if_os_ca_persistency~get_persistent_by_oid
exporting
i_oid = p_guid
receiving
result = ob.

* pers = ob. "syntax error


* WIDENING CAST
pers ?= ob.
if pers is not initial.
clear : p_empno,
p_ename,
p_desig.

try.
call method pers->get_empno
receiving
result = p_empno.
catch cx_os_object_not_found .
message 'Empno not found' type 'I'.
endtry.

try.
call method pers->get_ename
receiving
result = p_ename.
catch cx_os_object_not_found .
message 'Ename not found' type 'I'.
endtry.

try.
call method pers->get_empdesig
receiving
result = p_desig.
catch cx_os_object_not_found .
message 'Empdesig not found' type 'I'.
endtry.
endif.
catch cx_os_object_not_found .
message 'Object Not found exception' type 'I'.
catch cx_os_class_not_found .
message 'Class Not found exception' type 'I'.
endtry.
endform. " READ_PERSISTENT_OBJECT

form update_persistent_object .
* check the existence of persistence object
data ob type ref to object.
try.
call method actor->if_os_ca_persistency~get_persistent_by_oid
exporting
i_oid = p_guid
receiving
result = ob.

* pers = ob. "syntax error


* WIDENING CAST
pers ?= ob.
if pers is not initial.
* call setter methods for updating persistent object
try.
call method pers->set_empno
exporting
i_empno = p_empno.
catch cx_os_object_not_found .
message 'Failed to update empno' type 'I'.
endtry.
try.
call method pers->set_ename
exporting
i_ename = p_ename.
catch cx_os_object_not_found .
message 'Failed to update ename' type 'I'.
endtry.

commit work.
endif.
catch cx_os_object_not_found .
message 'Object Not found exception' type 'I'.
catch cx_os_class_not_found .
message 'Class Not found exception' type 'I'.
endtry.

endform. " UPDATE_PERSISTENT_OBJECT

form delete_persistent_object.
* check the existence of persistence object
data ob type ref to object.
try.
call method actor->if_os_ca_persistency~get_persistent_by_oid
exporting
i_oid = p_guid
receiving
result = ob.

* pers = ob. "syntax error


* WIDENING CAST
pers ?= ob.
if pers is not initial.
* delete the persistent object
try.
call method actor->if_os_factory~delete_persistent
exporting
i_object = pers.
commit work.
catch cx_os_object_not_existing .
message 'Object not found for deletion' type 'I'.
endtry.
endif.
catch cx_os_object_not_found .
message 'Object Not found exception' type 'I'.
catch cx_os_class_not_found .
message 'Class Not found exception' type 'I'.
endtry.

endform. " DELETE_PERSISTENT_OBJECT

transaction service execution

Example: Transaction Service Usage

Create a global class (Normal usual class)

Implementation of the method ͚M1͛:


method m1.

* import the values from ABAP memory


data : p_empno type z730emp-empno,
p_ename type z730emp-ename,
p_desig type z730emp-empdesig.

data : v_empno type z730emp-empno,


v_ename type z730emp-ename,
v_desig type z730emp-empdesig.

*import p_empno from MEMORY id 'A1'.


*import p_ename from MEMORY id 'A2'.
*import p_desig from MEMORY id 'A3'. "not supported

import p_empno to v_empno from memory id 'A1'.


import p_ename to v_ename from memory id 'A2'.
import p_desig to v_desig from memory id 'A3'.

* get the transaction manager object


data o_trans_mng type ref to if_os_transaction_manager.
call method cl_os_system=>get_transaction_manager
receiving
result = o_trans_mng.

* get the transaction object


data o_trans type ref to if_os_transaction.
call method o_trans_mng->create_transaction
receiving
result = o_trans.

* start OO Transaction
try.
call method o_trans->start.

* Operations on Persistent object--->Create Persistent Object


* get the actor class object
data o_actor type ref to zca_emp_pers.
o_actor = zca_emp_pers=>agent.

* create persistent object


data o_pers type ref to zcl_emp_pers.
try.
call method o_actor->create_persistent
exporting
i_empno = v_empno
receiving
result = o_pers.

if o_pers is not initial.


* set the ename and empdesig
try.
call method o_pers->set_ename
exporting
i_ename = v_ename.
catch cx_os_object_not_found .
message 'Failed to set ename' type 'I'.
endtry.

try.
call method o_pers->set_empdesig
exporting
i_empdesig = v_desig.
catch cx_os_object_not_found .
message 'Failed to set empdesig' type 'I'.
endtry.
endif.

catch cx_os_object_existing .
message 'Exception in creating persistent object' type 'I'.
endtry.

catch cx_os_transaction .
message 'Exception in starting OO Transaction' type 'I'.
endtry.

* End the OO Transaction


try.
call method o_trans->end. "internally executes commit work
catch cx_os_check_agent_failed .
catch cx_os_transaction .
* cancel the OO Transaction completely
call method o_trans->undo. "internally executes rollback
endtry.
endmethod.

Create the T-code for the above class method:


Executable program: for accessing Transaction Service

report z730oops49.
*data ob type ref to z730_transaction.
*create object ob.
*call method ob->m1.
parameters : p_empno type z730emp-empno,
p_ename type z730emp-ename,
p_desig type z730emp-empdesig.
export p_empno to memory id 'A1'.
export p_ename to memory id 'A2'.
export p_desig to memory id 'A3'.

call transaction 'ZTR'.


ALV (ABAP / ADVANCED LIST VIEWER): is a report

Classical Reporting Procedure:

1. Generate the Selection screen for reading user input (Parameters / select-
options)

2. Validate the User Input

3. Retrieve the data from database table/s into internal tables/work areas using
Select Query

4. Process the Retrieved data (sort/modify/append/delete...)

5. Display the processed data on L.P.S

ALV Reports can be developed in 3 ways

1. ALV Reporting using F.M's

2. ALV Reporting using Classes (Recommended)

3. ALV Object Model

ALV Reporting using Function Modules:

As part of this, we use following F.M s for display

a. REUSE_ALV_LIST_DISPLAY

b. REUSE_ALV_GRID_DISPLAY

Procedure for ALV reporting using function modules:

1. Declaration

2. Retrieve data

3. Field catalogue generation

4. Display

As part of the function module REUSE_ALV_GRID_DISPLAY there is only one mandatory


parameter T_OUTTAB . This parameter holds the internal table containing data. If we pass
only this parameter value as part of F.M call, it leads to Abort Error-Field Catalog Not
Found . The reason for this error is, we must specify the field catalog information. This
information can be specified in two ways.

i. By specifying the dictionary structure name.

ii. By specifying the field catalog directly.


Field catalogue:

It is an object which contains the information s of the fields display in the ALV Grid . This
information includes name of the field, position, label, grid, appearance etc. To specify the field
catalogue information using the dictionary structure, we need to use the importing parameter
I_STRUCTURE_NAME as part of the function module REUSE_ALV_GRID_DISPLAY . Whenever
this parameter is specified all the properties of the field are taken from dictionary itself.

The structure name passed must match with the format of internal table i.e. the no of fields
and sequence of fields in the structure and in the internal table must match otherwise it leads
to runtime error.

GENERATING FIELD CATALOGUE using standard Function Module


REUSE_ALV_FIELDCATALOG_MERGE’

This function module takes the dictionary structure as input, generates the field catalogue
based on structure fields and returns the field catalogue which is of type internal table
SLIS_T_FIELDCAT_ALV .

Note: It is recommended to generate the Field catalog manually, as we have better flexibility
and control of the fields. For this, we need to prepare work area for each field and append the
same to the internal table of type SLIS_T_FIELDCAT_ALV .

INTERACTIVE ALV REPORTING:

- This is generated based on the user interaction in the runtime.

- To handle events in ALV reports developed using function module we need to consider
the parameter IT_EVENTS as part of the F.M REUSE_ALV_GRID_DISPLAY .

- This parameter is an internal table of type SLIS_T_EVENT .

- This internal table holds the events information (refer to the document of the
parameter IT_EVENTS to get the events list).

- This internal table is associated with two fields.

1. Name and 2. Form


- Name holds the name of the event.

- Form holds the name of the user defined subroutine.

- As part of this subroutine definition, we need to implement the business logic related to
the event.

- This subroutine will be called by SAP whenever event is Triggered.


- By reading the documentation of the parameter IT_EVENTS we can understand what
events are supported in ALV using F.M s.

USER_COMMAND:-

This event is triggered when the user double clicks on ALV cell value (or) single click on hotspot
cell value. This event contains two parameters.

i. Parameter of type – sy-ucomm.

ii. Parameter of type slis_selfield.

Note:

To handle the events we need to specify the parameter I_CALLBACK_PROGRAM as part of


F.M REUSE_ALV_GRID_DISPLAY so that whenever the event is triggered SAP will search for the
corresponding event subroutine definition in the specified calling program.

Reuse_Alv_Commentary_Write is a function module used for Associating text and Logo to


the TOP OF PAGE Area of ALV report developed using F.M. This F.M should be called as part of
user defined subroutine definition associated with the event TOP_OF_PAGE .

Displaying LOGO in ALV report using function module:

 Upload the logo using the Transaction code OAER .

Step 1:

GOTO-> SE93->Enter Transaction-> OAER

Step 2:

In OAER Transaction -> enter the values in following below.

Class name -> pictures.

Class type -> OT.

Object key-> object name (any unique id).

And execute.

Step 3:

In the next screen , in the top pane, choose pictures , and in bottom pane, ->doctype-
>expand->standard doc types->double click on screen entry->choose filename (logo
file) from local drive->continue.
Blocked Alv:

- It is used for displaying the data in the form of blocks.

- As part of this we use following function modules.

- Reuse_alv_block_list_init.

- Reuse_alv_block_list_append.

- Reuse_alv_block_list_display.

Procedure:

Step 1:

Initialize the ALV blocked list using the function module.

Reuse_alv_block_list_init .

Step 2:

Generate the field catalog for the block.

Step 3:

Retrieve the data for the block.

Append the field catalog and the data to the blocked list using the function module
Reuse_alv_block_list_append .

Note:

Repeat the steps 2,3 for each of the block.

Step 4:

Display the ALV blocked list using the function module

Reuse_alv_block_list_display.

Note: Reuse_alv_events_get is the function module which returns list of events supported in
ALV function modules.
ALV Interactive Reporting using F.M, Image Display, Blocked List

Example: ALV Reporting Using Function Module – ABORT ERROR

report z730alvfm1.

include z730alvfm1_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM1_INC

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.


form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call function 'REUSE_ALV_GRID_DISPLAY'
tables
t_outtab = t_vbak
exceptions
program_error =1
others = 2.

if sy-subrc eq 1.
message 'Program error' type 'I'.
elseif sy-subrc eq 2.
message 'Unknown error' type 'I'.
endif.
endform. " DISPLAYSALESORDERS

Example: ALV Reporting using Function Module – Field Catalog info. Using Dictionary
Structure

report z730alvfm2.

include z730alvfm2_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM2_INC

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.
data t_vbak type table of ty_vbak.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
i_structure_name = 'ZCVBAK'
tables
t_outtab = t_vbak
exceptions
program_error =1
others = 2.

if sy-subrc eq 1.
message 'Program error' type 'I'.
elseif sy-subrc eq 2.
message 'Unknown error' type 'I'.
endif.
endform. " DISPLAYSALESORDERS

Example: ALV Reporting using Function Module – Field Catalog generated using F.M and
Modified at Report Level

report z730alvfm3.

include z730alvfm3_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform fldcatsalesorders.
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.
Include Program: Z730ALVFM3_INC

*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
it_fieldcat = t_fldcat
tables
t_outtab = t_vbak
exceptions
program_error =1
others = 2.

if sy-subrc eq 1.
message 'Program error' type 'I'.
elseif sy-subrc eq 2.
message 'Unknown error' type 'I'.
endif.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
call function 'REUSE_ALV_FIELDCATALOG_MERGE'
exporting
i_structure_name = 'ZCVBAK'
changing
ct_fieldcat = t_fldcat.

if t_fldcat is not initial.


loop at t_fldcat into wa_fldcat.
if wa_fldcat-fieldname = 'ERDAT'.
wa_fldcat-col_pos = 3.
modify t_fldcat from wa_fldcat transporting col_pos.
elseif wa_fldcat-fieldname = 'ERZET'.
wa_fldcat-col_pos = 2.
modify t_fldcat from wa_fldcat transporting col_pos.
elseif wa_fldcat-fieldname = 'ERNAM'.
wa_fldcat-seltext_m = 'Created Person'.
modify t_fldcat from wa_fldcat transporting seltext_m.
endif.
endloop.
endif.
endform. " FLDCATSALESORDERS

Example: ALV Reporting Using Function Module – Field Catalog manipulation using Field
Symbol Work area

report z730alvfm4.

include z730alvfm4_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform fldcatsalesorders.
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM4_INC

*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

field-symbols <abc> like line of t_fldcat.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
it_fieldcat = t_fldcat
tables
t_outtab = t_vbak
exceptions
program_error =1
others = 2.

if sy-subrc eq 1.
message 'Program error' type 'I'.
elseif sy-subrc eq 2.
message 'Unknown error' type 'I'.
endif.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
call function 'REUSE_ALV_FIELDCATALOG_MERGE'
exporting
i_structure_name = 'ZCVBAK'
changing
ct_fieldcat = t_fldcat.

if t_fldcat is not initial.


loop at t_fldcat assigning <abc>.
if <abc>-fieldname = 'ERDAT'.
<abc>-col_pos = 3.
elseif <abc>-fieldname = 'ERZET'.
<abc>-col_pos = 2.
elseif <abc>-fieldname = 'ERNAM'.
<abc>-seltext_m = 'Created Person'.
endif.
endloop.
endif.
endform. " FLDCATSALESORDERS

Example: ALV Reporting using Function Module – Field Catalog Generated Manually, Event
Handling Process in ALV F.M’s

report z730alvfm5.

include z730alvfm5_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform fldcatsalesorders.
perform prepareevents.
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM5_INC

*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

data : t_events type slis_t_event,


wa_events like line of t_events.
form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
* I_CALLBACK_PROGRAM = 'Z730ALVSUBPOOL' "(or)
i_callback_program = sy-repid
it_fieldcat = t_fldcat
it_events = t_events
tables
t_outtab = t_vbak
exceptions
program_error =1
others = 2.

if sy-subrc eq 1.
message 'Program error' type 'I'.
elseif sy-subrc eq 2.
message 'Unknown error' type 'I'.
endif.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
clear wa_fldcat.
wa_fldcat-fieldname = 'VBELN'.
wa_fldcat-col_pos = 1.
wa_fldcat-seltext_m = 'Sales Document'.
wa_fldcat-outputlen = 12.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERDAT'.
wa_fldcat-col_pos = 2.
wa_fldcat-seltext_m = 'Date of Creation'.
wa_fldcat-outputlen = 15.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERZET'.
wa_fldcat-col_pos = 3.
wa_fldcat-seltext_m = 'Time of Creation'.
wa_fldcat-outputlen = 15.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERNAM'.
wa_fldcat-col_pos = 4.
wa_fldcat-seltext_m = 'Name of Created User'.
wa_fldcat-outputlen = 25.
append wa_fldcat to t_fldcat.

endform. " FLDCATSALESORDERS

form prepareevents .
clear wa_events.
wa_events-name = 'USER_COMMAND'.
wa_events-form = 'SALESITEMS'.
append wa_events to t_events.
endform. " PREPAREEVENTS

form salesitems using ucomm type sy-ucomm


sel type slis_selfield.
message 'Sales items' type 'I'.
endform.

Subroutine Pool: Z730ALVSUBPOOL

program z730alvsubpool.

form salesitems using ucomm type sy-ucomm


sel type slis_selfield.
message 'Sales items' type 'I'.
endform.

Example: Interactive ALV Reporting using Function Modules

report z730alvfm6.

include z730alvfm6_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform fldcatsalesorders.
perform prepareevents.
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM6_INC

*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak like line of t_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap like line of t_vbap.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

data : t_events type slis_t_event,


wa_events like line of t_events.

types : begin of ty_marc,


matnr type marc-matnr,
werks type marc-werks,
ekgrp type marc-ekgrp,
end of ty_marc.

data t_marc type table of ty_marc.

types : begin of ty_mard,


matnr type mard-matnr,
werks type mard-werks,
lgort type mard-lgort,
end of ty_mard.

data t_mard type table of ty_mard.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
* I_CALLBACK_PROGRAM = 'Z730ALVSUBPOOL' "(or)
i_callback_program = sy-repid
it_fieldcat = t_fldcat
it_events = t_events
tables
t_outtab = t_vbak
exceptions
program_error =1
others = 2.

if sy-subrc eq 1.
message 'Program error' type 'I'.
elseif sy-subrc eq 2.
message 'Unknown error' type 'I'.
endif.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
clear wa_fldcat.
wa_fldcat-fieldname = 'VBELN'.
wa_fldcat-col_pos = 1.
wa_fldcat-seltext_m = 'Sales Document'.
wa_fldcat-outputlen = 12.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERDAT'.
wa_fldcat-col_pos = 2.
wa_fldcat-seltext_m = 'Date of Creation'.
wa_fldcat-outputlen = 15.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERZET'.
wa_fldcat-col_pos = 3.
wa_fldcat-seltext_m = 'Time of Creation'.
wa_fldcat-outputlen = 15.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERNAM'.
wa_fldcat-col_pos = 4.
wa_fldcat-seltext_m = 'Name of Created User'.
wa_fldcat-outputlen = 25.
append wa_fldcat to t_fldcat.

endform. " FLDCATSALESORDERS

form prepareevents .
clear wa_events.
wa_events-name = 'USER_COMMAND'.
wa_events-form = 'SALESITEMS'.
append wa_events to t_events.
endform. " PREPAREEVENTS

form salesitems using ucomm type sy-ucomm


sel type slis_selfield.
* message 'Sales items' type 'I'.
case sel-fieldname.
when 'VBELN'.
read table t_vbak into wa_vbak index sel-tabindex
transporting vbeln.
if sy-subrc eq 0.
perform getsalesitems.
if t_vbap is not initial.
perform fldcatsalesitems.
perform reg_events.
perform displaysalesitems.
endif.
endif.
when others.
message 'Please double click on Sales Document No' type 'I'.
endcase.
endform.

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
where vbeln = wa_vbak-vbeln.
endform. " GETSALESITEMS

form fldcatsalesitems .
refresh t_fldcat.
clear wa_fldcat.
wa_fldcat-fieldname = 'VBELN'.
wa_fldcat-col_pos = 1.
wa_fldcat-seltext_m = 'Sales Document'.
wa_fldcat-outputlen = 12.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'POSNR'.
wa_fldcat-col_pos = 2.
wa_fldcat-seltext_m = 'Item No'.
wa_fldcat-outputlen = 8.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'MATNR'.
wa_fldcat-col_pos = 3.
wa_fldcat-seltext_m = 'Material Number'.
wa_fldcat-outputlen = 20.
wa_fldcat-hotspot = 'X'.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'NETWR'.
wa_fldcat-col_pos = 4.
wa_fldcat-seltext_m = 'Net Value'.
wa_fldcat-outputlen = 15.
append wa_fldcat to t_fldcat.

endform. " FLDCATSALESITEMS


form displaysalesitems .
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
i_callback_program = sy-repid
i_grid_title = 'SALES ITEMS'
it_fieldcat = t_fldcat
it_events = t_events
tables
t_outtab = t_vbap.
endform. " DISPLAYSALESITEMS

form reg_events .
refresh t_events.
clear wa_events.
wa_events-name = 'TOP_OF_PAGE'.
wa_events-form = 'HEADING'.
append wa_events to t_events.

clear wa_events.
wa_events-name = 'USER_COMMAND'.
wa_events-form = 'MATERIALS'.
append wa_events to t_events.

endform. " REG_EVENTS

form heading.
* message 'top of page event' type 'I'.
data : t_header type slis_t_listheader,
wa_header like line of t_header.

clear wa_header.
wa_header-typ = 'H'.
wa_header-info = 'Gensoft Technologies'.
append wa_header to t_header.

clear wa_header.
wa_header-typ = 'S'.
wa_header-key = 'Date :'.
wa_header-info = sy-datum.
append wa_header to t_header.

clear wa_header.
wa_header-typ = 'A'.
wa_header-info = 'SAP Technical Training'.
append wa_header to t_header.

call function 'REUSE_ALV_COMMENTARY_WRITE'


exporting
it_list_commentary = t_header
i_logo = 'ZTIGER'.
endform.

form materials using ucomm type sy-ucomm


sel type slis_selfield.
* message 'materials' type 'I'.
case sel-fieldname.
when 'MATNR'.
* extract material no
clear wa_vbap.
read table t_vbap into wa_vbap index sel-tabindex
transporting matnr.
if sy-subrc eq 0.
perform alvblocks.
endif.
when others.
message 'Please select material only' type 'I'.
endcase.
endform.

form alvblocks .
* initialize the ALV Blocked list
call function 'REUSE_ALV_BLOCK_LIST_INIT'
exporting
i_callback_program = sy-repid.

data wa_layout type slis_layout_alv.


* layout for blocks
wa_layout-zebra = 'X'. "Alternate line coloring (striped pattern)
* field catalog for block 1(material plants)
perform fldcatmaterialplants.
* get material plant data
perform getmaterialplants.
if t_marc is not initial.
refresh t_events.
* append field catalog and data for block 1
call function 'REUSE_ALV_BLOCK_LIST_APPEND'
exporting
is_layout = wa_layout
it_fieldcat = t_fldcat
i_tabname = 'T_MARC'
it_events = t_events
tables
t_outtab = t_marc.
endif.

* field catalog for block 2 (material storage data)


perform fldcatmaterialstorage.
* get material storage data
perform getmaterialstorageloc.
if t_mard is not initial.
* append field catalog and data for block 2
refresh t_events.
call function 'REUSE_ALV_BLOCK_LIST_APPEND'
exporting
is_layout = wa_layout
it_fieldcat = t_fldcat
i_tabname = 'T_MARD'
it_events = t_events
tables
t_outtab = t_mard.
endif.

* display the ALV blocked list


call function 'REUSE_ALV_BLOCK_LIST_DISPLAY'.
endform. " ALVBLOCKS

form fldcatmaterialplants .
refresh t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'MATNR'.
wa_fldcat-col_pos = 1.
wa_fldcat-seltext_m = 'Material Number'.
wa_fldcat-outputlen = 20.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'WERKS'.
wa_fldcat-col_pos = 2.
wa_fldcat-seltext_m = 'Plant'.
wa_fldcat-outputlen = 10.
append wa_fldcat to t_fldcat.
clear wa_fldcat.
wa_fldcat-fieldname = 'EKGRP'.
wa_fldcat-col_pos = 3.
wa_fldcat-seltext_m = 'Purchase Group'.
wa_fldcat-outputlen = 15.
append wa_fldcat to t_fldcat.

endform. " FLDCATMATERIALPLANTS

form getmaterialplants .
select matnr werks ekgrp
from marc
into table t_marc
where matnr = wa_vbap-matnr.
endform. " GETMATERIALPLANTS

form fldcatmaterialstorage .
refresh t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'MATNR'.
wa_fldcat-col_pos = 1.
wa_fldcat-seltext_m = 'Material Number'.
wa_fldcat-outputlen = 20.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'WERKS'.
wa_fldcat-col_pos = 2.
wa_fldcat-seltext_m = 'Plant'.
wa_fldcat-outputlen = 10.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'LGORT'.
wa_fldcat-col_pos = 3.
wa_fldcat-seltext_m = 'Storage Location'.
wa_fldcat-outputlen = 15.
append wa_fldcat to t_fldcat.

endform. " FLDCATMATERIALSTORAGE

form getmaterialstorageloc .
select matnr werks lgort
from mard
into table t_mard
where matnr = wa_vbap-matnr.
endform. " GETMATERIALSTORAGE

Example: Hierarchial ALV Report – Abort Error – Field Catalog Not Found

report z730alvfm7.

include z730alvfm7_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform getsalesitems.
if t_vbap is not initial.
perform regkeyinfo.
perform display.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM7_INC

*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak like line of t_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap like line of t_vbap.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

data wa_keyinfo type slis_keyinfo_alv.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
for all entries in t_vbak
where vbeln = t_vbak-vbeln.
endform. " GETSALESITEMS
form display .
call function 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
exporting
i_tabname_header = 'T_VBAK'
i_tabname_item = 'T_VBAP'
is_keyinfo = wa_keyinfo
tables
t_outtab_header = t_vbak
t_outtab_item = t_vbap.
endform. " DISPLAY

form regkeyinfo .
clear wa_keyinfo.
wa_keyinfo-header01 = 'VBELN'.
wa_keyinfo-item01 = 'VBELN'.
wa_keyinfo-header02 = ''.
wa_keyinfo-item02 = 'POSNR'.
endform. " REGKEYINFO

Example: Hierarchial ALV Report – Run Time error (As Field catalog Internal table and Data
Internal table fields structure is different)

report z730alvfm8.

include z730alvfm8_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform getsalesitems.
if t_vbap is not initial.
perform regkeyinfo.
perform fldcat.
perform display.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM8_INC


*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak like line of t_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap like line of t_vbap.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

data wa_keyinfo type slis_keyinfo_alv.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
for all entries in t_vbak
where vbeln = t_vbak-vbeln.
endform. " GETSALESITEMS

form display .
call function 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
exporting
it_fieldcat = t_fldcat
i_tabname_header = 'T_VBAK'
i_tabname_item = 'T_VBAP'
is_keyinfo = wa_keyinfo
tables
t_outtab_header = t_vbak
t_outtab_item = t_vbap.
endform. " DISPLAY

form regkeyinfo .
clear wa_keyinfo.
wa_keyinfo-header01 = 'VBELN'.
wa_keyinfo-item01 = 'VBELN'.
wa_keyinfo-header02 = ''.
wa_keyinfo-item02 = 'POSNR'.
endform. " REGKEYINFO

form fldcat .
call function 'REUSE_ALV_FIELDCATALOG_MERGE'
exporting
i_structure_name = 'ZCVBAK'
changing
ct_fieldcat = t_fldcat.

call function 'REUSE_ALV_FIELDCATALOG_MERGE'


exporting
i_structure_name = 'ZCVBAP'
changing
ct_fieldcat = t_fldcat.

endform. " FLDCAT

Example: Hierarchial ALV Report – Field Catalog generated and merged using F.M

report z730alvfm9.

include z730alvfm9_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform getsalesitems.
if t_vbap is not initial.
perform regkeyinfo.
perform fldcat.
perform display.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM9_INC

*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak like line of t_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap like line of t_vbap.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

data wa_keyinfo type slis_keyinfo_alv.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
for all entries in t_vbak
where vbeln = t_vbak-vbeln.
endform. " GETSALESITEMS

form display .
call function 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
exporting
it_fieldcat = t_fldcat
i_tabname_header = 'T_VBAK'
i_tabname_item = 'T_VBAP'
is_keyinfo = wa_keyinfo
tables
t_outtab_header = t_vbak
t_outtab_item = t_vbap.
endform. " DISPLAY

form regkeyinfo .
clear wa_keyinfo.
wa_keyinfo-header01 = 'VBELN'.
wa_keyinfo-item01 = 'VBELN'.
wa_keyinfo-header02 = ''.
wa_keyinfo-item02 = 'POSNR'.
endform. " REGKEYINFO

form fldcat .
call function 'REUSE_ALV_FIELDCATALOG_MERGE'
exporting
i_structure_name = 'ZCVBAK'
i_internal_tabname = 'T_VBAK'
changing
ct_fieldcat = t_fldcat.

call function 'REUSE_ALV_FIELDCATALOG_MERGE'


exporting
i_structure_name = 'ZCVBAP'
i_internal_tabname = 'T_VBAP'
changing
ct_fieldcat = t_fldcat.

endform. " FLDCAT


Example: Hierarchial ALV Report – Field Catalog generated manually

report z730alvfm10.

include z730alvfm10_inc.

start-of-selection.
perform getsalesorders.
if t_vbak is not initial.
perform getsalesitems.
if t_vbap is not initial.
perform regkeyinfo.
perform fldcat.
perform display.
else.
message 'No Sales Items' type 'I'.
endif.
else.
message 'No Sales Orders' type 'I'.
endif.

Include Program: Z730ALVFM10_INC

*type-pools slis. "mandatory declaration in older versions

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak like line of t_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap like line of t_vbap.

data : t_fldcat type slis_t_fieldcat_alv,


wa_fldcat like line of t_fldcat.

data wa_keyinfo type slis_keyinfo_alv.

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
for all entries in t_vbak
where vbeln = t_vbak-vbeln.
endform. " GETSALESITEMS
form display .
call function 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
exporting
it_fieldcat = t_fldcat
i_tabname_header = 'T_VBAK'
i_tabname_item = 'T_VBAP'
is_keyinfo = wa_keyinfo
tables
t_outtab_header = t_vbak
t_outtab_item = t_vbap.
endform. " DISPLAY

form regkeyinfo .
clear wa_keyinfo.
wa_keyinfo-header01 = 'VBELN'.
wa_keyinfo-item01 = 'VBELN'.
wa_keyinfo-header02 = ''.
wa_keyinfo-item02 = 'POSNR'.
endform. " REGKEYINFO

form fldcat .
clear wa_fldcat.
wa_fldcat-fieldname = 'VBELN'.
wa_fldcat-col_pos = 1.
wa_fldcat-outputlen = 12.
wa_fldcat-seltext_m = 'Sales Doc'.
wa_fldcat-tabname = 'T_VBAK'.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERDAT'.
wa_fldcat-col_pos = 2.
wa_fldcat-outputlen = 12.
wa_fldcat-seltext_m = 'Date'.
wa_fldcat-tabname = 'T_VBAK'.
append wa_fldcat to t_fldcat.

clear wa_fldcat.
wa_fldcat-fieldname = 'ERZET'.
wa_fldcat-col_pos = 3.

wa_fldcat-outputlen = 12.
wa_fldcat-seltext_m = 'Time'.
wa_fldcat-tabname = 'T_VBAK'.
append wa_fldcat to t_fldcat.
clear wa_fldcat.
wa_fldcat-fieldname = 'ERNAM'.
wa_fldcat-col_pos = 4.
wa_fldcat-outputlen = 20.
wa_fldcat-seltext_m = 'Person'.
wa_fldcat-tabname = 'T_VBAK'.
append wa_fldcat to t_fldcat.
clear wa_fldcat.
wa_fldcat-fieldname = 'VBELN'.
wa_fldcat-col_pos = 5.
wa_fldcat-outputlen = 12.
wa_fldcat-seltext_m = 'Person'.
wa_fldcat-tabname = 'T_VBAP'.
append wa_fldcat to t_fldcat.
clear wa_fldcat.
wa_fldcat-fieldname = 'POSNR'.
wa_fldcat-col_pos = 6.
wa_fldcat-outputlen = 12.
wa_fldcat-seltext_m = 'Item No'.
wa_fldcat-tabname = 'T_VBAP'.
append wa_fldcat to t_fldcat.
clear wa_fldcat.
wa_fldcat-fieldname = 'MATNR'.
wa_fldcat-col_pos = 7.
wa_fldcat-outputlen = 12.
wa_fldcat-seltext_m = 'Material'.
wa_fldcat-tabname = 'T_VBAP'.
append wa_fldcat to t_fldcat.
clear wa_fldcat.
wa_fldcat-fieldname = 'NETWR'.
wa_fldcat-col_pos = 8.
wa_fldcat-outputlen = 12.
wa_fldcat-seltext_m = 'Net Value'.
wa_fldcat-tabname = 'T_VBAP'.
append wa_fldcat to t_fldcat.
endform. " FLDCAT
Procedure for Classical Reporting:

1. Generate a selection screen for reading user input

2. Retrieve data from database tables based on user input

3. Process the internal table for display (write)

--> displays the output in L.P.S

Procedure for developing ALV reports using classes:

1. Create a Module pool screen

2. Place custom control component on the module pool screen

3. Create the object for container class 'CL_GUI_CUSTOM_CONTAINER linking with


custom control (physical control on module pool screen toolbox)

4. Create the object for grid class 'CL_GUI_ALV_GRID' linking with


container object

5. Retrieve the data to be displayed in the ALV grid

6. Generate the field catalog for the fields of ALV grid

7. Generate the layout for the ALV grid (optional)

8. Display the data in the ALV grid using the method 'SET_TABLE_FOR_FIRST_DISPLAY'
of the grid class 'cl_gui_alv_grid'

Field catalog Generation:

Whenever we display the data in the form of ALV report, we need to provide field catalog
information; otherwise the report execution leads to ABORT error. In case of ALV reporting
using classes, we can generate field catalog in 2 ways.

1. Using the function module LVC_FIELDCATALOG_MERGE : As part of this F.M call, we


need to provide the dictionary structure containing the required fields (fields provided
as part of internal table) , based on this dictionary structure fields SAP constructs the
fieldcatalog internal table and returns which is of type LVC_T_FCAT .

2. Manually
Note: In either of the above 2 process, once the fieldcatalog is generated, we need to pass it as
a value to the parameter IT_FIELDCATALOG as part of the method call
SET_TABLE_FOR_FIRST_DISPLAY .

Excluding the standard ALV toolbar pushbuttons:


For this we need to identify the function codes of the ALV toolbar buttons and prepare an
internal table with those function codes and pass the internal table as a value to the parameter
IT_TOOLBAR_EXCLUDING of the method SET_TABLE_FOR_FIRST_DISPLAY . All the ALV
toolbar buttons function codes exist in the form of constant public attributes with the naming
standard MC_FC… of the class CL_GUI_ALV_GRID .

Note: For excluding entire ALV toolbar in the Report, set the field NO_TOOLBAR to X as part
of Layout.

ALV Column as pushbutton:

For displaying the entire ALV column as pushbutton, set the field STYLE as part of field catalog.
All the styles exist in the form of constant attributes with the naming standard MC_STYL as
part of the class CL_GUI_ALV_GRID .

ALV Column Coloring:

For coloring the entire ALV column, set the field EMPHASIZE to a color coding as part of field
catalog.

ALV Row Coloring:

Procedure:

Step1:

Take an additional column in the final internal table which is of type char4.

Step 2:

Before displaying the final data in the ALV grid, loop the final internal table and set the color
coding for the additional field based on the condition.

As part of layout generation, set the field info_fname whose value is name of the
additional field which holds the row color coding.

ALV Cell Coloring:

Procedure:

Step1:

Take an additional column in the final internal table which is of type LVC_T_SCOL .

Step 2:

Before displaying the final data in the ALV grid, loop the final internal table and set the color
coding for the additional field based on the condition.
For this, we need to prepare work area of type LVC_S_SCOL and append the same to the
additional field and update the internal table.

As part of layout generation, set the field ctab_fname whose value is name of the
additional field which holds the cell color coding.

Splitter control

It is used for splitting the container in to N no of partitions.

Each partition is called as a PANE .

Each PANE should be associated with a container to hold an object. The object can be ALV
Grid, Image and Tree.

Procedure for displaying images in ALV Reporting using classes

Step 1:

Upload the picture by using t-code SMW0 .

In SMW0, choose the radio button binary data for webrfc applications , click on FIND
(appl.toolbar)  provide package name(any package), object name (any name, unique id)
description … , click on execute  click on create button (appl.toolbar),provide object name
ZBT , description … , click on import button (status bar of dialog box)

Step 2:

Call the function module dp_publish_www_url .

This function module takes an image object id as input and returns the URL of picture which is
of type cndp_url .

Note:

cndp_url is a types declaration declared in the type group CNDP .

Step 3: Create the object of picture class CL_GUI_PICTURE linking with a container.

Step 4: call the instance method load_picture_from_url of the class cl_gui_picture . This
method takes URL of the picture as input and displays the picture in the container.

PROCEDURE FOR TREE CONTROL:

- A tree control is collection of nodes.

- A node can be a folder / it can be an action item.

- We can add the nodes to the tree control by using the instance method add_nodes of
the class cl_gui_simple_tree .
- This method contains two mandatory parameters.

1. Structure representing the nodes.

2. Internal table containing the nodes information.

Note: ABDEMONODE is one of the standard structure given by SAP which represents simple
tree (or) we can create custom dictionary structure by including std.structure TREEV_NODE
and a character field text of any length

Displaying ALV columns as Dropdown:

Generally we display ALV column as drop down when we have fixed set of values to be shown
to the user as a drop down so that the user can select the value in the runtime.

Procedure:

Step 1:

Take an additional column in the final internal table, this additional column needs to be
displayed as dropdown.

Step 2:

Generate the field catalog for the additional column.

As part of the field catalog, set the field DRDN_HNDL to some Numeric value and also set
the edit field to X as the column should be editable, so that user can choose value from the
drop down in the runtime.

Step 3:

Prepare an internal table of type LVC_T_DROP with drop down handle and dropdown
values and pass this internal table as a parameter to the method
SET_DROP_DOWN_TABLE of the class CL_GUI_ALV_GRID .

ALV Traffic Light columns:

- Traffic light acts as indicators in the ALV reports.

- These traffic lights by default are displayed as First column of the ALV report.

- Traffic light codes are 3 types (1-Red, 2-Yellow, 3-Green) and also we can refer to the
constant values in the ICON type-group.

Procedure:

Step 1:

Take an additional column in the final internal table which is of type character of One .
Step 2:

Before displaying the final data, loop the internal table and set the traffic light code for an
additional column.

Step 3:

As part of layout, set the field EXCP_FNAME the value of the field should be Name of the
additional column containing traffic light code.

Note: By default, Traffic light column is displayed in first column position. To display traffic
light in a specific column position, declare an additional column of type character with some
length, generate field catalog for this column including required column position and assign
traffic light code to its column value. In this case, we should not set the field EXCP_FNAME
in layout.

Custom event handling process:

1. Needs to be declared in custom class definition


2. Event Business logic needs to be implemented as part of custom class
implementation(inside event handler method)

3. Raised in custom class methods


4. Register the handlers for execution of event handler methods
Standard Event handling process in ALV Reports using classes:

1. They are declared by SAP itself as part of standard SAP classes

2. Event Business logic needs to implemented as part of custom class implementation (inside
event handler method)

3. Raised by SAP itself depending on user actions (from. The std. methods)

4. Register the handlers for execution of event handler methods

Note:

1. To Display ALV column values as link, we need to set the field HOTSPOT as part of field
catalog for that particular field.

2. HOTSPOT_CLICK is the instance event of the class CL_GUI_ALV_GRID which is


triggered by SAP whenever the user clicks on ALV Cell value in the runtime.

3. BUTTON_CLICK is the instance event of the class CL_GUI_ALV_GRID which is triggered


by SAP whenever the user clicks on ALV Cell displayed as pushbutton
4. DOUBLE_CLICK is the instance event of the class CL_GUI_ALV_GRID which is triggered
by SAP whenever the user double clicks on ALV Cell value in the runtime.

5. As part of interactive ALV reporting using classes, when the user interacts and navigates
from one screen to another screen, we need to refresh the grid with the corresponding
internal table data using the method REFRESH_TABLE_DISPLAY of the class
CL_GUI_ALV_GRID .

TOOLBAR Event: is the instance event of the class CL_GUI_ALV_GRID which is triggered when
the ALV grid is displayed. This event can be used to manage the ALV Toolbar for
Enabling/Disabling standard ALV Toolbar buttons, Adding custom buttons.

USER_COMMAND event: is the instance event of the class CL_GUI_ALV_GRID which is


triggered when the user clicks on custom normal buttons on ALV toolbar. Before this event, SAP
Triggers BEFORE_USER_COMMAND and then USER_COMMAND and after this it triggers
AFTER_USER_COMMAND . These events are also triggered when the user clicks on Menu
items of Menu Buttons of ALV toolbar.

MENU_BUTTON event: is the instance event of the class CL_GUI_ALV_GRID which is triggered
when the user clicks on custom MENU buttons on ALV toolbar.

Note:

1. To enable multiple selection of rows on ALV grid, we need to set the field SEL_MODE
TO A as part of layout

2. To identify the selected rows on the ALV grid, we need to use the instance method
GET_SELECTED_ROWS of the class CL_GUI_ALV_GRID . This method returns the
internal tables containing the indexes of selected rows.

Editing ALV Cells in runtime and updating to database:

Procedure:

1. For the ALV column to be editable, set the field edit to X As part of field catalog,
2. Handle the event DATA_CHANGED of the class CL_GUI_ALV_GRID . This event is not
triggered by default as it is a system event, it requires explicit registration and it is done
by calling the instance method REGISTER_EDIT_EVENT of the class
CL_GUI_ALV_GRID . This method takes event id as a mandatory input parameter.
These event ids exist in the form of constant attributes of the grid class and we can use
any of the following attribute event ids.
a) Mc_evt_modified  Allows only single cell editing, in this case the event
DATA_CHANGED is triggered when the user shifts the focus from the first modified
cell or when the user presses enter key in the first modified cell.
b) Mc_evt_enter -> Allows multi cell editing, in this case the event is triggered when
the user presses enter key in the last modified cell.
3. As part of the event handler method, we need to import the event parameter
MC_EVT_MODIFIED and using this event parameter (object) access the instance
attribute (internal table) MT_MODIFIED_CELLS which keeps track about the
information of the modified cells which includes row_id and modified value. Based on
this, update the grid internal table as well as corresponding database table.

Tree Control Events:

1. NODE_DOUBLE_CLICK : is the instance event of the class CL_GUI_SIMPLE_TREE


which is triggered when the user double clicks on the tree node of the tree control.
This event is not triggered by default; it needs to be registered explicitly by using the
instance method SET_REGISTERED_EVENTS of the class CL_GUI_SIMPLE_TREE .

2. NODE_CONTEXT_MENU_REQUEST : is the instance event of the class


CL_GUI_SIMPLE_TREE which is triggered when the user right clicks on the tree
node of the tree control. This event can be handled to associate the context menu
with the tree node. This event is not triggered by default; it needs to be registered
explicitly by using the instance method SET_REGISTERED_EVENTS of the class
CL_GUI_SIMPLE_TREE .

3. NODE_KEYPRESS : is the instance event of the class CL_GUI_SIMPLE_TREE which


is triggered when the user presses a key on the tree node of the tree control. For
this, we need to register the keys for triggering this event. The keys can be
registered by calling the method ADD_KEY_STROKE of the class
CL_GUI_SIMPLE_TREE . All the keys exist in the form of constant attributes with the
naming standard KEY_.... of the class CL_GUI_SIMPLE_TREE . This event is not
triggered by default; it needs to be registered explicitly by using the instance
method SET_REGISTERED_EVENTS of the class CL_GUI_SIMPLE_TREE .

4. NODE_CONTEXT_MENU_SELECT : is the instance event of the class


CL_GUI_SIMPLE_TREE which is triggered when the user selects a context menu
item from the context menu of the node.

Note: For the method SET_REGISTERED_EVENTS , we need to pass event id as a


parameter. All the event ids exist in the form of constant attributes with the naming
standard EVENTID_..... of the class CL_GUI_SIMPLE_TREE .

Generating TOP OF PAGE content for ALV Grid:

For this, we need to handle the event TOP_OF_PAGE . It is the instance event of the class
CL_GUI_ALV_GRID used for generating content in the TOP OF PAGE area of ALV Grid. This
event is not triggered by default; it should be registered explicitly by calling the instance
method LIST_PROCESSING_EVENTS of the class CL_GUI_ALV_GRID .

Displaying ALV cells as pushbutton:

Procedure:
Step1:

Take an additional column in the final internal table which is of table type LVC_T_STYL .

Step 2:

Before displaying the final data in the ALV grid, loop the final internal table and set the
button style (MC_STYLE_BUTTON) to ALV cells based on the condition.

As part of layout generation, set the field style_fname whose value is name of the
additional field which holds the style.

ALV Link

Example: ALV Reporting Using Classes – ABORT Error – Field Catalog Not Found

report z730alv1.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.


data : o_cont type ref to cl_gui_custom_container,
o_grid type ref to cl_gui_alv_grid.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link ALV grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if t_vbak is not initial.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales orders' type 'I'.
endif.
endmodule. " STATUS_0100 OUTPUT
module user_command_0100 input.
case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT
form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call method o_grid->set_table_for_first_display
changing
it_outtab = t_vbak.
endform. " DISPLAYSALESORDERS

flowlogic:
process before output.
module status_0100.
*
process after input.
module user_command_0100.

Screen Painter:

Menu Painter
Example: Generating Field Catalog referring to parameter I_STRUCTURE_NAME of the
method SET_TABLE_FOR_FIRST_DISPLAY

report z730alv2.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link ALV grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if t_vbak is not initial.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales orders' type 'I'.
endif.
endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
i_structure_name = 'ZCVBAK'
changing
it_outtab = t_vbak.
endform. " DISPLAYSALESORDERS

Example: Generating Field Catalog using function module LVC_FIELDCATALOG_MERGE

report z730alv3.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

data : t_fcat type lvc_t_fcat.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link ALV grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if t_vbak is not initial.
* generate field catalog for sales orders fields
perform fldcatsalesorders.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales orders' type 'I'.
endif.
endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call method o_grid->set_table_for_first_display
changing
it_outtab = t_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
call function 'LVC_FIELDCATALOG_MERGE'
exporting
i_structure_name = 'ZCVBAK'
changing
ct_fieldcat = t_fcat.
endform. " FLDCATSALESORDERS

Example: Generating Field Catalog manually, Column Coloring, Column Styling, Excluding
Standard ALV Toolbar buttons / Toolbar, Layout settings

report z730alv4.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

data : t_fcat type lvc_t_fcat,


wa_fcat type lvc_s_fcat.

data : t_functions type ui_functions,


wa_function type ui_func.

data wa_layo type lvc_s_layo.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link ALV grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if t_vbak is not initial.
* generate field catalog for sales orders fields
perform fldcatsalesorders.
* exclude standard alv toolbar buttons
perform excludebuttons.
* layout
perform layout.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales orders' type 'I'.
endif.
endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
it_toolbar_excluding = t_functions
changing
it_outtab = t_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
clear wa_fcat.
* wa_fcat-fieldname = 'vbeln'. "runtime error in ecc 6.0
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 15.
wa_fcat-tooltip = 'Sales Document Number'.
wa_fcat-emphasize = 'C310'. "column coloring
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 40.
wa_fcat-style = cl_gui_alv_grid=>mc_style_button.
append wa_fcat to t_fcat.

endform. " FLDCATSALESORDERS

form excludebuttons .
clear wa_function.
wa_function = cl_gui_alv_grid=>mc_fc_find.
append wa_function to t_functions.

clear wa_function.
wa_function = cl_gui_alv_grid=>mc_fc_print.
append wa_function to t_functions.

endform. " EXCLUDEBUTTONS

form layout .
clear wa_layo.
wa_layo-zebra = 'X'. "alternate line coloring (striped pattern)
wa_layo-grid_title = 'SALES DOCUMENTS'.
* wa_layo-no_toolbar = 'X'. "excludes entire ALV Toolbar
endform. " LAYOUT

Example: ALV Row Coloring and ALV Cell Coloring in OOPS ALV

report z730alv5.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '5020'.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

types : begin of ty_vbak.


include type zcvbak.
types : netwr type vbak-netwr,
end of ty_vbak.

data : lt_vbak type table of ty_vbak,


ls_vbak type ty_vbak.

types : begin of t_vbak.


include type zcvbak.
types : rowcolor(4) type c,
cellcolor type lvc_t_scol,
netwr type vbak-netwr,
end of t_vbak.

data : gt_vbak type table of t_vbak,


gs_vbak type t_vbak.

field-symbols <abc> like line of gt_vbak.

data wa_scol type lvc_s_scol.

data wa_layo type lvc_s_layo.

data : t_fcat type lvc_t_fcat,


wa_fcat like line of t_fcat.

start-of-selection.

call screen 100.


module status_0100 output.
set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link alv grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if gt_vbak is not initial.
* generate field catalog
perform fldcat.
* row coloring
perform rowcoloring.
* cell coloring
perform cellcoloring.
* layout
perform layout.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam netwr
from vbak
into table lt_vbak
where vbeln in so_vbeln.
if sy-subrc eq 0.
* append lines of lt_vbak to gt_vbak. "syntax error
loop at lt_vbak into ls_vbak.
clear gs_vbak.
gs_vbak-vbeln = ls_vbak-vbeln.
gs_vbak-erdat = ls_vbak-erdat.
gs_vbak-erzet = ls_vbak-erzet.
gs_vbak-ernam = ls_vbak-ernam.
gs_vbak-netwr = ls_vbak-netwr.
append gs_vbak to gt_vbak.
endloop.
endif.
endform. " GETSALESORDERS

form fldcat .
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 30.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 5.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

endform. " FLDCAT

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = gt_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form rowcoloring .
loop at gt_vbak assigning <abc>.
if <abc>-erdat = '19970121'.
<abc>-rowcolor = 'C110'.
elseif <abc>-erdat = '19970122'.
<abc>-rowcolor = 'C310'.
elseif <abc>-erdat = '19970123'.
<abc>-rowcolor = 'C710'.
elseif <abc>-erdat = '19970124'.
<abc>-rowcolor = 'C510'.
else.
<abc>-rowcolor = 'C610'.
endif.
endloop.
endform. " ROWCOLORING

form layout .
clear wa_layo.
wa_layo-info_fname = 'ROWCOLOR'. "row coloring
wa_layo-ctab_fname = 'CELLCOLOR'. "cell coloring
endform. " LAYOUT

form cellcoloring .
loop at gt_vbak assigning <abc>.
if <abc>-netwr < 10000.
clear wa_scol.
wa_scol-fname = 'VBELN'.
wa_scol-color-col = 3.
wa_scol-color-int = 1.
wa_scol-color-inv = 0.
append wa_scol to <abc>-cellcolor.
elseif <abc>-netwr >= 10000 and <abc>-netwr <= 15000.
clear wa_scol.
wa_scol-fname = 'VBELN'.
wa_scol-color-col = 7.
wa_scol-color-int = 1.
wa_scol-color-inv = 0.
append wa_scol to <abc>-cellcolor.
elseif <abc>-netwr > 15000 and <abc>-netwr <= 20000.
clear wa_scol.
wa_scol-fname = 'VBELN'.
wa_scol-color-col = 1.
wa_scol-color-int = 1.
wa_scol-color-inv = 0.
append wa_scol to <abc>-cellcolor.
else.
clear wa_scol.
wa_scol-fname = 'VBELN'.
wa_scol-color-col = 5.
wa_scol-color-int = 1.
wa_scol-color-inv = 0.
append wa_scol to <abc>-cellcolor.
endif.
endloop.
endform. " CELLCOLORING

Tree Control
Summary of Splitter, Tree, picture

splitter container link

Example: Splitter Control, Tree Control, Picture Control

report z730alv6.

data : cust_cont type ref to cl_gui_custom_container,


o_split type ref to cl_gui_splitter_container,
o_tree type ref to cl_gui_simple_tree,
o_pic type ref to cl_gui_picture,
o_cont1 type ref to cl_gui_container,
o_cont2 type ref to cl_gui_container.

types : begin of ty_nodes.


include type ztreestr.
types end of ty_nodes.

data : t_nodes type table of ty_nodes,


wa_nodes like line of t_nodes.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.

* link custom control with custom container


create object cust_cont
exporting
container_name = 'CST'.

* link splitter container with custom container


create object o_split
exporting
parent = cust_cont
rows =1
columns = 2.

* Associate widths for each columns


call method o_split->set_column_width
exporting
id =1
width = 10.

call method o_split->set_column_width


exporting
id =2
width = 7.

* Associate containers for each pane


call method o_split->get_container
exporting
row =1
column = 1
receiving
container = o_cont1.

call method o_split->get_container


exporting
row =1
column = 2
receiving
container = o_cont2.

* tree construction
perform tree_construction.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form tree_construction .

* link tree control with corresponding container (o_cont1)


create object o_tree
exporting
parent = o_cont1
node_selection_mode = cl_gui_simple_tree=>node_sel_mode_single.

* prepare nodes
perform preparenodes.

* display nodes
perform displaynodes.
endform. " TREE_CONSTRUCTION

form preparenodes .
clear wa_nodes.
wa_nodes-node_key = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Transactions'.
append wa_nodes to t_nodes.
clear wa_nodes.
wa_nodes-node_key = 'SO'.
wa_nodes-relatkey = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Create Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CHSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Change Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'DSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Display Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'PO'.
wa_nodes-relatkey = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Create Purchase Order'.
append wa_nodes to t_nodes.
clear wa_nodes.
wa_nodes-node_key = 'CHPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Change Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'DPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Display Purchase Order'.
append wa_nodes to t_nodes.

endform. " PREPARENODES

form displaynodes .
call method o_tree->add_nodes
exporting
table_structure_name = 'ZTREESTR'
node_table = t_nodes.
endform. " DISPLAYNODES

Flowlogic:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen 100 (Normal Screen):

On the layout, Place custom control and name it as CST (any name).
Splitter Control, Tree control and Picture Control

splitter within splitter-exercise

Example: Splitter Control, Tree Control, Picture Control

report z730alv7.

data : cust_cont type ref to cl_gui_custom_container,


o_split type ref to cl_gui_splitter_container,
o_tree type ref to cl_gui_simple_tree,
o_pic type ref to cl_gui_picture,
o_cont1 type ref to cl_gui_container,
o_cont2 type ref to cl_gui_container.

types : begin of ty_nodes.


include type ztreestr.
types end of ty_nodes.

data : t_nodes type table of ty_nodes,


wa_nodes like line of t_nodes.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.

* link custom control with custom container


create object cust_cont
exporting
container_name = 'CST'.

* link splitter container with custom container


create object o_split
exporting
parent = cust_cont
rows =1
columns = 2.

* Associate widths for each columns


call method o_split->set_column_width
exporting
id =1
width = 10.

call method o_split->set_column_width


exporting
id =2
width = 7.

* Associate containers for each pane


call method o_split->get_container
exporting
row =1
column = 1
receiving
container = o_cont1.
call method o_split->get_container
exporting
row =1
column = 2
receiving
container = o_cont2.

* tree construction
perform tree_construction.

* PICTURE
perform picture.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form tree_construction .

* link tree control with corresponding container (o_cont1)


create object o_tree
exporting
parent = o_cont1
node_selection_mode = cl_gui_simple_tree=>node_sel_mode_single.

* prepare nodes
perform preparenodes.

* display nodes
perform displaynodes.
endform. " TREE_CONSTRUCTION

form preparenodes .
clear wa_nodes.
wa_nodes-node_key = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Transactions'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'SO'.
wa_nodes-relatkey = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Create Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CHSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Change Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'DSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Display Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'PO'.
wa_nodes-relatkey = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Create Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CHPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Change Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'DPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Display Purchase Order'.
append wa_nodes to t_nodes.

endform. " PREPARENODES

form displaynodes .
call method o_tree->add_nodes
exporting
table_structure_name = 'ZTREESTR'
node_table = t_nodes.
endform. " DISPLAYNODES

form picture .
* link container (o_cont2) with picture control
create object o_pic
exporting
parent = o_cont2.

* get the URL of the image Object ID


data pic_url type cndp_url.
call function 'DP_PUBLISH_WWW_URL'
exporting
objid = 'Z730TIGER1'
lifetime = cndp_lifetime_transaction
importing
url = pic_url.

* display the picture in the container


call method o_pic->load_picture_from_url
exporting
url = pic_url.
call method o_pic->set_display_mode
exporting
display_mode = cl_gui_picture=>display_mode_normal_center.

endform. " PICTURE

Flowlogic:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen 100 (Normal Screen):

On the layout, Place custom control and name it as CST (any name).

Example: ALV Traffic Light Column (First Column Position)

report z730alv8.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '5020'.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

types : begin of ty_vbak.


include type zcvbak.
types : netwr type vbak-netwr,
lights type c,
end of ty_vbak.

data : lt_vbak type table of ty_vbak,


ls_vbak type ty_vbak.

field-symbols <abc> like line of lt_vbak.

data wa_layo type lvc_s_layo.

data : t_fcat type lvc_t_fcat,


wa_fcat like line of t_fcat.

start-of-selection.
call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link alv grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if lt_vbak is not initial.
* generate field catalog
perform fldcat.
* traffic lights
perform traffic_lights.
* layout
perform layout.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam netwr
from vbak
into table lt_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS
form fldcat .
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 20.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'LIGHTS'.
wa_fcat-col_pos = 5.
wa_fcat-coltext = 'Status'.
wa_fcat-outputlen = 10.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 6.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

endform. " FLDCAT


form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = lt_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form layout .
clear wa_layo.
wa_layo-excp_fname = 'LIGHTS'.
endform. " LAYOUT

form traffic_lights .
loop at lt_vbak assigning <abc>.
if <abc>-netwr < 10000.
<abc>-lights = '1'. "red color
elseif <abc>-netwr >= 10000 and <abc>-netwr <= 30000.
<abc>-lights = '2'. "yellow color
else.
<abc>-lights = '3'. "green color
endif.
endloop.
endform. " TRAFFIC_LIGHTS

Flowlogic:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Example: ALV Traffic Light Column (Specific Column Position)

report z730alv9.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '5020'.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.
types : begin of ty_vbak.
include type zcvbak.
types : netwr type vbak-netwr,
lights(20) type c,
end of ty_vbak.

data : lt_vbak type table of ty_vbak,


ls_vbak type ty_vbak.

field-symbols <abc> like line of lt_vbak.

data wa_layo type lvc_s_layo.

data : t_fcat type lvc_t_fcat,


wa_fcat like line of t_fcat.

start-of-selection.
call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link alv grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if lt_vbak is not initial.
* generate field catalog
perform fldcat.
* traffic lights
perform traffic_lights.
* layout
perform layout.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.
endmodule. " STATUS_0100 OUTPUT
module user_command_0100 input.
case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam netwr
from vbak
into table lt_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form fldcat .
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 20.
append wa_fcat to t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'LIGHTS'.
wa_fcat-col_pos = 5.
wa_fcat-coltext = 'Status'.
wa_fcat-outputlen = 10.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 6.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.
endform. " FLDCAT

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = lt_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form layout .
clear wa_layo.
endform. " LAYOUT

form traffic_lights .
loop at lt_vbak assigning <abc>.
if <abc>-netwr < 10000.
<abc>-lights = '@08@'. "red color
concatenate <abc>-lights 'Red' into <abc>-lights separated by space.
elseif <abc>-netwr >= 10000 and <abc>-netwr <= 30000.
<abc>-lights = '@09@'. "yellow color
concatenate <abc>-lights 'Yellow' into <abc>-lights separated by space.
else.
<abc>-lights = '@0A@'. "green color
concatenate <abc>-lights 'Green' into <abc>-lights separated by space.
endif.
endloop.
endform. " TRAFFIC_LIGHTS

Flowlogic:
process before output.
module status_0100.
*
process after input.
module user_command_0100.

Example: ALV Drop Down Column

report z730alv10.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '5020'.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

types : begin of ty_vbak.


include type zcvbak.
types : netwr type vbak-netwr,
currkey(3) type c,
end of ty_vbak.

data : lt_vbak type table of ty_vbak,


ls_vbak type ty_vbak.

field-symbols <abc> like line of lt_vbak.

data wa_layo type lvc_s_layo.

data : t_fcat type lvc_t_fcat,


wa_fcat like line of t_fcat.

start-of-selection.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link alv grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if lt_vbak is not initial.
* generate field catalog
perform fldcat.
* dropdown column
perform dropdown.
* layout
perform layout.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam netwr
from vbak
into table lt_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form fldcat .
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 5.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'CURRKEY'.
wa_fcat-col_pos = 6.
wa_fcat-coltext = 'Currency'.
wa_fcat-outputlen = 10.
wa_fcat-drdn_hndl = 1.
wa_fcat-edit = 'X'.
append wa_fcat to t_fcat.

endform. " FLDCAT

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = lt_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form layout .
clear wa_layo.
endform. " LAYOUT

form dropdown .
data : t_drop type lvc_t_drop,
wa_drop type lvc_s_drop.

clear wa_drop.
wa_drop-handle = 1.
wa_drop-value = 'INR'.
append wa_drop to t_drop.

clear wa_drop.
wa_drop-handle = 1.
wa_drop-value = 'USD'.
append wa_drop to t_drop.

clear wa_drop.
wa_drop-handle = 1.
wa_drop-value = 'GBP'.
append wa_drop to t_drop.

call method o_grid->set_drop_down_table


exporting
it_drop_down = t_drop.
endform. " DROPDOWN

Flowlogic:

process before output.


module status_0100.
*
process after input.
module user_command_0100.
Standard Event handling process in ALV Reports using classes:

1. They are declared by SAP itself as part of standard SAP classes

2. Event Business logic needs to implemented as part of custom class implementation (inside
event handler method)

3. They are raised by SAP itself depending on user actions (from the standard methods)

4. Register the handlers for execution of event handler methods

TOOLBAR Event: is the instance event of the class ͚CL_GUI_ALV_GRID͛ which is triggered when
the ALV grid is displayed. This event can be used to manage the ALV Toolbar for
Enabling/Disabling standard ALV Toolbar buttons, Adding custom buttons.

MENU_BUTTON event: is the instance event of the class ͚CL_GUI_ALV_GRID͛ which is triggered
when the user clicks on custom MENU buttons on ALV toolbar.

USER_COMMAND event: is the instance event of the class ͚CL_GUI_ALV_GRID͛ which is


triggered when the user clicks on custom normal buttons on ALV toolbar. Before this event, SAP
Triggers BEFORE_USER_COMMAND and then ͚USER_COMMAND͛ and after this it triggers
AFTER_USER_COMMAND . These events are also triggered when the user clicks on Menu
items of Menu Buttons of ALV toolbar.

Note:

1. To enable multiple selection of rows on ALV grid, we need to set the field SEL_MODE
TO ͚A͛ as part of layout

2. To identify the selected rows on the ALV grid, we need to use the instance method
GET_SELECTED_ROWS of the class ͚CL_GUI_ALV_GRID͛. This method returns the
internal tables containing the indexes of selected rows.

Tree Control Events:

1. NODE_DOUBLE_CLICK : is the instance event of the class ͚CL_GUI_SIMPLE_TREE͛


which is triggered when the user double clicks on the tree node of the tree control.
This event is not triggered by default; it needs to be registered explicitly by using the
instance method ͚SET_REGISTERED_EVENTS͛ of the class ͚CL_GUI_SIMPLE_TREE͛.

2. NODE_CONTEXT_MENU_REQUEST : is the instance event of the class


͚CL_GUI_SIMPLE_TREE͛ which is triggered when the user right clicks on the tree
node of the tree control. This event can be handled to associate the context menu
with the tree node. This event is not triggered by default; it needs to be registered
explicitly by using the instance method ͚SET_REGISTERED_EVENTS͛ of the class
͚CL_GUI_SIMPLE_TREE͛.
3. NODE_KEYPRESS : is the instance event of the class ͚CL_GUI_SIMPLE_TREE͛ which
is triggered when the user presses a key on the tree node of the tree control. For
this, we need to register the keys for triggering this event. The keys can be
registered by calling the method ADD_KEY_STROKE of the class
͚CL_GUI_SIMPLE_TREE͛. All the keys exist in the form of constant attributes with the
naming standard ͚KEY_....͛ of the class ͚CL_GUI_SIMPLE_TREE͛. This event is not
triggered by default; it needs to be registered explicitly by using the instance
method ͚SET_REGISTERED_EVENTS͛ of the class ͚CL_GUI_SIMPLE_TREE͛.

4. NODE_CONTEXT_MENU_SELECT : is the instance event of the class


͚CL_GUI_SIMPLE_TREE͛ which is triggered when the user selects a context menu
item from the context menu of the node.

Note: For the method ͚SET_REGISTERED_EVENTS͛, we need to pass event id as a


parameter. All the event ids exist in the form of constant attributes with the naming
standard ͚EVENTID_.....͛ of the class ͚CL_GUI_SIMPLE_TREE͛.

Editing ALV Cells in runtime and updating to database:

Procedure:

1. For the ALV column to be editable, set the field edit to ͚X͛ As part of field catalog,
2. Handle the event ͚DATA_CHANGED of the class ͚CL_GUI_ALV_GRID͛. This event is not
triggered by default as it is a system event, it requires explicit registration and it is done
by calling the instance method REGISTER_EDIT_EVENT of the class
͚CL_GUI_ALV_GRID͛. This method takes event id as a mandatory input parameter.
These event ids exist in the form of constant attributes of the grid class and we can use
any of the following attribute event ids.
a) Mc_evt_modified  Allows only single cell editing, in this case the event
͚DATA_CHANGED͛ is triggered when the user shifts the focus from the first modified
cell or when the user presses enter key in the first modified cell.
b) Mc_evt_enter -> Allows multi cell editing, in this case the event is triggered when
the user presses enter key in the last modified cell.
3. As part of the event handler method, we need to import the event parameter
͚MC_EVT_MODIFIED͛ and using this event parameter (object) access the instance
attribute (internal table) ͚MT_MODIFIED_CELLS͛ which keeps track about the
information of the modified cells which includes row_id and modified value. Based on
this, update the grid internal table as well as corresponding database table.

Scheduling ALV Reports using classes in Background:

1. Identify the ALV Report which needs to be scheduled in background. If the report
execution contains selection screen, provide input values on selection screen and save
them as variant.

2. Define the background job (SM36)


1. Job name

2. Job classification (Job priority)

3. Start condition

4. Define Step (Program name, Variant name)

5. Save the job  Job gets released

Note: Once the job is released, job gets executed depending on the start condition.

Check the background job status (SM37)

Note: The background job execution status will be cancelled if the ALV report makes use of
custom control. The reason for this is the background processer cannot address the front-end
controls such as custom control. So we need to modify the ALV report accordingly to link the
ALV grid directly with docking container without using custom control. Docking container is
represented by the class ͚CL_GUI_DOCKING_CONTAINER͛.

Note:

1. To Display ALV column values as link, we need to set the field HOTSPOT as part of field
catalog for that particular field.

2. HOTSPOT_CLICK is the instance event of the class ͚CL_GUI_ALV_GRID͛ which is


triggered by SAP whenever the user clicks on ALV Cell value in the runtime.

3. BUTTON_CLICK is the instance event of the class ͚CL_GUI_ALV_GRID͛ which is triggered


by SAP whenever the user clicks on ALV Cell displayed as pushbutton

4. DOUBLE_CLICK is the instance event of the class ͚CL_GUI_ALV_GRID͛ which is triggered


by SAP whenever the user double clicks on ALV Cell value in the runtime.

5. As part of interactive ALV reporting using classes, when the user interacts and navigates
from one screen to another screen, we need to refresh the grid with the corresponding
internal table data using the method REFRESH_TABLE_DISPLAY of the class
͚CL_GUI_ALV_GRID͛.

Generating TOP OF PAGE content for ALV Grid:

For this, we need to handle the event ͚TOP_OF_PAGE͛. It is the instance event of the class
͚CL_GUI_ALV_GRID͛ used for generating content in the TOP OF PAGE area of ALV Grid. This
event is not triggered by default; it should be registered explicitly by calling the instance
method LIST_PROCESSING_EVENTS of the class ͚CL_GUI_ALV_GRID͛.

F4 Help (Standard & Custom)


To Associate Standard F4 help to an ALV column, we need to set the field ͚ref_table͛ and
͚ref_field͛ as part of field catalog. In this case, F4 help will be populated if the data element of
the ALV column is associated with Search Help. To associate custom f4 help to an ALV column,
we need to handle the event ͚ONF4͛ of the class ͚CL_GUI_ALV_GRID͛. This event requires
explicit registration, for this we need to call the instance method ͚REGISTER_F4_FOR_FIELDS͛
which takes internal table as parameter value. This internal table should contain the field
names for which custom f4 help needs to be populated, Apart from this, we should also set the
field ͚F4AVAILABL͛ to ͚X͛ as part of field catalog.

F1 Help (Standard & Custom)

To Associate Standard F1 help to an ALV column, we need to set the field ͚ref_table͛ and
͚ref_field͛ as part of field catalog. In this case, F1 help will be populated if the data element of
the ALV column is associated with documentation (field labels). To associate custom f1 help to
an ALV column, we need to handle the event ͚ONF1͛ of the class ͚CL_GUI_ALV_GRID͛.

difference between instance and static events

Example: Custom Event Handling – Scenario 1

report z730events1.

class lcl_abc definition.


public section.
events e1. "instance custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2. "instance normal method
endclass.
class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
raise event e1.
endmethod.

endclass.

start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

call method ob1->m2.

Notes related to Scenario 1:

In this the event handler method ͚M1͛ will not be executed as the handler is not registered.

Example: Custom Event Handling – Scenario 2

report z730events2.

class lcl_abc definition.


public section.
events e1. "instance custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2. "instance normal method
endclass.

class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
raise event e1.
endmethod.
endclass.

start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

call method ob1->m2.


set handler ob1->m1 for ob1.

Notes related to Scenario 2:

In this the event handler method ͚M1͛ will not be executed as the handler is registered after
raising the event.

Example: Custom Event Handling – Scenario 3

report z730events3.

class lcl_abc definition.


public section.
events e1. "instance custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2. "instance normal method
endclass.

class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
raise event e1.
endmethod.

endclass.

start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

data ob2 type ref to lcl_abc.


create object ob2.
set handler ob1->m1 for ob2.
call method ob1->m2.

Notes related to Scenario 3:

In this, the event handler method ͚M1͛ will not be executed as the wrong object is registered
(OB2), the actual object which is raising the event is ͚OB1͛.

Example: Custom Event Handling – Scenario 4

report z730events4.

class lcl_abc definition.


public section.
events e1. "instance custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2. "instance normal method
endclass.

class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
raise event e1.
endmethod.

endclass.

start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

data ob2 type ref to lcl_abc.


create object ob2.

* set handler ob1->m1 for ob2.


set handler ob1->m1 for ob1.
call method ob1->m2.
Notes related to Scenario 4:

In this, the event handler method ͚M1͛ will be executed as and when the event is raised in the
method m2 by the object OB1

Example: Custom Event Handling – Scenario 5

report z730events5.

class lcl_abc definition.


public section.
events e1. "instance custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2. "instance normal method
endclass.

class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
set handler me->m1 for me.
raise event e1.
endmethod.

endclass.

start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

data ob2 type ref to lcl_abc.


create object ob2.

*set handler ob1->m1 for ob1.


call method ob1->m2.

Notes related to Scenario 5:

In this, the event handler method ͚M1͛ will be executed as and when the event is raised in the
method m2 by the object OB1 (ME refers to current object in execution ob1 executing the
method ͚m2͛)
Example: Custom Event Handling – Scenario 6

report z730events6.

class lcl_abc definition.


public section.
events e1. "instance custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2, "instance normal method
m3 for event e1 of lcl_abc."instance event handler method
class-methods m4 for event e1 of lcl_abc. "static event handler method
endclass.

class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m3.
write :/ 'Inside instance event handler method m3'.
endmethod.

method m4.
write :/ 'Inside static event handler method m4'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
raise event e1.
endmethod.

endclass.

class lcl_pqr definition.


public section.
methods m5 for event e1 of lcl_abc.
endclass.

class lcl_pqr implementation.


method m5.
write :/ 'inside instance event handler method m5 of class lcl_pqr..'.
endmethod.
endclass.
start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

data ob2 type ref to lcl_pqr.


create object ob2.

* set handler ob1->m1 for ob1.


* set handler ob1->m3 for ob1. "(or)
set handler ob1->m3 for ob1.
set handler ob1->m1 for ob1.
* set handler ob1->m4 for ob1. "(or)
set handler lcl_abc=>m4 for ob1.
set handler ob2->m5 for ob1.

call method ob1->m2.

Notes related to Scenario 6:

A event can be associated with multiple event handler methods. These event handler methods
can be within the same class or across classes. If the event handler method is instance, the
handler must be object and if the event handler method is static, the handler can be either
object or class name. The sequence of execution of event handler methods depends on
sequence of handler registrations.

Example: For All instances

report z730events7.

class lcl_abc definition.


public section.
events e1. "instance custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2. "instance normal method
endclass.

class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
raise event e1.
endmethod.

endclass.

start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

data ob2 type ref to lcl_abc.


create object ob2.

data ob3 type ref to lcl_abc.


create object ob3.

*set handler ob1->m1 for ob1.


*set handler ob1->m1 for ob2.
*set handler ob1->m1 for ob3. "(or)

set handler ob1->m1 for all instances.

call method : ob1->m2,


ob2->m2,
ob3->m2.

Example: Static events

report z730events8.

class lcl_abc definition.


public section.
class-events e1. "static custom event
methods : m1 for event e1 of lcl_abc, "instance event handler method
m2. "instance normal method
endclass.

class lcl_abc implementation.

method m1.
write :/ 'Inside instance event handler method m1'.
endmethod.

method m2.
write :/ 'Inside instance normal method m2-about to raise event'.
raise event e1.
endmethod.

endclass.

start-of-selection.
data ob1 type ref to lcl_abc.
create object ob1.

data ob2 type ref to lcl_abc.


create object ob2.

data ob3 type ref to lcl_abc.


create object ob3.

set handler ob1->m1.

call method : ob1->m2,


ob2->m2,
ob3->m2.

Example: Events with Parameters (Local classes)

report z730events9.

class lcl_abc definition.


public section.
* events e1 EXPORTING value(e_kunnr) type kna1-kunnr OPTIONAL.
events e1 exporting value(e_kunnr) type kna1-kunnr.
methods : m1 for event e1 of lcl_abc importing e_kunnr,
m2 for event e1 of lcl_abc,
m3 importing i_kunnr type kna1-kunnr.
endclass.

class lcl_abc implementation.

method m1.
format color 3.
write :/ 'Inside event handler method m1, importing event parameter...'.
data : lv_name1 type kna1-name1,
lv_ort01 type kna1-ort01.
select single name1 ort01
from kna1
into (lv_name1,lv_ort01)
where kunnr = e_kunnr.
if sy-subrc eq 0.
write :/ 'Customer Name :',lv_name1,
/ 'Customer City :',lv_ort01.
else.
write :/ 'Customer Not found...'.
endif.
format color off.

endmethod.

method m2.
format color 7.
write :/ 'Inside event handler method m2, not importing event parameter...'.
format color off.
endmethod.

method m3.
format color 1.
write :/ 'Inside normal method m3, about to raise event...'.
* raise event e1. "syntax error as mandatory event parameter not exported

raise event e1
exporting
* e_kunnr = '0000001000'.
e_kunnr = i_kunnr.
endmethod.
endclass.

start-of-selection.
parameters p_kunnr type kna1-kunnr.

data ob type ref to lcl_abc.


create object ob.

set handler ob->m1 for ob.


set handler ob->m2 for ob.

call method ob->m3


exporting
i_kunnr = p_kunnr.

Example: Events with Parameters (Global classes)


Create a custom event E1 as part of Global class z730events

Declare parameter e_kunnr for the event e1

Declare 3 methods M1 , M2 , M3
Register Method M1 as event handler (select checkbox event handler for in detail view
button)

Declare event parameter E_kunnr for the event handler method M1


Register Method M2 as event handler (select checkbox event handler for in detail view
button)
Declare Importing parameter i_kunnr for normal method M3

Implementation of methods:

method m1.
format color 3.
write :/ 'Inside event handler method m1, importing event parameter...'.
data : lv_name1 type kna1-name1,
lv_ort01 type kna1-ort01.
select single name1 ort01
from kna1
into (lv_name1,lv_ort01)
where kunnr = e_kunnr.
if sy-subrc eq 0.
write :/ 'Customer Name :',lv_name1,
/ 'Customer City :',lv_ort01.
else.
write :/ 'Customer Not found...'.
endif.
format color off.

endmethod.

method m2.
format color 7.
write :/ 'Inside event handler method m2, not importing event parameter...'.
format color off.
endmethod.

method m3.
format color 1.
write :/ 'Inside normal method m3, about to raise event...'.
* raise event e1. "syntax error as mandatory event parameter not exported

raise event e1
exporting
* e_kunnr = '0000001000'.
e_kunnr = i_kunnr.

endmethod.

Save and activate the global class

Executable Program: For accessing above global class

report z730events10.

parameters p_kunnr type kna1-kunnr.

data ob type ref to z730events.


create object ob.

set handler ob->m1 for ob.


set handler ob->m2 for ob.

call method ob->m3


exporting
i_kunnr = p_kunnr.
alv tollbar buttons

Example: Managing Standard ALV Toolbar (Enabling / Disabling Std. ALV toolbar buttons,
Adding Custom Buttons on Std. ALV Toolbar)

report z730alv11.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '5020'.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

types : begin of ty_vbak.


include type zcvbak.
types : netwr type vbak-netwr,
end of ty_vbak.

data : lt_vbak type table of ty_vbak,


ls_vbak type ty_vbak.

field-symbols <abc> like line of lt_vbak.

data wa_layo type lvc_s_layo.


data : t_fcat type lvc_t_fcat,
wa_fcat like line of t_fcat.

class lcl_eventreceiver definition.


public section.
methods handle_toolbar for event toolbar
of cl_gui_alv_grid
importing e_object.
methods handle_menu_button for event menu_button
of cl_gui_alv_grid
importing e_object e_ucomm.
endclass.

class lcl_eventreceiver implementation.


method handle_toolbar.
* message 'Toolbar event triggered' type 'I'.
data wa_button type stb_button.
* logic for disabling std.alv toolbar buttons
loop at e_object->mt_toolbar into wa_button
where function = cl_gui_alv_grid=>mc_fc_find or
function = cl_gui_alv_grid=>mc_fc_print_back.
wa_button-disabled = 'X'.
modify e_object->mt_toolbar from wa_button
transporting function disabled.
endloop.

* logic for adding custom buttons


clear wa_button.
wa_button-function = 'FC1'.
wa_button-icon = '@15@'.
wa_button-quickinfo = 'Display Sales Items'.
wa_button-butn_type = 0. "normal button
wa_button-text = 'Sales Items'.
append wa_button to e_object->mt_toolbar.

clear wa_button.
wa_button-butn_type = 3. "Separator
append wa_button to e_object->mt_toolbar.

clear wa_button.
wa_button-function = 'FC2'.
wa_button-icon = '@08@'.
wa_button-quickinfo = 'Display Transactions'.
wa_button-butn_type = 2. "Menu button
wa_button-text = 'Transactions'.
append wa_button to e_object->mt_toolbar.

endmethod.

method handle_menu_button.
case e_ucomm.
when 'FC2'.
message 'Clicked on Custom Menu Button' type 'I'.
when others.
message 'Clicked on other than Custom Menu Button' type 'I'.
endcase.
endmethod.
endclass.

data k type ref to lcl_eventreceiver.

start-of-selection.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link alv grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if lt_vbak is not initial.
* generate field catalog
perform fldcat.
* layout
perform layout.
* register handlers
perform reghandlers.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam netwr
from vbak
into table lt_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form fldcat .
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 5.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

endform. " FLDCAT

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = lt_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form layout .
clear wa_layo.
endform. " LAYOUT

form reghandlers .
create object k.
set handler k->handle_toolbar for o_grid.
set handler k->handle_menu_button for o_grid.
endform. " REGHANDLERS

Flowlogic:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen 100 Layout:


Example: Managing Standard ALV Toolbar (Enabling / Disabling Std. ALV toolbar buttons,
Adding Custom Buttons on Std. ALV Toolbar, Associating menu items with menu button,
Handling events related to custom buttons)

report z730alv11.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '5020'.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid.

data : vbap_cont type ref to cl_gui_custom_container,


vbap_grid type ref to cl_gui_alv_grid.

types : begin of ty_vbak.


include type zcvbak.
types : netwr type vbak-netwr,
end of ty_vbak.

data : lt_vbak type table of ty_vbak,


ls_vbak type ty_vbak.

data : temp_vbak type table of ty_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data : lt_vbap type table of ty_vbap,


ls_vbap type ty_vbap.

field-symbols <abc> like line of lt_vbak.

data wa_layo type lvc_s_layo.

data : t_fcat type lvc_t_fcat,


wa_fcat like line of t_fcat.

data : lt_rows type lvc_t_row,


ls_rows type lvc_s_row.

class lcl_eventreceiver definition.


public section.
methods handle_toolbar for event toolbar
of cl_gui_alv_grid
importing e_object.
methods handle_menu_button for event menu_button
of cl_gui_alv_grid
importing e_object e_ucomm.
methods handle_user_command for event user_command
of cl_gui_alv_grid
importing e_ucomm.
endclass.

class lcl_eventreceiver implementation.


method handle_toolbar.
* message 'Toolbar event triggered' type 'I'.
data wa_button type stb_button.
* logic for disabling std.alv toolbar buttons
loop at e_object->mt_toolbar into wa_button
where function = cl_gui_alv_grid=>mc_fc_find or
function = cl_gui_alv_grid=>mc_fc_print_back.
wa_button-disabled = 'X'.
modify e_object->mt_toolbar from wa_button
transporting function disabled.
endloop.

* logic for adding custom buttons


clear wa_button.
wa_button-function = 'FC1'.
wa_button-icon = '@15@'.
wa_button-quickinfo = 'Display Sales Items'.
wa_button-butn_type = 0. "normal button
wa_button-text = 'Sales Items'.
append wa_button to e_object->mt_toolbar.

clear wa_button.
wa_button-butn_type = 3. "Separator
append wa_button to e_object->mt_toolbar.

clear wa_button.
wa_button-function = 'FC2'.
wa_button-icon = '@08@'.
wa_button-quickinfo = 'Display Transactions'.
wa_button-butn_type = 2. "Menu button
wa_button-text = 'Transactions'.
append wa_button to e_object->mt_toolbar.

endmethod.

method handle_menu_button.
case e_ucomm.
when 'FC2'.
* message 'Clicked on Custom Menu Button' type 'I'.
call method e_object->add_function
exporting
fcode = 'MI1'
text = 'Screen Painter'.

call method e_object->add_function


exporting
fcode = 'MI2'
text = 'FormPainter'.

* Add a separator
call method e_object->add_separator.

* create local menu object


data o_menu type ref to cl_ctmenu.
create object o_menu.

call method o_menu->add_function


exporting
fcode = 'MI3'
text = 'Create Sales Orders'.

call method o_menu->add_function


exporting
fcode = 'MI4'
text = 'Change Sales Orders'.

* Add the above local menu object to the imported menu object
call method e_object->add_menu
exporting
menu = o_menu.

clear o_menu.
create object o_menu.
call method o_menu->add_function
exporting
fcode = 'MI5'
text = 'Create Purchase Order'.

call method o_menu->add_function


exporting
fcode = 'MI6'
text = 'Change Purchase Order'.

* add the above local menu object as a submenu to imported menu object
call method e_object->add_submenu
exporting
menu = o_menu
text = 'Purchase Orders'.
when others.
message 'Clicked on other than Custom Menu Button' type 'I'.
endcase.
endmethod.

method handle_user_command.
case e_ucomm.
when 'FC1'.
* message 'Clicked on Normal button' type 'I'.
* identify the indexes of selected rows
refresh lt_rows.
call method o_grid->get_selected_rows
importing
et_index_rows = lt_rows.

if lt_rows is not initial.


refresh temp_vbak.
* get the selected sales document no's into temp.internal table
loop at lt_rows into ls_rows.
clear ls_vbak.
read table lt_vbak into ls_vbak index ls_rows-index.
if sy-subrc eq 0.
append ls_vbak to temp_vbak.
endif.
endloop.
if temp_vbak is not initial.
* get the sales items of selected sales documents
perform getsalesitems.
if lt_vbap is not initial.
call screen 200.
else.
message 'No Sales Items for selected sales orders' type 'I'.
endif.
endif.
else.
message 'Please select atleast one row' type 'I'.
endif.
when 'MI1'.
call transaction 'SE51'.
when 'MI2'.
call transaction 'SE41'.
when 'MI3'.
call transaction 'VA01'.
when 'MI4'.
call transaction 'VA02'.
when 'MI5'.
call transaction 'ME21'.
when 'MI6'.
call transaction 'ME22'.
endcase.
endmethod.
endclass.
data k type ref to lcl_eventreceiver.

start-of-selection.

call screen 100.

module status_0100 output.


set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link alv grid with custom container
create object o_grid
exporting
i_parent = o_cont.
* get sales orders
perform getsalesorders.
if lt_vbak is not initial.
* generate field catalog
perform fldcat.
* layout
perform layout.
* register handlers
perform reghandlers.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales Orders' type 'I'.
endif.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam netwr
from vbak
into table lt_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form fldcat .
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 5.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

endform. " FLDCAT

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = lt_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form layout .
clear wa_layo.
wa_layo-sel_mode = 'A'. "enables multiple row selection
endform. " LAYOUT

form reghandlers .
create object k.
set handler k->handle_toolbar for o_grid.
set handler k->handle_menu_button for o_grid.
set handler k->handle_user_command for o_grid.
endform. " REGHANDLERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table lt_vbap
for all entries in temp_vbak
where vbeln = temp_vbak-vbeln.
endform. " GETSALESITEMS

module status_0200 output.


set pf-status 'LMNG'.
* link custom container with custom control
create object vbap_cont
exporting
container_name = 'CST2'.
* link alv grid with custom container
create object vbap_grid
exporting
i_parent = vbap_cont.
* field catalog for sales items
perform fldcatvbap.
* display salesitems
perform displaysalesitems.

endmodule. " STATUS_0200 OUTPUT


form fldcatvbap .
refresh t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'POSNR'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Item No'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'MATNR'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Material No'.
wa_fcat-outputlen = 20.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Item Value'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

endform. " FLDCATVBAP

form displaysalesitems .
call method vbap_grid->set_table_for_first_display
changing
it_outtab = lt_vbap
it_fieldcatalog = t_fcat.

endform. " DISPLAYSALESITEMS

module user_command_0200 input.


case sy-ucomm.
when 'BACK'.
leave to screen 100.
endcase.
endmodule. " USER_COMMAND_0200 INPUT

Flowlogic of screen 100:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen 100 Layout:

Flowlogic of screen 200:

process before output.


module status_0200.
*
process after input.
module user_command_0200.

GUI Status of screen 200:


Screen layout of 200:
Example: TREE Control events

report z730alv12.

data : cust_cont type ref to cl_gui_custom_container,


o_split type ref to cl_gui_splitter_container,
o_tree type ref to cl_gui_simple_tree,
o_pic type ref to cl_gui_picture,
o_cont1 type ref to cl_gui_container,
o_cont2 type ref to cl_gui_container.

types : begin of ty_nodes.


include type ztreestr.
types end of ty_nodes.

data : t_nodes type table of ty_nodes,


wa_nodes like line of t_nodes.

class lcl_eventreceiver definition.


public section.
methods handle_node_context_menu_req
for event node_context_menu_request
of cl_gui_simple_tree
importing node_key menu.
methods handle_node_context_menu_sel
for event node_context_menu_select
of cl_gui_simple_tree
importing node_key fcode.
methods handle_node_double_click
for event node_double_click
of cl_gui_simple_tree
importing node_key.
endclass.

class lcl_eventreceiver implementation.


method handle_node_context_menu_req.
* message 'NODE_CONTEXT_MENU_REQUEST event' type 'I'.
case node_key.
when 'SO'.
call method menu->add_function
exporting
fcode = 'MI1'
text = 'Create Sales Order'.

call method menu->add_function


exporting
fcode = 'MI2'
text = 'Change Sales Order'.

call method menu->add_function


exporting
fcode = 'MI3'
text = 'Display Sales Order'.
when 'PO'.
call method menu->add_function
exporting
fcode = 'MI4'
text = 'Create Purchase Order'.

call method menu->add_function


exporting
fcode = 'MI5'
text = 'Change Purchase Order'.

call method menu->add_function


exporting
fcode = 'MI6'
text = 'Display Purchase Order'.
endcase.
endmethod.

method handle_node_context_menu_sel.
case node_key.
when 'SO'.
if fcode = 'MI1'.
call transaction 'VA01'.
elseif fcode = 'MI2'.
call transaction 'VA02'.
elseif fcode = 'MI3'.
call transaction 'VA03'.
endif.
when 'PO'.
if fcode = 'MI4'.
call transaction 'ME21'.
elseif fcode = 'MI5'.
call transaction 'ME22'.
elseif fcode = 'MI6'.
call transaction 'ME23'.
endif.
endcase.
endmethod.

method handle_node_double_click.
case node_key.
when 'CSO'.
call transaction 'VA01'.
when 'CHSO'.
call transaction 'VA02'.
when 'DSO'.
call transaction 'VA03'.
when 'CPO'.
call transaction 'ME21'.
when 'CHPO'.
call transaction 'ME22'.
when 'DPO'.
call transaction 'ME23'.
endcase.
endmethod.
endclass.

data ob type ref to lcl_eventreceiver.

start-of-selection.
call screen 100.

module status_0100 output.


set pf-status 'ABC'.

* link custom control with custom container


create object cust_cont
exporting
container_name = 'CST'.

* link splitter container with custom container


create object o_split
exporting
parent = cust_cont
rows =1
columns = 2.
* Associate widths for each columns
call method o_split->set_column_width
exporting
id =1
width = 10.

call method o_split->set_column_width


exporting
id =2
width = 7.

* Associate containers for each pane


call method o_split->get_container
exporting
row =1
column = 1
receiving
container = o_cont1.

call method o_split->get_container


exporting
row =1
column = 2
receiving
container = o_cont2.

* tree construction
perform tree_construction.

* PICTURE
perform picture.

endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form tree_construction .

* link tree control with corresponding container (o_cont1)


create object o_tree
exporting
parent = o_cont1
node_selection_mode = cl_gui_simple_tree=>node_sel_mode_single.

* prepare nodes
perform preparenodes.

* register handlers for event handler methods of tree control


perform reghandlers.

* display nodes
perform displaynodes.
endform. " TREE_CONSTRUCTION

form preparenodes .
clear wa_nodes.
wa_nodes-node_key = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Transactions'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'SO'.
wa_nodes-relatkey = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Create Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CHSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Change Sales Order'.
append wa_nodes to t_nodes.
clear wa_nodes.
wa_nodes-node_key = 'DSO'.
wa_nodes-relatkey = 'SO'.
wa_nodes-n_image = '@15@'.
wa_nodes-text = 'Display Sales Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'PO'.
wa_nodes-relatkey = 'RT'.
wa_nodes-isfolder = 'X'.
wa_nodes-expander = 'X'.
wa_nodes-text = 'Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Create Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'CHPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Change Purchase Order'.
append wa_nodes to t_nodes.

clear wa_nodes.
wa_nodes-node_key = 'DPO'.
wa_nodes-relatkey = 'PO'.
wa_nodes-n_image = '@16@'.
wa_nodes-text = 'Display Purchase Order'.
append wa_nodes to t_nodes.

endform. " PREPARENODES

form displaynodes .
call method o_tree->add_nodes
exporting
table_structure_name = 'ZTREESTR'
node_table = t_nodes.
endform. " DISPLAYNODES

form picture .
* link container (o_cont2) with picture control
create object o_pic
exporting
parent = o_cont2.

* get the URL of the image Object ID


data pic_url type cndp_url.
call function 'DP_PUBLISH_WWW_URL'
exporting
objid = 'Z730TIGER1'
lifetime = cndp_lifetime_transaction
importing
url = pic_url.

* display the picture in the container


call method o_pic->load_picture_from_url
exporting
url = pic_url.

call method o_pic->set_display_mode


exporting
display_mode = cl_gui_picture=>display_mode_normal_center.

endform. " PICTURE

form reghandlers .
create object ob.
set handler ob->handle_node_context_menu_req for o_tree.
set handler ob->handle_node_context_menu_sel for o_tree.
set handler ob->handle_node_double_click for o_tree.

data : t_events type cntl_simple_events,


wa_events like line of t_events.

* register the event node_context_menu_request explicitly


clear wa_events.
wa_events-eventid = cl_gui_simple_tree=>eventid_node_context_menu_req.
append wa_events to t_events.
* register the event node_double_click explicitly
clear wa_events.
wa_events-eventid = cl_gui_simple_tree=>eventid_node_double_click.
append wa_events to t_events.

call method o_tree->set_registered_events


exporting
events = t_events.

endform. " REGHANDLERS

Flowlogic:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen Layout:

ALV Grid events:- ---> cl_gui_alv_grid


toolbar, menu_button, user_command

TREE events:- --> cl_gui_simple_tree

event method

node_context_menu_request ---> explicit registration --> set_registered_events

node_context_menu_select --> No explicit registration

node_double_click - - -> explicit registration ---> set_registered_events

ALV CEll editing in runtime

Example: Editing ALV Cells values in runtime and updating to database

Consider a db table ZEMP with some test data


Executable program:

REPORT Z730ALV13.

data : cust_cont type ref to cl_gui_custom_container,


emp_grid type ref to cl_gui_alv_grid.

types : begin of ty_emp.


include type zemp.
types end of ty_emp.

data : t_emp type table of ty_emp,


wa_emp type ty_emp.

data : t_fcat type lvc_t_fcat,


wa_fcat type lvc_s_fcat.

class lcl_eventreceiver DEFINITION.


public SECTION.
methods handle_data_changed
for event data_changed
of cl_gui_alv_grid
importing ER_DATA_CHANGED.
endclass.

class lcl_eventreceiver IMPLEMENTATION.


method handle_data_changed.
* message 'Data changed' type 'I'.
data wa_modi type lvc_s_modi.
loop at er_data_changed->mt_mod_cells into wa_modi.
clear wa_emp.
read table t_emp into wa_emp
index wa_modi-row_id
TRANSPORTING empno ename.
if sy-subrc eq 0.
wa_emp-ename = wa_modi-value. "updates work area
modify t_emp from wa_emp index wa_modi-
row_id TRANSPORTING empno ename. "updates internal table
endif.
endloop.
modify zemp from table t_emp. "updates db table
endmethod.
endclass.

data ob type ref to lcl_eventreceiver.

START-OF-SELECTION.
call screen 100.

MODULE STATUS_0100 OUTPUT.


SET PF-STATUS 'ABC'.
* link custom container with custom control
CREATE OBJECT CUST_CONT
EXPORTING
CONTAINER_NAME = 'CST'.

* link alv grid with custom container


CREATE OBJECT EMP_GRID
EXPORTING
I_PARENT = cust_cont.

* get employee data


perform getemp.
if t_emp is not INITIAL.
* fieldcatalog
perform fldcatemp.
* register handlers
perform reghandlers.
* display
perform displayemp.
endif.
ENDMODULE. " STATUS_0100 OUTPUT

MODULE USER_COMMAND_0100 INPUT.


case sy-ucomm.
when 'BACK'.
leave PROGRAM.
endcase.
ENDMODULE. " USER_COMMAND_0100 INPUT

FORM GETEMP .
select * from zemp
into table t_emp.
ENDFORM. " GETEMP

FORM FLDCATEMP .
clear wa_fcat.
wa_fcat-fieldname = 'EMPNO'.
wa_fcat-coltext = 'Employee No'.
wa_fcat-col_pos = 1.
wa_fcat-outputlen = 10.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ENAME'.
wa_fcat-coltext = 'Employee Name'.
wa_fcat-col_pos = 2.
wa_fcat-outputlen = 25.
wa_fcat-edit = 'X'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'EMPDESIG'.
wa_fcat-coltext = 'Designation'.
wa_fcat-col_pos = 3.
wa_fcat-outputlen = 20.
append wa_fcat to t_fcat.

ENDFORM. " FLDCATEMP

FORM DISPLAYEMP .
CALL METHOD EMP_GRID->SET_TABLE_FOR_FIRST_DISPLAY
CHANGING
IT_OUTTAB = t_emp
IT_FIELDCATALOG = t_fcat.

ENDFORM. " DISPLAYEMP

FORM REGHANDLERS .
create object ob.
set handler ob->handle_data_changed for emp_grid.
* register the event data_changed explicitly
CALL METHOD EMP_GRID->REGISTER_EDIT_EVENT
EXPORTING
* I_EVENT_ID = cl_gui_alv_grid=>mc_evt_modified. "single cell modification
I_EVENT_ID = cl_gui_alv_grid=>mc_evt_enter. "triggers only when enter key is pressed
ENDFORM. " REGHANDLERS

Flowlogic:

PROCESS BEFORE OUTPUT.


MODULE STATUS_0100.
*
PROCESS AFTER INPUT.
MODULE USER_COMMAND_0100.

Screen Layout 100:


alv report in background
Example: Scheduling ALV Reports in background

report z730alv14.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data t_vbak type table of ty_vbak.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid,
o_dock type ref to cl_gui_docking_container.

data : t_fcat type lvc_t_fcat,


wa_fcat type lvc_s_fcat.

data wa_layo type lvc_s_layo.

data gv_mode type i.

call screen 100.

module status_0100 output.


* check whether report is in foreground or background execution
gv_mode = cl_gui_alv_grid=>offline( ).
if gv_mode eq 0. "foreground execution
set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link ALV grid with custom container
create object o_grid
exporting
i_parent = o_cont.
else. "background execution
* link alv grid with docking container reference
create object o_grid
exporting
i_parent = o_dock.
endif.

* get sales orders


perform getsalesorders.
if t_vbak is not initial.
* generate field catalog for sales orders fields
perform fldcatsalesorders.
* layout
perform layout.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales orders' type 'I'.
endif.
endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = t_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
clear wa_fcat.
* wa_fcat-fieldname = 'vbeln'. "runtime error in ecc 6.0
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 15.
wa_fcat-tooltip = 'Sales Document Number'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 40.
append wa_fcat to t_fcat.

endform. " FLDCATSALESORDERS

form layout .
clear wa_layo.
wa_layo-zebra = 'X'. "alternate line coloring (striped pattern)
wa_layo-grid_title = 'SALES DOCUMENTS'.
endform. " LAYOUT

Example: Interactive ALV Reporting using classes

report z730alv15.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.
types : begin of ty_vbak.
include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak type ty_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.

data : t_vbap type table of ty_vbap,


wa_vbap type ty_vbap.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid,
o_dock type ref to cl_gui_docking_container.

data : vbap_cont type ref to cl_gui_custom_container,


vbap_grid type ref to cl_gui_alv_grid.

data : t_fcat type lvc_t_fcat,


wa_fcat type lvc_s_fcat.

data wa_layo type lvc_s_layo.

data gv_mode type i.

class lcl_eventreceiver definition.


public section.
methods handle_double_click
for event double_click
of cl_gui_alv_grid
importing e_row e_column.
endclass.

class lcl_eventreceiver implementation.


method handle_double_click.
case e_column-fieldname.
when 'VBELN'.
* message 'double click on Sales Document ' type 'I'.
clear wa_vbak.
read table t_vbak into wa_vbak
index e_row-index
transporting vbeln.
if sy-subrc eq 0.
* get sales items
perform getsalesitems.
if t_vbap is not initial.
call screen 200.
else.
message 'No Sales items for selected sales documnent' type 'I'.
endif.
endif.
when others.
message 'Please double click on Sales Document only' type 'I'.
endcase.
endmethod.
endclass.

data ob type ref to lcl_eventreceiver.

start-of-selection.
call screen 100.

module status_0100 output.


* check whether report is in foreground or background execution
gv_mode = cl_gui_alv_grid=>offline( ).
if gv_mode eq 0. "foreground execution
set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link ALV grid with custom container
create object o_grid
exporting
i_parent = o_cont.
else. "background execution
* link alv grid with docking container reference
create object o_grid
exporting
i_parent = o_dock.
endif.

* get sales orders


perform getsalesorders.
if t_vbak is not initial.
* generate field catalog for sales orders fields
perform fldcatsalesorders.
* layout
perform layout.
* handlers
perform reghandlers.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales orders' type 'I'.
endif.
endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = t_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
clear wa_fcat.
* wa_fcat-fieldname = 'vbeln'. "runtime error in ecc 6.0
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 15.
wa_fcat-tooltip = 'Sales Document Number'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 40.
append wa_fcat to t_fcat.

endform. " FLDCATSALESORDERS

form layout .
clear wa_layo.
wa_layo-zebra = 'X'. "alternate line coloring (striped pattern)
wa_layo-grid_title = 'SALES DOCUMENTS'.
endform. " LAYOUT

form reghandlers .
create object ob.
set handler ob->handle_double_click for o_grid.
endform. " REGHANDLERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
where vbeln = wa_vbak-vbeln.
endform. " GETSALESITEMS

form fldcatvbap .
refresh t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 15.
wa_fcat-tooltip = 'Sales Document Number'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'POSNR'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Item No'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'MATNR'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Material No'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 10.
append wa_fcat to t_fcat.
endform. " FLDCATVBAP

module status_0200 output.


if vbap_cont is initial.
set pf-status 'MNR'.
* link custom container with custom control
create object vbap_cont
exporting
container_name = 'CST2'.

* link alv grid with custom container


create object vbap_grid
exporting
i_parent = vbap_cont.

* fieldcatalog for sales items fields


perform fldcatvbap.

* display sales items


perform displaysalesitems.
else.
* refresh alv grid
call method vbap_grid->refresh_table_display.
endif.
endmodule. " STATUS_0200 OUTPUT

module user_command_0200 input.


case sy-ucomm.
when 'BACK'.
leave to screen 100.
endcase.
endmodule. " USER_COMMAND_0200 INPUT

form displaysalesitems .
call method vbap_grid->set_table_for_first_display
changing
it_outtab = t_vbap
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESITEMS

Flowlogic of screen 100:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen Layout 100:


Flowlogic of screen 200:

process before output.


module status_0200.
*
process after input.
module user_command_0200.

Screen layout of 200:


checkbox events in abap

container allocations for splitter panes

splitter within Splitter - checkbox, top of page


Example: Interactive ALV Reporting using classes (Complete Program) (Events: double_click,
button_click, hotspot_click)

report z730alv16.

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4985'.

types : begin of ty_vbak.


include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


wa_vbak type ty_vbak.

types : begin of ty_temp_vbap.


include type zcvbap.
types end of ty_temp_vbap.

data : t_temp_vbap type table of ty_temp_vbap,


wa_temp_vbap type ty_temp_vbap.

types : begin of ty_vbap.


include type zcvbap.
types : cellstyles type lvc_t_styl,
end of ty_vbap.

data wa_styl type lvc_s_styl.

data : t_vbap type table of ty_vbap,


wa_vbap type ty_vbap.

types : begin of ty_marc,


matnr type marc-matnr,
werks type marc-werks,
ekgrp type marc-ekgrp,
end of ty_marc.

data : t_marc type table of ty_marc,


wa_marc type ty_marc.

data : o_cont type ref to cl_gui_custom_container,


o_grid type ref to cl_gui_alv_grid,
o_dock type ref to cl_gui_docking_container.

data : vbap_cont type ref to cl_gui_custom_container,


vbap_grid type ref to cl_gui_alv_grid.

data : marc_cont type ref to cl_gui_custom_container,


marc_grid type ref to cl_gui_alv_grid.

data : t_fcat type lvc_t_fcat,


wa_fcat type lvc_s_fcat.

data wa_layo type lvc_s_layo.

data gv_mode type i.


data gv_flag type i.

class lcl_eventreceiver definition.


public section.
methods handle_double_click
for event double_click
of cl_gui_alv_grid
importing e_row e_column.
methods handle_button_click
for event button_click
of cl_gui_alv_grid
importing es_row_no.
methods handle_hotspot_click
for event hotspot_click
of cl_gui_alv_grid
importing e_row_id.
endclass.

class lcl_eventreceiver implementation.


method handle_double_click.
case e_column-fieldname.
when 'VBELN'.
* message 'double click on Sales Document ' type 'I'.
clear wa_vbak.
read table t_vbak into wa_vbak
index e_row-index
transporting vbeln.
if sy-subrc eq 0.
* get sales items
perform getsalesitems.
if t_temp_vbap is not initial.
call screen 200.
else.
message 'No Sales items for selected sales documnent' type 'I'.
endif.
endif.
when others.
message 'Please double click on Sales Document only' type 'I'.
endcase.
endmethod.

method handle_button_click.
* message 'button click' type 'I'.
clear wa_vbap.
read table t_vbap into wa_vbap
index es_row_no-row_id transporting matnr.
if sy-subrc eq 0.
perform getmaterialplants.
if t_marc is not initial.
call screen 300.
else.
message 'No Plants for selected material' type 'I'.
endif.
endif.
endmethod.

method handle_hotspot_click.
* message 'hotspot_click event' type 'I'.
clear wa_marc.
read table t_marc into wa_marc
index e_row_id-index
transporting matnr.
if sy-subrc eq 0.
set parameter id 'MAT' field wa_marc-matnr.
call transaction 'MM03'.
endif.
endmethod.
endclass.

data ob type ref to lcl_eventreceiver.

start-of-selection.
call screen 100.
module status_0100 output.
if gv_flag = 0.
* check whether report is in foreground or background execution
gv_mode = cl_gui_alv_grid=>offline( ).
if gv_mode eq 0. "foreground execution
set pf-status 'ABC'.
* link custom container with custom control
create object o_cont
exporting
container_name = 'CST'.
* link ALV grid with custom container
create object o_grid
exporting
i_parent = o_cont.
else. "background execution
* link alv grid with docking container reference
create object o_grid
exporting
i_parent = o_dock.
endif.

* get sales orders


perform getsalesorders.
if t_vbak is not initial.
* generate field catalog for sales orders fields
perform fldcatsalesorders.
* layout
perform layout.
* handlers
perform reghandlers.
* display sales orders
perform displaysalesorders.
else.
message 'No Sales orders' type 'I'.
endif.
endif.
endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_vbak
where vbeln in so_vbeln.
endform. " GETSALESORDERS

form displaysalesorders .
call method o_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = t_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form fldcatsalesorders .
refresh t_fcat.
clear wa_fcat.
* wa_fcat-fieldname = 'vbeln'. "runtime error in ecc 6.0
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 15.
wa_fcat-tooltip = 'Sales Document Number'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Creation Date'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Creation Time'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Created By'.
wa_fcat-outputlen = 40.
append wa_fcat to t_fcat.
endform. " FLDCATSALESORDERS

form layout .
clear wa_layo.
wa_layo-zebra = 'X'. "alternate line coloring (striped pattern)
wa_layo-grid_title = 'SALES DOCUMENTS'.
endform. " LAYOUT

form reghandlers .
create object ob.
set handler ob->handle_double_click for o_grid.
endform. " REGHANDLERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_temp_vbap
where vbeln = wa_vbak-vbeln.
endform. " GETSALESITEMS

form fldcatvbap .
refresh t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Document'.
wa_fcat-outputlen = 15.
wa_fcat-tooltip = 'Sales Document Number'.
* wa_fcat-style = cl_gui_alv_grid=>mc_style_button. "will set for entire column
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'POSNR'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Item No'.
wa_fcat-outputlen = 12.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'MATNR'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Material No'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 10.
append wa_fcat to t_fcat.
endform. " FLDCATVBAP

module status_0200 output.


gv_flag = 1.
if vbap_cont is initial.
set pf-status 'MNR'.
* link custom container with custom control
create object vbap_cont
exporting
container_name = 'CST2'.

* link alv grid with custom container


create object vbap_grid
exporting
i_parent = vbap_cont.

* fieldcatalog for sales items fields


perform fldcatvbap.

* ALV Cells as pushbuttons


perform alvcellsbuttons.

* layout
perform layoutvbap.

* reg handlers
perform handlers_reg.

* display sales items


perform displaysalesitems.
else.
* ALV Cells as pushbuttons
perform alvcellsbuttons.

* refresh alv grid


call method vbap_grid->refresh_table_display.
endif.
endmodule. " STATUS_0200 OUTPUT

module user_command_0200 input.


case sy-ucomm.
when 'BACK'.
leave to screen 100.
endcase.
endmodule. " USER_COMMAND_0200 INPUT

form displaysalesitems .
call method vbap_grid->set_table_for_first_display
exporting
is_layout = wa_layo
changing
it_outtab = t_vbap
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESITEMS

form alvcellsbuttons.
refresh t_vbap.
loop at t_temp_vbap into wa_temp_vbap.
clear wa_vbap.
wa_vbap-vbeln = wa_temp_vbap-vbeln.
wa_vbap-posnr = wa_temp_vbap-posnr.
wa_vbap-matnr = wa_temp_vbap-matnr.
wa_vbap-netwr = wa_temp_vbap-netwr.
if wa_vbap-netwr >= 5000.
clear wa_styl.
wa_styl-fieldname = 'VBELN'.
wa_styl-style = cl_gui_alv_grid=>mc_style_button.
append wa_styl to wa_vbap-cellstyles.
endif.
append wa_vbap to t_vbap.
endloop.
endform. " ALVCELLSBUTTONS

form layoutvbap .
clear wa_layo.
wa_layo-stylefname = 'CELLSTYLES'.
endform. " LAYOUTVBAP

form handlers_reg .
create object ob.
set handler ob->handle_button_click for vbap_grid.
endform. " HANDLERS_REG

form getmaterialplants .
select matnr werks ekgrp from marc
into table t_marc
where matnr = wa_vbap-matnr.
endform. " GETMATERIALPLANTS

module status_0300 output.


gv_flag = 1.
if marc_cont is initial .
set pf-status 'TBD'.
* link custom container with alv grid
create object marc_cont
exporting
container_name = 'CST3'.
* link alv grid with custom container
create object marc_grid
exporting
i_parent = marc_cont.
* fieldcatalog for material plant fields
perform fldcatmarc.
* handler registration
perform reg_handlers.
* display material plants
perform displaymatplants.
else.
* refresh material plants grid
call method marc_grid->refresh_table_display.
endif.
endmodule. " STATUS_0300 OUTPUT

form fldcatmarc .
refresh t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'MATNR'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Material No'.
wa_fcat-outputlen = 15.
wa_fcat-hotspot = 'X'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'WERKS'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Material Plant'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'EKGRP'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Purchase Group'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

endform. " FLDCATMARC

form displaymatplants .
call method marc_grid->set_table_for_first_display
changing
it_outtab = t_marc
it_fieldcatalog = t_fcat.
endform. " DISPLAYMATPLANTS

module user_command_0300 input.


case sy-ucomm.
when 'BACK'.
leave to screen 200.
endcase.
endmodule. " USER_COMMAND_0300 INPUT

form reg_handlers .
create object ob.
set handler ob->handle_hotspot_click for marc_grid.
endform. " REG_HANDLERS

Flowlogic of screen 100:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen Layout 100:

Flowlogic of screen 200:

process before output.


module status_0200.
*
process after input.
module user_command_0200

Screen layout of 200:


Flowlogic of screen 300:

process before output.


module status_0300.
*
process after input.
module user_command_0300.

Screen Layout 300:


Example: Splitter Within Splitter, ALV Checkbox Column, Events: Top_of_page, data_changed

Executable Program:

report z730alv17.

include z730alv17_inc.

start-of-selection.
call screen 100.

Include Program:

data gv_vbeln type vbak-vbeln.


select-options so_vbeln for gv_vbeln default '4980' to '4990'.

data : o_split1 type ref to cl_gui_splitter_container,


o_split2 type ref to cl_gui_splitter_container,
vbak_grid type ref to cl_gui_alv_grid,
vbap_grid type ref to cl_gui_alv_grid,
cust_cont type ref to cl_gui_custom_container,
o_cont type ref to cl_gui_container,
top_cont type ref to cl_gui_container,
vbak_cont type ref to cl_gui_container,
vbap_cont type ref to cl_gui_container.

types : begin of ty_temp_vbak.


include type zcvbak.
types end of ty_temp_vbak.

data : t_temp_vbak type table of ty_temp_vbak,


wa_temp_vbak type ty_temp_vbak.

types : begin of ty_vbak,


sel type c.
include type zcvbak.
types end of ty_vbak.

data : t_vbak type table of ty_vbak,


lt_vbak type table of ty_vbak,
wa_vbak type ty_vbak.

types : begin of ty_vbap.


include type zcvbap.
types end of ty_vbap.
data : t_vbap type table of ty_vbap,
wa_vbap type ty_vbap.

data : t_fcat type lvc_t_fcat,


wa_fcat type lvc_s_fcat.

data wa_layo type lvc_s_layo.

class lcl_eventreceiver definition.


public section.
methods handle_data_changed
for event data_changed of cl_gui_alv_grid
importing er_data_changed.
methods handle_top_of_page
for event top_of_page of cl_gui_alv_grid
importing e_dyndoc_id.
endclass.

class lcl_eventreceiver implementation .


method handle_data_changed.
* message 'checkbox selected / deselected' type 'I'.
data wa_modi type lvc_s_modi.
read table er_data_changed->mt_mod_cells into wa_modi
index 1.
if sy-subrc eq 0.
* identify content of selected/deselected row
clear wa_vbak.
read table t_vbak into wa_vbak
index wa_modi-row_id.
if sy-subrc eq 0.
if wa_modi-value = 'X'. "checkbox selected.
wa_vbak-sel = 'X'.
else.
wa_vbak-sel = space.
endif.
modify t_vbak from wa_vbak index wa_modi-row_id transporting sel.
endif.
endif.
endmethod.

method handle_top_of_page.
* message 'top' type 'I'.
call method e_dyndoc_id->add_text
exporting
text = 'Gensoft Technologies'.

call method e_dyndoc_id->add_gap


exporting
width = 5.

call method e_dyndoc_id->add_text


exporting
text = 'ABAP Cross-Applications'.

call method e_dyndoc_id->new_line


exporting
repeat = 1.

call method e_dyndoc_id->add_text


exporting
text = 'Start Date: 1st Aug 2017'.

call method e_dyndoc_id->add_gap


exporting
width = 5.

call method e_dyndoc_id->add_text


exporting
text = 'Timings: 7:30 am to 8:30 am'.

* associate top of page with corresponding container


call method e_dyndoc_id->display_document
exporting
parent = top_cont.
endmethod.
endclass.

data ob type ref to lcl_eventreceiver.

module status_0100 output.


if cust_cont is initial.
set pf-status 'ABC'.
set titlebar 'PQR'.
* link custom container with custom control
create object cust_cont
exporting
container_name = 'CST'.
* link splitter container 1 with custom container
create object o_split1
exporting
parent = cust_cont
rows =2
columns = 1.
* set the heights of the row
call method o_split1->set_row_height
exporting
id =1
height = 2.

call method o_split1->set_row_height


exporting
id =2
height = 9.
* associate the containers for each of the panes(2 rows)
call method o_split1->get_container
exporting
row =1
column = 1
receiving
container = top_cont.

call method o_split1->get_container


exporting
row =2
column = 1
receiving
container = o_cont.
* split o_cont further (2 columns,1 row)
create object o_split2
exporting
parent = o_cont
rows =1
columns = 2.
* set column widths for each panes(2 columns)
call method o_split2->set_column_width
exporting
id =1
width = 8.

call method o_split2->set_column_width


exporting
id =2
width = 5.

* associate the containers for each of the panes(2 columns)


call method o_split2->get_container
exporting
row =1
column = 1
receiving
container = vbak_cont.

call method o_split2->get_container


exporting
row =1
column = 2
receiving
container = vbap_cont.

* link vbak_grid with vbak_cont


create object vbak_grid
exporting
i_parent = vbak_cont.

* get default sales orders


perform getsalesorders.
if t_vbak is not initial.
* fieldcatalog for sales orders fields
perform fldcatvbak.
* register handlers
perform reghandlers.
* display sales orders
perform displaysalesorders.
endif.
endif.
endmodule. " STATUS_0100 OUTPUT

module user_command_0100 input.


case sy-ucomm.
when 'BACK'.
leave program.
when 'FC1'.
* transfer selected sales orders rows to temp.int table
refresh lt_vbak.
loop at t_vbak into wa_vbak where sel = 'X'.
append wa_vbak to lt_vbak.
endloop.
if lt_vbak is not initial.
* get sales items for selected sales orders
perform getsalesitems.
if t_vbap is not initial.
* generate field catalog for sales items fields
perform fldcatvbap.
* display/refresh sales items
perform displaysalesitems.
else.
message 'No sales items for selected sales orders' type 'I'.
endif.
endif.
endcase.
endmodule. " USER_COMMAND_0100 INPUT

form getsalesorders .
select vbeln erdat erzet ernam
from vbak
into table t_temp_vbak
where vbeln in so_vbeln.
if sy-subrc eq 0.
loop at t_temp_vbak into wa_temp_vbak.
clear wa_vbak.
wa_vbak-vbeln = wa_temp_vbak-vbeln.
wa_vbak-erdat = wa_temp_vbak-erdat.
wa_vbak-erzet = wa_temp_vbak-erzet.
wa_vbak-ernam = wa_temp_vbak-ernam.
append wa_vbak to t_vbak.
endloop.
endif.
endform. " GETSALESORDERS

form fldcatvbak .
refresh t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'SEL'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Select'.
wa_fcat-outputlen = 7.
wa_fcat-checkbox = 'X'.
wa_fcat-edit = 'X'.
append wa_fcat to t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Sales Doc'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERDAT'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Date'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERZET'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Time'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ERNAM'.
wa_fcat-col_pos = 5.
wa_fcat-coltext = 'Person'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.

endform. " FLDCATVBAK

form displaysalesorders .
call method vbak_grid->set_table_for_first_display
changing
it_outtab = t_vbak
it_fieldcatalog = t_fcat.
endform. " DISPLAYSALESORDERS

form reghandlers .
create object ob.
set handler ob->handle_data_changed for vbak_grid.

* register data_changed event explictly


call method vbak_grid->register_edit_event
exporting
i_event_id = cl_gui_alv_grid=>mc_evt_modified.
endform. " REGHANDLERS

form getsalesitems .
select vbeln posnr matnr netwr
from vbap
into table t_vbap
for all entries in lt_vbak
where vbeln = lt_vbak-vbeln.
endform. " GETSALESITEMS

form fldcatvbap .
refresh t_fcat.
clear wa_fcat.
wa_fcat-fieldname = 'VBELN'.
wa_fcat-col_pos = 1.
wa_fcat-coltext = 'Sales Doc'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'POSNR'.
wa_fcat-col_pos = 2.
wa_fcat-coltext = 'Item No'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'MATNR'.
wa_fcat-col_pos = 3.
wa_fcat-coltext = 'Material'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'NETWR'.
wa_fcat-col_pos = 4.
wa_fcat-coltext = 'Net Value'.
wa_fcat-outputlen = 15.
append wa_fcat to t_fcat.
endform. " FLDCATVBAP

form displaysalesitems .
if vbap_grid is initial.
* link vbap_grid with vbap_cont
create object vbap_grid
exporting
i_parent = vbap_cont.
* register handlers
perform reg_handlers.
* display sales items for first time
call method vbap_grid->set_table_for_first_display
changing
it_outtab = t_vbap
it_fieldcatalog = t_fcat.
else.
* refresh sales items grid
call method vbap_grid->refresh_table_display.
endif.
endform. " DISPLAYSALESITEMS

form reg_handlers .
create object ob.
set handler ob->handle_top_of_page for vbap_grid.

* register top_of_page event explictly


data k type ref to cl_dd_document.
create object k.

call method vbap_grid->list_processing_events


exporting
i_event_name = 'TOP_OF_PAGE'
i_dyndoc_id = k.

endform. " REG_HANDLERS

Flowlogic of screen 100:

process before output.


module status_0100.
*
process after input.
module user_command_0100.

Screen Layout 100:


FCTCODE of Sales Items button is FC1

Example: F4 Help (Standard & Custom), F1 Help (Standard & Custom) for ALV Columns

REPORT Z730ALV18.

data : cust_cont type ref to cl_gui_custom_container,


emp_grid type ref to cl_gui_alv_grid.

types : begin of ty_emp.


include type zemp.
types end of ty_emp.

data : t_emp type table of ty_emp,


wa_emp type ty_emp.

data : t_fcat type lvc_t_fcat,


wa_fcat type lvc_s_fcat.

types : begin of ty_f4values,


empno type zemp-empno,
ename type zemp-ename,
end of ty_f4values.
data : t_f4values type table of ty_f4values,
wa_f4values type ty_f4values.

class lcl_eventreceiver DEFINITION.


public SECTION.
methods handle_onf4
for event onf4
of cl_gui_alv_grid
importing e_fieldname e_fieldvalue
es_row_no er_event_data.
methods handle_onf1
for event onf1
of cl_gui_alv_grid
importing e_fieldname er_event_data.

endclass.

class lcl_eventreceiver IMPLEMENTATION.


method handle_onf4.
data : lt_retval type table of DDSHRETVAL,
ls_retval like line of lt_retval.

case e_fieldname.
when 'EMPNO'.
message 'custom f4 help for empno' type 'I'.
* suppress std.f4 help for empno(if available)
er_event_data->m_event_handled = 'X'.
when 'ENAME'.
* message 'custom f4 help for ename' type 'I'.
* suppress std.f4 help for ename(if available)
er_event_data->m_event_handled = 'X'.
* logic for populating custom f4 values
select empno ename
from zemp
into table t_f4values.
if sy-subrc eq 0.
* populate custom f4 values
CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
EXPORTING
RETFIELD = 'ENAME' "int.table field name
DYNPPROG = sy-repid
DYNPNR = sy-dynnr
DYNPROFIELD = 'ENAME' "ALV column name
VALUE_ORG = 'S'
TABLES
VALUE_TAB = t_f4values
RETURN_TAB = lt_retval.

if lt_retval is not INITIAL.


* read the selected value
read table lt_retval into ls_retval index 1.
if sy-subrc eq 0.
clear wa_emp.
read table t_emp into wa_emp
index es_row_no-row_id.
if sy-subrc eq 0.
wa_emp-ename = ls_retval-fieldval.
modify t_emp from wa_emp
index es_row_no-row_id
TRANSPORTING ename.
CALL METHOD EMP_GRID->REFRESH_TABLE_DISPLAY.
endif.
endif.
endif.
endif.
endcase.
endmethod.

method handle_onf1.
case e_fieldname.
when 'EMPDESIG'.
* suppress standard f1 help
er_event_data->m_event_handled = 'X'.
* logic for associating custom f1 help
CALL FUNCTION 'POPUP_TO_INFORM'
EXPORTING
TITEL = 'Custom F1 Help'
TXT1 = 'Employee Designation'
TXT2 = 'Table:ZEMP, Fieldname: EMPDESIG'.
endcase.
endmethod.
endclass.

data ob type ref to lcl_eventreceiver.

START-OF-SELECTION.
call screen 100.
MODULE STATUS_0100 OUTPUT.
SET PF-STATUS 'ABC'.
* link custom container with custom control
CREATE OBJECT CUST_CONT
EXPORTING
CONTAINER_NAME = 'CST'.

* link alv grid with custom container


CREATE OBJECT EMP_GRID
EXPORTING
I_PARENT = cust_cont.

* get employee data


perform getemp.
if t_emp is not INITIAL.
* fieldcatalog
perform fldcatemp.
* reg handlers
perform reghandlers.
* display
perform displayemp.
endif.
ENDMODULE. " STATUS_0100 OUTPUT

MODULE USER_COMMAND_0100 INPUT.


case sy-ucomm.
when 'BACK'.
leave PROGRAM.
endcase.
ENDMODULE. " USER_COMMAND_0100 INPUT

FORM GETEMP .
select * from zemp
into table t_emp.
ENDFORM. " GETEMP

FORM FLDCATEMP .
clear wa_fcat.
wa_fcat-fieldname = 'EMPNO'.
wa_fcat-coltext = 'Employee No'.
wa_fcat-col_pos = 1.
wa_fcat-outputlen = 10.
wa_fcat-ref_table = 'ZEMP'.
wa_fcat-ref_field = 'EMPNO'.
wa_fcat-f4availabl = 'X'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'ENAME'.
wa_fcat-coltext = 'Employee Name'.
wa_fcat-col_pos = 2.
wa_fcat-outputlen = 25.
wa_fcat-ref_table = 'ZEMP'.
wa_fcat-ref_field = 'ENAME'.
wa_fcat-f4availabl = 'X'.
append wa_fcat to t_fcat.

clear wa_fcat.
wa_fcat-fieldname = 'EMPDESIG'.
wa_fcat-coltext = 'Designation'.
wa_fcat-col_pos = 3.
wa_fcat-outputlen = 20.
append wa_fcat to t_fcat.

ENDFORM. " FLDCATEMP

FORM DISPLAYEMP .
CALL METHOD EMP_GRID->SET_TABLE_FOR_FIRST_DISPLAY
CHANGING
IT_OUTTAB = t_emp
IT_FIELDCATALOG = t_fcat.

ENDFORM. " DISPLAYEMP

FORM REGHANDLERS .
create object ob.
set handler ob->handle_onf4 for emp_grid.
set handler ob->handle_onf1 for emp_grid.

* register onf4 event explictly


data : lt_f4 type lvc_t_f4,
ls_f4 type lvc_s_f4.

clear ls_f4.
ls_f4-fieldname = 'EMPNO'.
ls_f4-register = 'X'.
insert ls_f4 into table lt_f4.
clear ls_f4.
ls_f4-fieldname = 'ENAME'.
ls_f4-register = 'X'.
insert ls_f4 into table lt_f4.

CALL METHOD EMP_GRID->REGISTER_F4_FOR_FIELDS


EXPORTING
IT_F4 = lt_f4.
ENDFORM. " REGHANDLERS
ALV Object Model Notes:

Introduction:

The CL_SALV_TABLE class is part of the ALV Object Model which was introduced in Net Weaver
2004. Basically it is an encapsulation of the pre-existing ALV tools. For example the class
CL_SALV_TABLE actually wraps around the CL_GUI_ALV_GRID class for container
implementation, as well as the REUSE_ALV_GRID_DISPLAY and REUSE_ALV_LIST_DISPLAY
function modules for full screen display.

It was designed to be a single point of entry when using a specific ALV tool such as the ALV
table display, ALV hierarchical sequential list, and tree ALV. All of these individual ALV tools
have their own base class, for table it is the CL_SALV_TABLE, but all have a common look. A lot
of the methods are the same, with only some differences in the parameters of the methods
depending on the actual tool you are using.

Following are the general classes used in ALV Object Model:

Basis Class for Simple Tables: CL_SALV_TABLE

Basis Class for Hierarchical-Sequential Tables: CL_SALV_HIERSEQ_TABLE

Basis Class for Tree Structure: CL_SALV_TREE

So to summarize, the ALV Object Model was delivered to give a more collective interface to the
ALV tools. There are limitations in the ALV Object Model, for example, you can NOT color a line
or a cell, but you can color a column. Also, you can NOT have an editable ALV using the Object
Model.

But for basic lists, it is a very powerful tool.

Following are the restrictions with CL_SALV_TABLE (ALV Object Model):-

The number of columns is restricted to 90.

The output length of a column is restricted to 128 characters.

For sorting and subtotals, you use a total of nine levels or columns.

For columns that can be aggregated, note that the internal length of the column is large
enough for both single values and the result.

The output is column-oriented. You are only able to display flat, structured tables. You are not
able to display nested tables.
Tables displayed with ALV are not ready for input.

If you insert the table as grid in container, you are not able to use batch mode (background)

MVC Requirement

MVC Design Pattern Layout

Design Pattern: is a set of rules using which the code can be implemented.
Design Patterns in ABAP Objects:

1. Singleton Design Pattern ---> implementation  Singleton class --> Example:


Persistence service (actor class is a singleton class)

2. MVC Design Pattern - --> In this, we need to separate the business logic with presentation
logic

MVC --> Model view controller

Model ---> responsible for fetching the data

View ---> responsible for generating the content to the user (output)

Controller --> acts as a interface (mediator) between model and view

3. Factory Design Pattern - ---> hides the complexity of instantiating the objects

4. FACADE Design Pattern

5. Observer Design Pattern

MVC (Model View Controller) Design pattern: The aim of MVC design pattern is to separate
the business logic and presentation logic, so that in future, changes can be made to business
logic and presentation logic without having much dependency.

Requirement: Develop an interface using MVC Design pattern to display the sales orders data
in the selected format.

Create Model class: z730model

Attribute tab:
Note: ͚ZTVBAK͛ is table type associated with dictionary structure ͚ZCVBAK͛ with the fields vbeln,
erdat, erzet, ernam
Method tab:

Parameters for method ͚getsalesorders͛:


Note: In the above method signature ͚ZSTRERDAT͛ is a custom dictionary structure copied from
standard dictionary structure ͚RSDSSELOPT͛

After copying the standard dictionary structure ͚RSDSSELOPT͛ to the custom dictionary
structure ͚ZSTRERDAT͛, replace the data elements of low and high fields to ͚ERDAT͛.
Implementation for method ͚getsalesorders͛:

method getsalesorders.
select vbeln erdat erzet ernam
from vbak
into table gt_vbak
where erdat between i_erdat-low and i_erdat-high.
endmethod.

Save and activate the model class

Create Controller class: z730controller

Attribute Tab:

Method tab:
Implementation for method ͚createmodelobject͛ :

method createmodelobject.
create object o_model.
endmethod.

Save and activate the controller class

SMARTFORM Creation: (one of the view generated based on user selection)

T-code: SMARTFORMS
Save and activate the smartform  Generates function module dynamically

Report Program (Generates Appropriate View based on User Selection)

report z730view.

data v_erdat type vbak-erdat.


select-options so_erdat for v_erdat default '19970103' to '19970203' no-extension.

parameters : p_r1 radiobutton group grp1 user-command fc1,


p_r2 radiobutton group grp1,
p_r3 radiobutton group grp1,
p_r4 radiobutton group grp1 default 'X'.

data o_ctrl type ref to z730controller.

initialization.
create object o_ctrl.

at selection-screen on radiobutton group grp1.


case sy-ucomm.
when 'FC1'.
if p_r1 = 'X'.
perform getmodelobject.
perform getdata.
perform displayalvreport.
elseif p_r2 = 'X'.
perform getmodelobject.
perform getdata.
perform displayclassicalreport.
elseif p_r3 = 'X'.
perform getmodelobject.
perform getdata.
perform displaysmartform.
endif.
endcase.

form getmodelobject .
call method o_ctrl->createmodelobject.
endform. " GETMODELOBJECT

form getdata .
call method o_ctrl->o_model->getsalesorders
exporting
i_erdat = so_erdat.

endform. " GETDATA

form displayalvreport .
data o_alv type ref to cl_salv_table.
try.
call method cl_salv_table=>factory "uses factory design pattern
importing
r_salv_table = o_alv
changing
t_table = o_ctrl->o_model->gt_vbak.

catch cx_salv_msg .
message 'Exception in creating ALV object' type 'I'.
endtry.

if o_alv is not initial.


call method o_alv->display.
endif.
endform. " DISPLAYALVREPORT

form displayclassicalreport .
data wa_vbak type zcvbak.
leave to list-processing.
format color 3.
loop at o_ctrl->o_model->gt_vbak into wa_vbak.
write :/ wa_vbak-vbeln,
wa_vbak-erdat,
wa_vbak-erzet,
wa_vbak-ernam.
endloop.
format color off.
endform. " DISPLAYCLASSICALREPORT

form displaysmartform .
* get the smartform function module name
data lv_fname type rs38l_fnam.
call function 'SSF_FUNCTION_MODULE_NAME'
exporting
formname = 'Z730SFORM'
importing
fm_name = lv_fname.

* call the smartform


call function lv_fname
exporting
t_vbak = o_ctrl->o_model->gt_vbak.
endform. " DISPLAYSMARTFORM

Selection-Screen selection texts:

In the program, choose goto menu  text elements  selection texts (construct appropriate
text)
CROSS-APPLICATIONS

RFC:

BAPI
ALE AND IDOCS

ENHANCEMENTS

Lsmw
RFC

RFC communication

Example: Synchronous RFC

Steps in RFC Server (EHP7):

1. Create a Function group in SE80 to store the function modules Function Group
name  ZRFCGRP
2. Create a remote Function Module (SE37)
Source Code of Function Module:

FUNCTION ZGETCUSTOMER.
*types : begin of ty_kna1,
* name1 type kna1-name1,
* ort01 type kna1-ort01,
* end of ty_kna1.
*
*data wa_kna1 type ty_kna1.
*
*select single name1 ort01
* from kna1
* into wa_kna1
* where kunnr = i_kunnr.
*if sy-subrc eq 0.
* e_name1 = wa_kna1-name1.
* e_ort01 = wa_kna1-ort01.
*endif. "(or)
select single name1 ort01
from kna1
into (e_name1,e_ort01)
where kunnr = i_kunnr.
ENDFUNCTION.

Steps in RFC Client (EHP 5):

1. Create the RFC Destination (SM59)

Click on Create (toolbar)


Executable Program: To call Remote function in Synchronous Mode

REPORT ZCALLSRFC.

PARAMETERS p_kunnr type kna1-kunnr.

data : gv_name1 type kna1-name1,


gv_ort01 type kna1-ort01.

call function 'ZGETCUSTOMER'


DESTINATION 'RFCDESTEHP7'
EXPORTING
i_kunnr = p_kunnr
IMPORTING
e_name1 = gv_name1
e_ort01 = gv_ort01.

write :/ 'Customer Name :',gv_name1,


/ 'Customer City :',gv_ort01.

Summary :

Cross-Apps--> RFC

RFC --> Remote Function Call

--> It is a process of calling a function module existing in remote SAP Serve

--> For this, we need to create the F.M as 'Remote'

--> For Remote Function Modules, parameters are always passed by value

--> In RFC communication, two parties are involved

a) RFC Server --> system where the remote F.M is existing

b) RFC Client --> system from where the remote F.M is called

Synchronous RFC Vs Asynchronous RFC

Types of RFC s:-


1. Synchronous RFC

2. Asynchronous RFC

3. Transactional RFC

Synchronous RFC:

Syntax:

call function <remote function>

destination <rfc destination>

[parameters list].

Asynchronous RFC:

Syntax:

Call function <remote function>

destination <rfc destination>

starting new task <task name>

performing <subroutine> on end of task

[exporting parameters].

Syntax for receiving results from ARFC:

form <subroutine> using <task name>.

receive results from function <function name>

[importing parameters].

--- ---

-- ---

endform.

RFC Server and RFC client

RFC server --> EHP7

remote function --> zgetcustomer

RFC client --> EHP 5


rfc destination -->RFCDESTEHP7

Steps in RFC Server (EHP7):

1. Create / Consider a existing function group (zrfcgrp)

2. Create a Remote Function module

Remote function module: zgetcustomer

import :

i_kunnr type kna1-kunnr passbyval (select checkbox)

export:

e_name1 type kna1-name1 passbyval (select checkbox)

e_ort01 type kna1-ort01 passbyval (select checkbox)

source code :

select single name1 ort01 from kna1 into ( e_name1,e_ort01)

where kunnr = i_kunnr.

Steps in RFC Client (EHP5):

Executable program (RFC client program) to call above remote function in Synchronous
MODE:

REPORT ZCALLSRFC.

PARAMETERS p_kunnr type kna1-kunnr.

data : gv_name1 type kna1-name1,


gv_ort01 type kna1-ort01.

call function 'ZGETCUSTOMER'


DESTINATION 'RFCDESTEHP7'
EXPORTING
i_kunnr = p_kunnr
IMPORTING
e_name1 = gv_name1
e_ort01 = gv_ort01.
write :/ 'Customer Name :',gv_name1,
/ 'Customer City :',gv_ort01.

Executable program (RFC client program) to call above remote function in ASynchronous
MODE:

REPORT ZCALLARFC.

PARAMETERS p_kunnr type kna1-kunnr.


data : gv_name1 type kna1-name1,

gv_ort01 type kna1-ort01.

call function 'ZGETCUSTOMER'


DESTINATION 'RFCDESTEHP7'
STARTING NEW TASK 'T1'
PERFORMING getdata on END OF TASK
EXPORTING
i_kunnr = p_kunnr.

*wait up to 15 seconds. "suspends main thread for 15 seconds


write :/ 'Customer Name :',gv_name1,
/ 'Customer City :',gv_ort01.

form getdata using t1.


RECEIVE RESULTS FROM FUNCTION 'ZGETCUSTOMER'
IMPORTING
e_name1 = gv_name1
e_ort01 = gv_ort01.
endform.

Note: Both for Synchronous RFC and Asynchronous RFC, RFC Server should be available at the
time of communication, otherwise call to Remote Function leads to runtime error.
TRFC Communication

TRFC (Transactional RFC):

Syntax for TRFC:

call function <remote function>

in background task

destination <rfc destination>

[exporting parameters].

It is recommended to call only those F.M's in TRFC Mode which doesn't return any value.

In case of TRFC call, the remote server need not be available at the time of communication. In
this case, if the remote server is not available at the time of communication, the request is
stored in the db tables 'ARFCSSTATE' and 'ARFCSDATA'of the calling system (RFC Client).

After this, SAP schedules the program 'RSARFCSE' in the background which is executed for
every 15 minutes for 20/30 attempts for processing the request. Within these attempts, if the
remote server is not available, a fresh request needs to send.

Whenever a remote function is called in TRFC mode, we need to provide the statement 'commit
work' as part of calling program, so that the request is stored in the above db tables. We can
check the execution status of TRFC using 'SM58'.

TRFC Steps:
RFC server (EHP7)

1. Consider/create a db table

DB Table: ZCUSTOMERS

Fields:

Kunnr kunnr char 10

Name1 name1_gp char 35

Ort01 ort01_gp char 35

2. Consider/create a function group (zrfcgrp)

3. Create a remote function module(ZINSERTCUSTOMER)

import:

i_customer type zcustomers passbyval

source code :

insert zcustomers from i_customer.

RFC client (EHP5):

1. Consider/create a RFC destination (RFCDESTEHP7)

2. Create an executable program to call the remote function in TRFC mode

Executable program name --> ZCALLTRFC

REPORT ZCALLTRFC.

types : begin of ty_customer,


f1(10) type c,
f2(35) type c,
f3(35) type c,
end of ty_customer.

data wa_customer type ty_customer.

wa_customer-f1 = '0000000101'.
wa_customer-f2 = 'Kiran'.
wa_customer-f3 = 'Mumbai'.

call function 'ZINSERTCUSTOMER'


in background task
DESTINATION 'RFCDESTEHP7'
exporting
i_customer = wa_customer.

commit work.

write :/ 'End of RFC client program'.

Note: Before executing the above RFC client program, Switch off the Remote SAP Server (EHP7)
and then execute, SAP schedules a program RSARFCSE in the background as a background job
which gets executed every 15 minutes to check whether remote SAP server is switched on for
processing the request. Following is the status of Background job after successful execution.
Check the status of the background job using SM37.
Job log:

Check the entry in RFC server (EHP7): DB table ZCUSTOMERS


Normal Vs Remote Vs Update F.M's

Calling RFC's Back


Update function modules:-

Update Function modules called using the addition in update task will not be executed
immediately; instead it is marked in VBLOG table for later execution. As part of program
execution, whenever commit work statement is executed, SAP picks the entry from VBLOG
table and then executes the update F.M. As part of update F.M execution, SAP executes all the
DB statements as a single LUW in a separate process called as UPDATE Work Process .

The Normal Function modules called using the addition in update task will lead to runtime
error.

1. Consider a db table zcustomers

2. Create update function module (attributes tab -->select 'update F.M' radiobutton)

Update F.M: ZCUSTOMERS_DML


Source code:

FUNCTION ZCUSTOMERS_DML.
*"----------------------------------------------------------------------
*"*"Update Function Module:
*"
*"*"Local Interface:
*"----------------------------------------------------------------------

* insert a customer
data wa_cust type zcustomers.
wa_cust-kunnr = '0000000103'.
wa_cust-name1 = 'Kranthi Kumar'.
wa_cust-ort01 = 'Hyderabad'.

insert zcustomers from wa_cust.

* delete the customer


delete from zcustomers where kunnr = '0000000102'.

* update the customer


update zcustomers set name1 = 'Sridhar Sunkari-SAP'
where kunnr = '0000000100'.
ENDFUNCTION.
3. Create an executable program to call the update F.M USING in update task addition

REPORT ZCALLUPDATEFM.

call function 'ZCUSTOMERS_DML'


in update task.

write :/ 'Hello',
/ 'Welcome'.

commit work.

BAPI's (Business Application Programming Interface)

BAPI is also a Remote Function Module

Every BAPI must be an RFC

Every RFC need not be BAPI.

As long as we access BAPI from SAP Environment, it is just like calling a F.M

SAP ---> has provided many standard Business objects which are used for performing a
task (create / change / read sales order & purchase order, create / change
/ display material, create / change / display bank details...)

Every STD. Business object --> contains collection of API methods

--> Every API method is associated with BAPI F.M

For an ABAP consultant, a BAPI is nothing but a F.M.

For a Legacy Programmer, a BAPI is nothing but a API method.

Business objects are stored inside 'BOR' (Business object Repository).

To access 'BOR' ---> t-code used is 'BAPI'.

Example:

Business Object name --> Bank (object)

Business Object Type --> BUS1011 (class)

SW01 (Business object builder) is the t-code used for developing custom business object
/ view the components of standard business object.

BAPI Function Module standards:


1. Function module name must start with 'BAPI_....'

2. Function module should be remote enabled

3. Function module parameters must be passed by value

4. Function module parameter references must start with 'BAPI' and these references must
refer to a whole structure / a structure field

5. Function module must contain a return parameter which is of type 'BAPIRETURN' /


'BAPIRETURN1' / 'BAPIRET1' / 'BAPIRET2'. This parameter is responsible for returning the
execution status of the BAPI.

6. Function Module source code should not contain the statements 'COMMIT WORK' /
'ROLLBACK', instead we can use the F.M's 'BAPI_TRANSACTION_COMMIT' /
'BAPI_TRANSACTION_ROLLBACK'

Concepts Related to BAPI's:

a) Working with Standard BAPI's

b) Modifying standard BAPI's

c) Extending Standard BAPI's (BAPI Extension)

d) Creating Custom BAPI's

e) Using BAPI's in LSMW Tool


Accessing BAPIs

bapi access

BOR
Example: Create bank using Standard BAPI - Runtime error

report zbapi1.

data : gv_bctry type bapi1011_key-bank_ctry value 'IN',


wa_baddr type bapi1011_address,
wa_return type bapiret2.

* prepare bank address details


clear wa_baddr.
wa_baddr-bank_name = 'Punjab National Bank'.
wa_baddr-region = '01'.
wa_baddr-street = 'Srinivasa Nagar'.
wa_baddr-city = 'Hyderabad'.

* call BAPI F.M


call function 'BAPI_BANK_CREATE'
exporting
bank_ctry = gv_bctry
* BANK_KEY =
bank_address = wa_baddr
importing
return = wa_return.

write :/ 'Bank creation status ...'.


write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.

Note: The above BAPI execution results in runtime error specify bank key

Example: Create bank using Standard BAPI

report zbapi2.

data : gv_bctry type bapi1011_key-bank_ctry value 'IN',


gv_bkey type bapi1011_key-bank_key value 'RBS',
wa_baddr type bapi1011_address,
wa_return type bapiret2.

* prepare bank address details


clear wa_baddr.
wa_baddr-bank_name = 'Royal Bank of Scotland'.
wa_baddr-region = '01'.
wa_baddr-street = 'Srinivasa Nagar'.
wa_baddr-city = 'Hyderabad'.
* call BAPI F.M
call function 'BAPI_BANK_CREATE'
exporting
bank_ctry = gv_bctry
bank_key = gv_bkey
bank_address = wa_baddr
importing
return = wa_return.

call function 'BAPI_TRANSACTION_COMMIT'.

write :/ 'Bank creation status ...'.


write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.

Example: BAPI to modify Bank details

REPORT Z730BAPI3.

DATA : v_bctry type BAPI1011_KEY-BANK_CTRY value 'IN',


v_bkey type BAPI1011_KEY-BANK_KEY value 'PNB',
wa_baddr type BAPI1011_ADDRESS,
wa_baddrx type BAPI1011_ADDRESSX,
wa_return type BAPIRET2.

* prepare modified bank address data


wa_baddr-bank_name = 'Punjab National Bank-2'.
wa_baddr-street = 'Sr Nagar'.
wa_baddr-city = 'Hyderabad'.

* prepare and mark modified fields


wa_baddrx-bank_name = 'X'.
wa_baddrx-street = 'X'.
wa_baddrx-city = 'X'.

* call the BAPI F.M to update bank details


CALL FUNCTION 'BAPI_BANK_CHANGE'
EXPORTING
BANKCOUNTRY = v_bctry
BANKKEY = v_bkey
BANK_ADDRESS = wa_baddr
BANK_ADDRESSX = wa_baddrx
IMPORTING
RETURN = wa_return.

CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.

write :/ 'Type :',wa_return-type,


/ 'Message :',wa_return-message.

Example: BAPI to Read Single Bank Details

REPORT Z730BAPI4.

parameters : p_bctry type BAPI1011_KEY-BANK_CTRY,


p_bkey type BAPI1011_KEY-BANK_KEY.

data : wa_baddr type BAPI1011_ADDRESS,


wa_return type BAPIRET2.

* call BAPI F.M to get bank details


CALL FUNCTION 'BAPI_BANK_GETDETAIL' "SELECT SINGLE
EXPORTING
BANKCOUNTRY = p_bctry
BANKKEY = p_bkey
IMPORTING
BANK_ADDRESS = wa_baddr
RETURN = wa_return.

format color 3.
write :/ 'Bank Address data..'.
write :/ 'Bank name :',wa_baddr-bank_name,
/ 'Region :',wa_baddr-region,
/ 'Street :',wa_baddr-street,
/ 'City :',wa_baddr-city.
format color off.

uline.
write :/ 'Bank Execution status..'.
format color 7.
write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.
format color off.

Example: BAPI to Read Multiple Bank Details


REPORT Z730BAPI5 line-SIZE 150.

PARAMETERS : p_bctry type BAPI1011_LIST-BANK_CTRY,


p_rows type BAPI1011_KEY-MAX_ROWS.

data wa_return type BAPIRET2.

data : t_blist type TABLE OF BAPI1011_LIST,


wa_blist like line of t_blist. "(or)
* wa_blist type BAPI1011_LIST.

* Call bapi f.m to get list of banks


CALL FUNCTION 'BAPI_BANK_GETLIST' "SELECT INTO TABLE
EXPORTING
BANK_CTRY = p_bctry
MAX_ROWS = p_rows
IMPORTING
RETURN = wa_return
TABLES
BANK_LIST = t_blist.

format color 1.
write :/ 'Bank Execution status...'.
write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.
format color off.

uline.
format color 3.
loop at t_blist into wa_blist.
write :/ wa_blist-bank_ctry,
wa_blist-bank_key,
wa_blist-bank_name,
wa_blist-city.
endloop.
format color off.

Example: BAPI TO CREATE MATERIAL (BAPI ERROR – NO DESCRIPTION TRANSFERRED)

REPORT Z730BAPI6.

* prepare material header data


data wa_mathead type BAPIMATHEAD.
wa_mathead-material = '730MAT_501'.
wa_mathead-ind_sector = 'P'. "pharmaceuticals-T137
wa_mathead-matl_type = 'ROH'. "Raw material-T134

data wa_return type BAPIRET2.

* call BAPI F.M to create Material


CALL FUNCTION 'BAPI_MATERIAL_SAVEDATA'
EXPORTING
HEADDATA = wa_mathead
IMPORTING
RETURN = wa_return.

CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.

format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type .....',wa_return-type,
/ 'Message ..',wa_return-message.
format color off.

Example: BAPI TO CREATE MATERIAL (BAPI ERROR – BASE UNIT OF MEASURE IS DEFINED AS
REQUIRED FIELD)

REPORT Z730BAPI7.

* prepare material header data


data wa_mathead type BAPIMATHEAD.
wa_mathead-material = '730MAT_501'.
wa_mathead-ind_sector = 'P'. "pharmaceuticals-T137
wa_mathead-matl_type = 'ROH'. "Raw material-T134

* prepare material descriptions


data : t_makt type table of BAPI_MAKT,
wa_makt type BAPI_MAKT.

clear wa_makt.
wa_makt-langu = 'E'. "Language keys-T002
wa_makt-langu_iso = 'EN'.
wa_makt-MATL_DESC = 'This is Material in English'.
append wa_makt to t_makt.

clear wa_makt.
wa_makt-langu = 'D'. "Language keys-T002
wa_makt-langu_iso = 'DE'.
wa_makt-MATL_DESC = 'This is Material in German'.
append wa_makt to t_makt.

data wa_return type BAPIRET2.

* call BAPI F.M to create Material


CALL FUNCTION 'BAPI_MATERIAL_SAVEDATA'
EXPORTING
HEADDATA = wa_mathead
IMPORTING
RETURN = wa_return
TABLES
MATERIALDESCRIPTION = t_makt.

CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.

format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type .....',wa_return-type,
/ 'Message ..',wa_return-message.
format color off.

Example: BAPI TO CREATE MATERIAL (BAPI ERROR – MATERIAL GROUP IS DEFINED AS


REQUIRED FIELD)

REPORT Z730BAPI8.

* prepare material header data


data wa_mathead type BAPIMATHEAD.
wa_mathead-material = '730MAT_501'.
wa_mathead-ind_sector = 'P'. "pharmaceuticals-T137
wa_mathead-matl_type = 'ROH'. "Raw material-T134

* Prepare base unit of measure


data wa_clientdata type BAPI_MARA.
wa_clientdata-base_uom = 'KG'. "Kilogram - T006
wa_clientdata-base_uom_iso = 'KGM'. "T006I

* prepare and set update fields


data wa_clientdatax type BAPI_MARAX.
wa_clientdatax-base_uom = 'X'.
wa_clientdatax-base_uom_iso = 'X'.

* prepare material descriptions


data : t_makt type table of BAPI_MAKT,
wa_makt type BAPI_MAKT.

clear wa_makt.
wa_makt-langu = 'E'. "Language keys-T002
wa_makt-langu_iso = 'EN'.
wa_makt-MATL_DESC = 'This is Material in English'.
append wa_makt to t_makt.

clear wa_makt.
wa_makt-langu = 'D'. "Language keys-T002
wa_makt-langu_iso = 'DE'.
wa_makt-MATL_DESC = 'This is Material in German'.
append wa_makt to t_makt.

data wa_return type BAPIRET2.

* call BAPI F.M to create Material


CALL FUNCTION 'BAPI_MATERIAL_SAVEDATA'
EXPORTING
HEADDATA = wa_mathead
CLIENTDATA = wa_clientdata
CLIENTDATAX = wa_clientdatax
IMPORTING
RETURN = wa_return
TABLES
MATERIALDESCRIPTION = t_makt.

CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.

format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type .....',wa_return-type,
/ 'Message ..',wa_return-message.
format color off.

Example: BAPI TO CREATE MATERIAL (SUCCESS – MATERIAL CREATED OR EXTENDED)

REPORT Z730BAPI9.

* prepare material header data


data wa_mathead type BAPIMATHEAD.
wa_mathead-material = '730MAT_501'.
wa_mathead-ind_sector = 'P'. "pharmaceuticals-T137
wa_mathead-matl_type = 'ROH'. "Raw material-T134

* Prepare base unit of measure and matl.group


data wa_clientdata type BAPI_MARA.
wa_clientdata-base_uom = 'KG'. "Kilogram - T006
wa_clientdata-base_uom_iso = 'KGM'. "T006I
wa_clientdata-matl_group = '001'.

* prepare and set update fields


data wa_clientdatax type BAPI_MARAX.
wa_clientdatax-base_uom = 'X'.
wa_clientdatax-base_uom_iso = 'X'.
wa_clientdatax-matl_group = 'X'.

* prepare material descriptions


data : t_makt type table of BAPI_MAKT,
wa_makt type BAPI_MAKT.

clear wa_makt.
wa_makt-langu = 'E'. "Language keys-T002
wa_makt-langu_iso = 'EN'.
wa_makt-MATL_DESC = 'This is Material in English'.
append wa_makt to t_makt.

clear wa_makt.
wa_makt-langu = 'D'. "Language keys-T002
wa_makt-langu_iso = 'DE'.
wa_makt-MATL_DESC = 'This is Material in German'.
append wa_makt to t_makt.

data wa_return type BAPIRET2.

* call BAPI F.M to create Material


CALL FUNCTION 'BAPI_MATERIAL_SAVEDATA'
EXPORTING
HEADDATA = wa_mathead
CLIENTDATA = wa_clientdata
CLIENTDATAX = wa_clientdatax
IMPORTING
RETURN = wa_return
TABLES
MATERIALDESCRIPTION = t_makt.

CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.


format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type .....',wa_return-type,
/ 'Message ..',wa_return-message.
format color off.

Header and Item data in SD and MM Modules

Example: Create Employee Communication Details (BAPI Status- Personel number not yet
assigned)

REPORT Z730BAPI10.

data : v_empno type BAPIP0105N-EMPLOYEENO value '00001999',


v_stype type BAPIP0105N-SUBTYPE value '0010',
v_bdate type BAPIP0105N-VALIDBEGIN value '20160101',
v_edate type BAPIP0105N-VALIDEND value '20160404',
v_email type BAPIP0105N-ID value 'abc@outlook.com',
wa_return type BAPIRETURN1.

* call bapi F.M to create Employee Communication details


CALL FUNCTION 'BAPI_EMPLCOMM_CREATE'
EXPORTING
EMPLOYEENUMBER = v_empno
SUBTYPE = v_stype
VALIDITYBEGIN = v_bdate
VALIDITYEND = v_edate
COMMUNICATIONID = v_email
IMPORTING
RETURN = wa_return.

format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.
format color off.

Example: Create Employee Communication Details (BAPI Status- Employee / Applicant not
locked)

REPORT Z730BAPI11.

data : v_empno type BAPIP0105N-EMPLOYEENO value '00001000',


v_stype type BAPIP0105N-SUBTYPE value '0010',
v_bdate type BAPIP0105N-VALIDBEGIN value '20160101',
v_edate type BAPIP0105N-VALIDEND value '20160404',
v_email type BAPIP0105N-ID value 'abc@outlook.com',
wa_return type BAPIRETURN1.

* call bapi F.M to create Employee Communication details


CALL FUNCTION 'BAPI_EMPLCOMM_CREATE'
EXPORTING
EMPLOYEENUMBER = v_empno
SUBTYPE = v_stype
VALIDITYBEGIN = v_bdate
VALIDITYEND = v_edate
COMMUNICATIONID = v_email
IMPORTING
RETURN = wa_return.

format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.
format color off.

Example: Create Employee Communication Details (BAPI Status-Invalid Date)

REPORT Z730BAPI12.

data : v_empno type BAPIP0105N-EMPLOYEENO value '00001000',


v_stype type BAPIP0105N-SUBTYPE value '0010',
v_bdate type BAPIP0105N-VALIDBEGIN value '20160101',
v_edate type BAPIP0105N-VALIDEND value '20161304',
v_email type BAPIP0105N-ID value 'abc@outlook.com',
wa_return type BAPIRETURN1.

* lock the employee


clear wa_return.
CALL FUNCTION 'BAPI_EMPLOYEET_ENQUEUE'
EXPORTING
NUMBER = v_empno
VALIDITYBEGIN = '19000101'
IMPORTING
RETURN = wa_return.

if wa_return-type ne 'E'. "successfully locked


clear wa_return.
* call bapi F.M to create Employee Communication details
CALL FUNCTION 'BAPI_EMPLCOMM_CREATE'
EXPORTING
EMPLOYEENUMBER = v_empno
SUBTYPE = v_stype
VALIDITYBEGIN = v_bdate
VALIDITYEND = v_edate
COMMUNICATIONID = v_email
IMPORTING
RETURN = wa_return.

format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.
format color off.

* unlock employee
clear wa_return.
CALL FUNCTION 'BAPI_EMPLOYEET_DEQUEUE'
EXPORTING
NUMBER = v_empno
VALIDITYBEGIN = '19000101'
IMPORTING
RETURN = wa_return.

endif.
Example: Create Employee Communication Details

REPORT Z730BAPI13.

data : v_empno type BAPIP0105N-EMPLOYEENO value '00001000',


v_stype type BAPIP0105N-SUBTYPE value '0010',
v_bdate type BAPIP0105N-VALIDBEGIN value '20160101',
v_edate type BAPIP0105N-VALIDEND value '20160504',
v_email type BAPIP0105N-ID value 'abc@outlook.com',
wa_return type BAPIRETURN1.

* lock the employee


clear wa_return.
CALL FUNCTION 'BAPI_EMPLOYEET_ENQUEUE'
EXPORTING
NUMBER = v_empno
VALIDITYBEGIN = '19000101'
IMPORTING
RETURN = wa_return.

if wa_return-type ne 'E'. "successfully locked


clear wa_return.
* call bapi F.M to create Employee Communication details
CALL FUNCTION 'BAPI_EMPLCOMM_CREATE'
EXPORTING
EMPLOYEENUMBER = v_empno
SUBTYPE = v_stype
VALIDITYBEGIN = v_bdate
VALIDITYEND = v_edate
COMMUNICATIONID = v_email
IMPORTING
RETURN = wa_return.

format color 3.
write :/ 'BAPI Execution status...'.
write :/ 'Type :',wa_return-type,
/ 'Message :',wa_return-message.
format color off.

* unlock employee
clear wa_return.
CALL FUNCTION 'BAPI_EMPLOYEET_DEQUEUE'
EXPORTING
NUMBER = v_empno
VALIDITYBEGIN = '19000101'
IMPORTING
RETURN = wa_return.

endif.

sd, mm --> Header data & item data

eg: sales order --> va01 (create s.o)

header data --> vbak

item data --> vbap

eg : purchase order --> me21 (create p.o)

header data --> ekko

item data --> ekpo

hr ---> data is stored in the form of infotypes

infotype --> 4 digit no

sap hr ---> sub modules

a) PA (Personal Administration) --> 0000 to 0999

b) OM (Organization Management) --> 1000 to 1999

c) TM (Time management) --> 2000 to 2999

d) RE (Recruitment) ---> 4000 to 4999

custom infotypes ==> 9000 to 9999

eg: infotype --> 0002 (PA)

db table --> PA0002 (PA<infotype no>)

dic.str --> P0002 (P<infotype no>)

Module pool program ---> MP000200 (MP<infotype no>00)

bank ---> FI01 ---> BNKA

material --> MM01 ---> MARA, MAKT, MARC...

HR master data --> PA30

--> CREATE COMMUNICATION DETAILS (0105) ---> PA0105


4952

1003 --> 2

lock the customer

perform the operation

unlock the customer

lock object ---> kna1-kunnr

2 f/m's ---> enqueue_<lock obj.name> --> locking

--> dequeue_<lock obj.name> --> release

BAPI Extension

Example: Create Sales Order using Standard BAPI F.M

REPORT Z730BAPI14.

* Prepare Order Header Details


data wa_order_header type BAPISDHD1.
wa_order_header-doc_type = 'TA'.
wa_order_header-sales_org = '1000'.
wa_order_header-distr_chan = '12'.
wa_order_header-division = '00'.
* prepare partners internal table
data : t_partners type TABLE OF BAPIPARNR,
wa_partners like line of t_partners.

clear wa_partners.
wa_partners-partn_role = 'AG'.
wa_partners-partn_numb = '0000001000'.
append wa_partners to t_partners.

* prepare Item data


data : t_items type table of BAPISDITM,
wa_items like line of t_items.

clear wa_items.
wa_items-itm_number = '10'.
wa_items-material = 'AM2-GTL'.
append wa_items to t_items.

data v_vbeln type BAPIVBELN-VBELN.


data : t_return type table of BAPIRET2,
wa_return like line of t_return.

CALL FUNCTION 'BAPI_SALESORDER_CREATEFROMDAT2'


EXPORTING
ORDER_HEADER_IN = wa_order_header
IMPORTING
SALESDOCUMENT = v_vbeln
TABLES
RETURN = t_return
ORDER_ITEMS_IN = t_items
ORDER_PARTNERS = t_partners.

CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.

format color 3.
write :/ 'BAPI Execution status...'.
loop at t_return into wa_return.
write :/ wa_return-type,
wa_return-message.
endloop.
format color off.

write :/ 'Generated Sales Order Document no is :',v_vbeln.


Business object : SalesOrder

BAPI F.M: BAPI_SALESORDER_CREATEFROMDAT2 --> used for creating sales order

T-code : VA01

Tables: VBAK (Sales Doc.Header data) --> 10.669 + 1

VBAP (Sales Doc. Item data) --> 18.797 + 1

std.bapi's ---> updates std. db tables

std.table 'vbak' --> 269 fields (std.fields)

additional 10 fields (customer specific fields)

vbak ---> 279 fields

(269 fields + 10 fields)

BAPI Extension :- ExtensionIN & ExtensionOUT

ExtensionIN --> used for passing data related to customer specific fields while calling
BAPI F.M

ExtensioOUT --> used for reading data related to customer specific fields while calling
BAPI F.M

15579
BAPIExtension-ExtensionIn Internal table

Procedure for Extending standard BAPI F.M 'BAPI_SALESORDER_CREATEFROMDAT2'

Enhancements to the table and structures:

Table 'vbak' ---> Append Structure zcompetitor

Additional Fields:

zzcompname zcompname char 20

zzcompaddr zcompaddr char 20

Dependent Structures:

vbakkoz --> Append Structure  zavbakkoz

Additional Fields:

zzcompname zcompname char 20

zzcompaddr zcompaddr char 20

vbakkozx --> Append Structure  zavbakkozx

Additional Fields:
zzcompname char 1

zzcompaddr char 1

bape_vbak --> Append Structure zbape_vbak

Additional Fields:

zzcompname zcompname char 20

zzcompaddr zcompaddr char 20

bape_vbakx --> Append Structure zbape_vbakx

Additional Fields:

zzcompname char 1

zzcompaddr char 1

Example: Creating Sales Order using Standard BAPI by passing data related to Customer
Specific Fields through Extensionin Parameter

REPORT Z730BAPI15.

* Prepare Order Header Details


data wa_order_header type BAPISDHD1.
wa_order_header-doc_type = 'TA'.
wa_order_header-sales_org = '1000'.
wa_order_header-distr_chan = '12'.
wa_order_header-division = '00'.

* prepare partners internal table


data : t_partners type TABLE OF BAPIPARNR,
wa_partners like line of t_partners.

clear wa_partners.
wa_partners-partn_role = 'AG'.
wa_partners-partn_numb = '0000001000'.
append wa_partners to t_partners.

* prepare Item data


data : t_items type table of BAPISDITM,
wa_items like line of t_items.

clear wa_items.
wa_items-itm_number = '10'.
wa_items-material = 'AM2-GTL'.
append wa_items to t_items.

data v_vbeln type BAPIVBELN-VBELN.


data : t_return type table of BAPIRET2,
wa_return like line of t_return.

* prepare data for customer specific fields


data : t_extin type table of BAPIPAREX,
wa_extin type BAPIPAREX.

data wa_bape_vbak type bape_vbak.


clear wa_bape_vbak.
wa_bape_vbak-zzcompname = 'Reliance'.
wa_bape_vbak-zzcompaddr = 'Ameerpet'.

clear wa_extin.
wa_extin-structure = 'BAPE_VBAK'.
wa_extin-valuepart1 = wa_bape_vbak.
append wa_extin to t_extin.

data wa_bape_vbakx type bape_vbakx.


clear wa_bape_vbakx.
wa_bape_vbakx-zzcompname = 'X'.
wa_bape_vbakx-zzcompaddr = 'X'.

clear wa_extin.
wa_extin-structure = 'BAPE_VBAKX'.
wa_extin-valuepart1 = wa_bape_vbakx.
append wa_extin to t_extin.

CALL FUNCTION 'BAPI_SALESORDER_CREATEFROMDAT2'


EXPORTING
ORDER_HEADER_IN = wa_order_header
IMPORTING
SALESDOCUMENT = v_vbeln
TABLES
RETURN = t_return
ORDER_ITEMS_IN = t_items
ORDER_PARTNERS = t_partners
EXTENSIONIN = t_extin.

CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.


format color 3.
write :/ 'BAPI Execution status...'.
loop at t_return into wa_return.
write :/ wa_return-type,
wa_return-message.
endloop.
format color off.

write :/ 'Generated Sales Order Document no is :',v_vbeln.

BAPI Extension:-

using this, we can pass data to customer specific fields while calling the standard
BAPI F.M's

1. customer include structure --> 'ci_....'---> additional fields --> 'zz' / 'yy'

2. append structure (z...) ---> additional fields --> 'zz' / 'yy'

dbtable ---> vbak

--> append str --> zcompetitor

fields --> zzcompname zcompname char 20

-> zzcompaddrzcompaddr char 20

dependent structures

1. vbakkoz --> zzcompname zcompname char 20

zzcompaddr zcompaddr char 20

2. vbakkozx --> zzcompname char1 char 1

zzcompaddr char1 char 1

3. bape_vbak --> zzcompname zcompname char 20

zzcompaddr zcompaddr char 20

4. bape_vbakx --> zzcompname char1 char 1

zzcompaddr char1 char 1

Bapi extension
extensionin --> used for passing data to additional fields through BAPI

extensionout --> used for reading data related to additional fields through BAPI

Example: Create Purchase order using std.bapi BAPI_PO_CREATE1 without considering


EXTENSIONIN parameter

report zbapi13.

* prepare PO Header data


data wa_poheader type bapimepoheader.
wa_poheader-comp_code = '1000'.
wa_poheader-doc_type = 'NB'.
wa_poheader-vendor = '0000001000'.
wa_poheader-purch_org = '1000'.
wa_poheader-pur_group = '001'.

* prepare PO Header data update flag parameters


data wa_poheaderx type bapimepoheaderx.
wa_poheaderx-comp_code = 'X'.
wa_poheaderx-doc_type = 'X'.
wa_poheaderx-vendor = 'X'.
wa_poheaderx-purch_org = 'X'.
wa_poheaderx-pur_group = 'X'.

* prepare PO Item data


data : t_poitem type table of bapimepoitem,
wa_poitem type bapimepoitem.

clear wa_poitem.
wa_poitem-po_item = '00001'.
wa_poitem-material = '100-100'.
wa_poitem-plant = '1000'.
wa_poitem-stge_loc = '0001'.
wa_poitem-quantity = '15.000'.
append wa_poitem to t_poitem.

* prepare PO Item data update flag parameters


data : t_poitemx type table of bapimepoitemx,
wa_poitemx type bapimepoitemx.

clear wa_poitemx.
wa_poitemx-po_item = '00001'.
wa_poitemx-material = 'X'.
wa_poitemx-plant = 'X'.
wa_poitemx-stge_loc = 'X'.
wa_poitemx-quantity = 'X'.
append wa_poitemx to t_poitemx.

data : t_return type table of bapiret2,


wa_return type bapiret2.

data gv_ponum type bapimepoheader-po_number.

* call BAPI F.M to create purchase order without extensionin parameter


call function 'BAPI_PO_CREATE1'
exporting
poheader = wa_poheader
poheaderx = wa_poheaderx
importing
exppurchaseorder = gv_ponum
tables
return = t_return
poitem = t_poitem
poitemx = t_poitemx.

* save the bapi changes


call function 'BAPI_TRANSACTION_COMMIT'.

format color 3.
write :/ 'BAPI Execution status...'.
loop at t_return into wa_return.
write :/ 'Type :',wa_return-type,
/ 'Message:',wa_return-message.
endloop.
format color off.

write :/ 'Purchase document number generated :',gv_ponum.

Example: Create Purchase order using std.bapi BAPI_PO_CREATE1 considering


EXTENSIONIN parameter

Procedure:

1. Add the customer specific fields in the header table

Header table: EKKO

Include structure: CI_EKKODB

Custom Fields:
zzcompname zcompname char 20

zzcompaddr zcompaddr char 20

2. Add the customer specific fields in the DEPENDENT structure BAPI_TE_MEPOHEADERX as


update flag fields.

Program:

report zbapi14.

* prepare PO Header data


data wa_poheader type bapimepoheader.
wa_poheader-comp_code = '1000'.
wa_poheader-doc_type = 'NB'.
wa_poheader-vendor = '0000001000'.
wa_poheader-purch_org = '1000'.
wa_poheader-pur_group = '001'.

* prepare PO Header data update flag parameters


data wa_poheaderx type bapimepoheaderx.
wa_poheaderx-comp_code = 'X'.
wa_poheaderx-doc_type = 'X'.
wa_poheaderx-vendor = 'X'.
wa_poheaderx-purch_org = 'X'.
wa_poheaderx-pur_group = 'X'.

* prepare PO Item data


data : t_poitem type table of bapimepoitem,
wa_poitem type bapimepoitem.

clear wa_poitem.
wa_poitem-po_item = '00001'.
wa_poitem-material = '100-100'.
wa_poitem-plant = '1000'.
wa_poitem-stge_loc = '0001'.
wa_poitem-quantity = '15.000'.
append wa_poitem to t_poitem.

* prepare PO Item data update flag parameters


data : t_poitemx type table of bapimepoitemx,
wa_poitemx type bapimepoitemx.

clear wa_poitemx.
wa_poitemx-po_item = '00001'.
wa_poitemx-material = 'X'.
wa_poitemx-plant = 'X'.
wa_poitemx-stge_loc = 'X'.
wa_poitemx-quantity = 'X'.
append wa_poitemx to t_poitemx.

data : t_return type table of bapiret2,


wa_return type bapiret2.

data gv_ponum type bapimepoheader-po_number.

* prepare data for customer specific fields


data : wa_bapi_te_mepoheader type bapi_te_mepoheader,
wa_bapi_te_mepoheaderx type bapi_te_mepoheaderx.

clear wa_bapi_te_mepoheader.
wa_bapi_te_mepoheader-zzcompname = 'Gentech'.
wa_bapi_te_mepoheader-zzcompaddr = 'SRnagar'.

clear wa_bapi_te_mepoheaderx.
wa_bapi_te_mepoheaderx-zzcompname = 'X'.
wa_bapi_te_mepoheaderx-zzcompaddr = 'X'.

* associate customer specific fields data to extensionin parameter


data : gt_extin type table of bapiparex,
gs_extin type bapiparex.

clear gs_extin.
gs_extin-structure = 'BAPI_TE_MEPOHEADER'.
gs_extin-valuepart1 = wa_bapi_te_mepoheader.
append gs_extin to gt_extin.

clear gs_extin.
gs_extin-structure = 'BAPI_TE_MEPOHEADERX'.
gs_extin-valuepart1 = wa_bapi_te_mepoheaderx.
append gs_extin to gt_extin.

call function 'BAPI_PO_CREATE1'


exporting
poheader = wa_poheader
poheaderx = wa_poheaderx
importing
exppurchaseorder = gv_ponum
tables
return = t_return
poitem = t_poitem
poitemx = t_poitemx
extensionin = gt_extin.

call function 'BAPI_TRANSACTION_COMMIT'.

format color 3.
write :/ 'BAPI Execution status...'.
loop at t_return into wa_return.
write :/ 'Type :',wa_return-type,
/ 'Message:',wa_return-message.
endloop.
format color off.

write :/ 'Purchase document number generated :',gv_ponum.

Example: Display Purchase order using std.bapi BAPI_PO_GETDETAIL1 without considering


EXTENSIONOUT parameter
report zbapi15.

parameters : p_ponum type bapimepoheader-po_number.

data wa_poheader type bapimepoheader.

data : t_return type table of bapiret2,


wa_return type bapiret2.

call function 'BAPI_PO_GETDETAIL1'


exporting
purchaseorder = p_ponum
importing
poheader = wa_poheader
tables
return = t_return.

format color 3.
write :/ 'Bapi return status...'.
loop at t_return into wa_return.
write :/ 'Type ......',wa_return-type,
/ 'Message ...',wa_return-message.
endloop.
format color off.

format color 1.
write :/ 'PO Header data...'.
write :/ 'Company code :',wa_poheader-comp_code,
/ 'Document type:',wa_poheader-doc_type,
/ 'Vendor :',wa_poheader-vendor.
format color off.

Example: Display Purchase order using std.bapi BAPI_PO_GETDETAIL1 considering


EXTENSIONOUT parameter

report zbapi16.

parameters : p_ponum type bapimepoheader-po_number.

data wa_poheader type bapimepoheader.

data : t_return type table of bapiret2,


wa_return type bapiret2.
data : t_extout type table of bapiparex,
wa_extout type bapiparex.

data wa_bapi_te_mepoheader type bapi_te_mepoheader.

call function 'BAPI_PO_GETDETAIL1'


exporting
purchaseorder = p_ponum
importing
poheader = wa_poheader
tables
return = t_return
extensionout = t_extout.

format color 3.
write :/ 'Bapi return status...'.
loop at t_return into wa_return.
write :/ 'Type ......',wa_return-type,
/ 'Message ...',wa_return-message.
endloop.
format color off.

format color 1.
write :/ 'PO Header data...'.
write :/ 'Company code :',wa_poheader-comp_code,
/ 'Document type:',wa_poheader-doc_type,
/ 'Vendor :',wa_poheader-vendor.
format color off.

format color 7.
write :/ 'PO customer specific data...'.
loop at t_extout into wa_extout.
case wa_extout-structure.
when 'BAPI_TE_MEPOHEADER'.
wa_bapi_te_mepoheader = wa_extout-valuepart1.
endcase.
endloop.

write :/ 'Competitor name :',wa_bapi_te_mepoheader-zzcompname,


/ 'Competitor addr :',wa_bapi_te_mepoheader-zzcompaddr.

BAPI Modifications :-
Business object : CompanyCode

Object type : BUS0002

API method : GetList

Bapi F.M : BAPI_COMPANYCODE_GETLIST

AS IS : Returns list of all company codes

and comp.name

TO BE : Modify the above bapi to accept the lower limit and upper

limit of company codes as input and return the comp.codes and their
names between the given range

procedure :-

1) Consider /create function group

zrfcgrp

2) copy the standard bapi F.M to custom f.m following bapi standards

copied F.M : ZBAPI_COMPANYCODE_GETLIST

3) Make the necessary changes in the copied F.m

a) create the custom structure for holding company code field

structure : zbapibukrs

fields :

comp_code bukrs

b) Specify the import parameters in the copied F.M

lbukrs type zbapibukrs-comp_code passbyval

hbukrs type zbapibukrs-comp_code passbyval

c) Modify the source code of the copied F.M accordingly based on the
parameters passed.

d) save,activate and release the copied F.M

4) Create the business object inheriting the standard business object

a) Redefine the method 'getlist'


b) Associate the copied bapi f.m with the redefined method

c) Implement the redefined method 'getlist'

choose method 'getlist --> click on 'program' button (Appl.toolbar) ,yes, displays
source code.

In the source code declare 2


variables(lbukrs,hbukrs) of type bukrs

and specify them as values to parameters to bapi


f.m

d) Release the method 'getlist'

choose the method 'getlist' and choose

edit --> change release status --> object type --> implemented

edit --> change release status --> object type --> released

edit --> change release status --> object type component-->implemented

edit --> change release status --> object type component-->released

f) in the initial screen of SW01, release the business object and check the entry in BOR.

Note: Make sure the F.M, Business object should be saved in transportable package.
accessing sap business object from legacy appl

Accessing SAP business object from VB application:

1. Create a Form with 4 textfields and 1 command button

Event Builder:

General Declarations section:

Option Compare Database

Dim obj As Object

Dim con As Object

Dim obj_bapi As Object

Dim inputparam As Object

Dim outputparam As Object

Dim x As String

Form_Load event:

Private Sub Form_Load()

Set obj = CreateObject("SAP.BAPI.1")


Set con = obj.Connection

con.logon

MsgBox "Connected to SAP"

Set obj_bapi = obj.getsapobject("Z830_ETYPE")

Set inputparam = obj.dimas(obj_bapi, "Zbapi830emp", "Iemp")

End Sub

Button_click event:

Private Sub cmdinsert_Click()

inputparam.Value("empno") = Me.txtempno

inputparam.Value("ename") = Me.txtename

inputparam.Value("empdesig") = Me.txtdesig

inputparam.Value("deptno") = Me.txtdeptno

obj_bapi. Zbapi830emp Iemp:=inputparam, return:=outputparam

x = outputparam.Value("type")

If x = "S" Then

MsgBox "record inserted"

Else

MsgBox "record not inserted"

End If

End Sub

Creating Custom BAPI's :-

Procedure :-

1. Create a Function Module using BAPI standards and release the F.M

2. Create a Business object using BOB

(business object builder) --> SWO1 T-CODE


3. Release the Business object and check the entry in BOR --> BAPI T-CODE

BAPI F.M standards :-

1. F.M name -> 'BAPI_...'

2. F.M should be--> Remote enabled

3. F.M --> can contain return parameter of type--> 'BAPIRET1' /

'BAPIRET2' /

'BAPIRETURN' /

'BAPIRETURN1'

4. F.M --> parameter reference names should start with--> 'BAPI'

5. F.M --> parameter references should be--> structure / individual structure fields

6. F.M --> parameters should be --> pass by value

7. F.M --> source code --> shouldn't contain commit work and rollback

--> can contain 'BAPI_TRANSACTION_COMMIT' AND

'BAPI_TRANSACTION_ROLLBACK'

8. F.M --> should be transportable --> should be stored in transportable package and
assigned to change request

4.7 :-

1. Consider/CREATE a db table

table : z7amemp

fields :

empno zempnum char10

ename zename char10

empdesig zempdesig char10

deptno zdeptno int2 5

2. Create A Function group (z830bapigrp)

3. Create Function module using BAPI standards

a) consider a bapi structure (ZBAPI7AMEMP)


Fields :

empno zempnum char10

ename zename char10

empdesig zempdesig char10

deptno zdeptno int2 5

b) Function module (ZBAPI_INSERT_830EMP)

import :

i_emp type ZBAPI7AMEMP passbyvalue

export :

return type bapireturn passbyvalue

source code :

if i_emp is not initial.

insert z7amemp from i_emp.

if sy-subrc eq 0.

return-type = 'S'.

else.

return-type = 'E'.

endif.

endif.

c) Release the Function modul

function builder tool(se37),initial screen --> choose function module menu --> release --
> release

4. Create Business object (SWO1)

Business object type --> z830_etype

Business object --> z830_empobj

4.a) Create API method for our bapi F.M.


utilities menu --> API methods --> create, provide bapi F.M
(ZBAPI_INSERT_830EMP) , click on continue, proposes API method, click on next step,
proposes parameters for API methods, click on next, yes..

4.b) Redefine the std.methods 'existencecheck' and 'display' in the methods sectionselect
existencecheck method, choose 'edit' menu --> redefine.select display method, choose 'edit'
menu --> redefine.

4. c) select each method (existencecheck,display, our api method) one after the other and click
on 'program' button(appl.toolbar), save and comeback

4. d) select each method --> choose edit menu, change release status --> object type --> to
implemented select each method --> choose edit menu, change release status --> object type --
> to released

Now object type 'z830_etype' gets released (tick mark appears)

4. e) select each method --> choose edit menu, change release status --> object type
component--> to implemented select each method --> choose edit menu, change release status
--> object type component --> to released

Now individual methods (3 methods) gets released (tick mark appears)

5. Check the business object entry in BOR (BAPI T-CODE)

API method : Zbapi7amemp

parameters :

IEmp

Return
Customer exit classification

enhancement classification
enhancement meaning

screen enhancements meaning

enhancement procedure :

Enhancement is a process of adding additional functionality without disturbing the standard


functionality.

Additional functionality can be in the form of additional menu items, additional validations,
additional fields.

Procedure for enhancing SAP Transactions :


1. identify the enhancement requirement

2. identify the transaction and the base program where the enhancement needs to be
implemented

3. Search for the suitable enhancement technique

that can be implemented

Note: enhancement technique can be either user-exits (outdated) / customer-exits /


badi's / enhancement framework

Customer-exits: (types of customer-exits / components of customer-exit)

1. Function exit ---> used for implementing additional validations

2. Menu exit ---> used for plugging additional menu items

3. screen exit ---> used for plugging additional fields

procedure for identifying customer-exits:

Procedure to identify customer-exits in a SAP transaction :

1. Identify the main program of the transaction

se93 --> provide t-code, display --> identify program name

2. In the main program, search for the string

'call customer-function', so that SAP will display the points (places) where
the string is used

3. Double click on the call customer-function statement,

SAP takes the control to the corresponding function module from where identify
the customer-exit name

note :

Procedure 2 :

1. Identify the main program of the transaction

2. Identify the package of the main program

3. In the t-code SE84, Search for customer-exits by providing the package


Note: Associated with customer-exits, we need to use t-codes 'SMOD' and 'CMOD'.

SMOD can be used for identifying the components of the customer-exit and to read the
documentation.

CMOD can be used to implement the customer-exit.

Screen exits in customer-exits: (screen enhancements): Used for adding additional fields
specific to customer in the std. SAP screens.

These additional fields are generally placed in the subscreen reserved for customer
enhancement. This subscreen is placed on top of subscreen area. This subscreen is called by
SAP itself at the relevant place.

Customer specific fields are used to capture additional info. which is specific to customer.
Initially, we need to add these fields in the corresponding std.base table in the form of
customer include structure ('CI_...') or in the form of append structure. It is recommended to
following the CUSTOMER NAMESPACE naming standard for the customer specific fields.
According to customer namespace standards, the customer specific fields must start either with
'ZZ' / 'YY' otherwise we may face issues at the time of upgradation.

Every screen exit of a customer exit MAY/will be associated with 2 function exits.

1. PBO function exit --> can be implemented to provide default values for the customer
specific fields on the transaction

2. PAI function exit --> can be implemented to capture values entered by the user in the
runtime for the customer specific fields on the transaction.

Note: Every function exit is nothing but a function module.

Example 1: Screen exits and Function exits

MP01 --> Approved Manufacturer parts list

Requirement: Enhance the Transaction 'MP01' to capture additional data (customer specific)

Transaction: MP01

Main Program: SAPLMBAM

Package of the main program: ME

Customer-exit: AMPL0001

Screen-exit information: (collect from the enhancement in SMOD t-code)

Calling screen: SAPLMBAM (main program)

No : 120 (main screen-->normal screen)


Area : USER0001 (subscreen area)

Called screen : SAPLXAMP (subscreen program)

No : 1000 (subscreen no)

Syntax for calling customer subscreen in module pool transactions:

call customer-subscreen <subscreen area>

including <subscreen program name> <subscreen no>.

Procedure:

1. Add the additional fields in the STD. table 'AMPL'

Customer include: 'CI_AMPL'

Additional Fields:

zzcompname zcompname char 25

zzcompaddr zcompaddr char 25

2. Design the additional fields in the subscreen

se51 --> program name (SAPLXAMP)

screen no (1000) , create / change

In the attributes tab, choose screen type as 'subscreen'

Design the additional fields on the subscreen

(layout button-->appl.toolbar)

3. Implement the screen exit (CMOD)

cmod --> provide project name(zcrpj), create -->

Assign customer exit 'AMPL0001' in the enhancement assignments, click on


components to implement, activate.

Implementation for PBO Function exit :

tables ampl.

*i_ampl-zzcompname = 'IMAX'.

*i_ampl-zzcompaddr = 'Ameerpet'.

*move-corresponding i_ampl to ampl.


*(or)

i_ampl-zzcompname = 'IMAX'.

i_ampl-zzcompaddr = 'Ameerpet'.

ampl-zzcompname = i_ampl-zzcompname.

ampl-zzcompaddr = i_ampl-zzcompaddr.

*(or)

*ampl-zzcompname = 'IMAX1'.

*ampl-zzcompaddr = 'Srnagar'.

Implementation for PAI Function exit :

e_ampl-zzcompname = ampl-zzcompname.

e_ampl-zzcompaddr = ampl-zzcompaddr.

Example 2: Function exits

XD01 --> Customer Create

Requirement: Enhance the Transaction 'XD01' to make industry key field mandatory for Indian
customers

transaction : XD01

MAIN PROGRAM : SAPMF02d

package of the main program : VS

Customer-exit : SAPMF02d

Function-exit to be implemented: EXIT_SAPMF02D_001

Procedure:

1. Implement the function exit (CMOD)

cmod --> provide project name(zcrpj), create -->

assign customer exit 'SAPMF02D' in the enhancement assignments, click


on components to implement, activate.

Implementation for function exit:

if i_kna1-land1 = 'IN' and


i_kna1-brsch is initial.

message 'Please enter industry key in control data tab for indian customers' type 'E'.

endif.

Menu exits in customer-exits :-( Menu enhancements) :

Used for adding additional menu items specific to customer in the std. SAP menus.

These additional menu items are generally placed in the std. menu called as 'Extras'.

For these additional menu items, the function codes are provided by SAP itself and they start
with '+'.

As a developer, we are only responsible for providing menu item text and implementing the
action for that menu item.

The implementation for these menu items are done as part of corresponding function exit.

Transaction: MC94

Main program: SAPMMCP6

Package of main program: MCP2

Enhancement (customer-exit): MCP20003

1. Implement the MENU exit (CMOD)

cmod --> provide project name(zcrpj), create -->

Assign customer exit 'mcp20003' in the enhancement assignments, click on


components to implement.

Double click on each function code, provide function text (abap editor, function builder, class
builder......)

To implement the logic for these menu items, double click on function exit and implement the
following in the corresponding include program.

case sy-ucomm.

when '+CU1'.

call transaction 'SE38'.

when '+CU2'.

call transaction 'SE37'.


when '+CU3'.

call transaction 'SE24'.

when '+CU4'.

call transaction 'SE51'.

when '+CU5'.

call transaction 'SE41'.

when '+CU6'.

call transaction 'SE71'.

when '+CU7'.

call transaction 'SMARTFORMS'.

when '+CU8'.

call transaction 'SE91'.

when '+CU9'.

call transaction 'S010'.

endcase.

Save, activate the include,f.m, enhancement and project.

Test the t-code 'MC94' (provide planning type as commit, press enter) --> choose active version
button, displays a screen and choose the menu 'extras' for additional menu items under
submenu 'customer functions'.

Note: Customer-exit always supports single implementation i.e a customer-exit assigned to a


customer project cannot be assigned to other project. So, In this case, all the enhancement
requirements have to be implemented in the single project itself. The disadvantage of this
approach is customer will not have the flexibility to switch on / switch off a specific
functionality.
diff between classic badi's and kernel badi's

differences between customer exits and badi's

Menu Enhancements using BADI s:

Transaction: FBL3N

BADI: FI_ITEMS_MENUE01
Implementation (SE19): Provide Functions texts for menu items

Implementation of methods: (Functionality for Menu items)

method IF_EX_FI_ITEMS_MENUE01~LIST_ITEMS01.
call transaction 'SE38'.
endmethod.

method IF_EX_FI_ITEMS_MENUE01~LIST_ITEMS02.
call transaction 'SE24'.
endmethod.

method IF_EX_FI_ITEMS_MENUE01~LIST_ITEMS03.
call transaction 'SE37'.
endmethod.

method IF_EX_FI_ITEMS_MENUE01~LIST_ITEMS04.
call transaction 'SEGW'.
endmethod.

Testing:

T-code FBL3N : Provide G/L account (1000) and company code(1000) and execute  Displays
ALV Report , check the menu Extras for additional menu items
BADI's (Business Addin's):

1. BADI definition (se18) -->similar to 'SMOD'

2. BADI implementation (se19) --> similar to 'CMOD'

Components of BADI definition:

1. BADI interface --> 'IF_EX_<BADI DEFINITION>' --> collection of abstract


methods.

2. BADI class --> 'CL_EX_<BADI DEFINITION>' --> keeps track of all


implementations (active/inactive) of badi.

3. Information whether BADI is single use / multiple use -->

Single use  can contain only one active implementation

Multiple use  can contain any number of active implementations

4. Information whether BADI is filter dependent / filter independent -->

5. Documentation related to BADI

Components of BADI implementation:

1. BADI implementation name --> responsible for implementing the BADI definition
2. BADI Implementation class --> ''z/y'cl_im_<impl.name>' --> Responsible for
implementing the BADI interface
3. Filter values -->
4. Fallback class --> Associated with 'KERNEL' BADI s -->

Purpose of BADI:

1. Additional validations 2. Additional menu items 3. Additional fields

BADI searching techniques:

Procedure 1:

1. Identify the main program of the transaction

2. In the main program, search for the string cl_exithandler=>get_instance', displays the lines
where the method is called. In the method Signature, identify the badi name by referring to the
parameter 'exit_name' (or) refer to the parameter 'instance'

Procedure 2:

1. Identify the main program of the transaction


2. Identify the package of the program

3. In SE84, Provide package name and execute, displays badi's

Procedure 3:

1. In performance analysis tool (ST05), select the traces 'SQL Trace' and 'Table buffer
trace' and activate the trace

2. In another session, make the necessary changes in the appropriate transaction


where the BADI s needs to be identified

3. Come back to 'ST05' session, deactivate the trace and display the trace. Search for the
BADI's by providing the database views 'V_EXT_ACT' and 'V_EXT_IMP' in the objects field.

Requirement: While creating customers in XD01, for Indian customers, Industry key is
mandatory.

Transaction: XD01

Validation screen fields: land1, brsch

BADI definition to be implemented: customer_add_data (multiple use)

Enhancement spot: customer_add_data

Enhancement spot --> is a collection of badi definitions

Enhancement implementations --> is a collection of badi implementations

First Implementation:

SE19 --> In 'create implementation' block , choose the radio button (new badi), provide the
enhancement spot name (customer_add_data), click on 'create impl.' --> It will prompt to
provide enhancement implementation, provide the enh.impl.
name(ZCUSTOMER_ADD_DATA_ENHIMPL),continue---> It will prompt to provide 'badi
implementaion name', provide badi impl.name(zcustomer_add_data_impl1) for the badi
definition 'customer_add_data',continue --> Double click on implementing class node and
provide the impl. class name (zcl_im_customer_add_data_impl1), press enter and create class -
-> In the Implementation class , double click on the method 'check_all_data' to implement the
method.

Enhancement implementation --> ZCUSTOMER_ADD_DATA_ENHIMPL implementing


enhancement spot 'CUSTOMER_ADD_DATA'

First implementation:

BADI implementation --> zcustomer_add_data_impl1 implementing BADI definition


CUSTOMER_ADD_DATA'
BADI implementation class--> zcl_im_customer_add_data_impl1 implementing BADI interface
'IF_EX_CUSTOMER_ADD_DATA'

method if_ex_customer_add_data~check_all_data.

message 'check all data impl 1' type 'I'.

endmethod.

Second implementation:

BADI implementation --> zcustomer_impl2 implementing BADI definition


'CUSTOMER_ADD_DATA'

BADI implementation class --> zcl_im_customer_impl2 implementing BADI interface


'IF_EX_CUSTOMER_ADD_DATA'

method if_ex_customer_add_data~check_all_data.

message 'check all data second impl' type 'I'.

endmethod.

Third implementation:

BADI Implementation --> zcustomer_impl3 implementing BADI definition


'CUSTOMER_ADD_DATA'

BADI implementation class--> zcl_im_customer_impl3 implementing BADI interface


'IF_EX_CUSTOMER_ADD_DATA'

method if_ex_customer_add_data~check_all_data.

message 'check all data third impl' type 'I'.

endmethod.

Fourth implementation:

Enhancement implementation --> ZCUSTOMER_ADD_DATA_ENHIMPL2 implementing


enhancement spot 'CUSTOMER_ADD_DATA'

BADI implementation --> zcustomer_impl4 implementing BADI definition


'CUSTOMER_ADD_DATA'
BADI implementation class--> zcl_im_customer_impl4 implementing BADI interface
'IF_EX_CUSTOMER_ADD_DATA'

Consolidated Example:

First implementation of BADI customer_add_data:

method IF_EX_CUSTOMER_ADD_DATA~CHECK_ALL_DATA.

if s_kna1-LAND1 = 'IN' and s_kna1-brsch is INITIAL.

message 'Please enter industry key for INDIAN Customers' type 'I'.

endif.

endmethod.

Second implementation of BADI customer_add_data:

method IF_EX_CUSTOMER_ADD_DATA~PRESET_VALUES_CCODE.

E_KNB1-AKONT = '125000'.

endmethod.

Note: To test the second implementation, while creating customer in 'XD01' provide company
code (1000) in initial screen --> click on company code data button in Appl. toolbar -->
Recon.account field will be defaulted with the value '125000'.

28th and 29th Aug Summary :

enhancement spot --> container of one or more badi definitions--> each badi definition --->
associated with badi interface--> badi interface ---> associated with one or more abstract
methods

enhancement implementation --> container of one or more badi implementations--> each badi
implementation --> associated with badi implementation class --> badi implementation class -->
implements methods of badi interface

first implementation:

enh.impl (zenhimpl1) ---> badi impl(zimpl1) --->

--> badi impl.class(zcl_im_impl1)

--> check_all_data, save_data

second implementation:

enh.impl (zenhimpl1) --> badi impl(zimpl2) -->


--> badi impl.class(zcl_im_impl2)

--> check_all_data,save_data

third implementation:

enh.impl(zenhimpl2) --> badi impl(zimpl3) -->

--> badi impl.class (zcl_im_impl3)


--> check_all_data

Fourth implementation:

enh.impl(zenhimpl3) --> badi impl(zimpl4) -->

--> badi impl.class (zcl_im_impl4)

--> check_all_data

screen group fields

Filter dependent Standard BADI's

Requirement: Enhance the XD01 transaction for plugging additional fields:

BADI's: customer_add_data_cs (Filter dependent)

Filter type --> cust_scgr (Screen group)

customer_add_data

1. Define the custom screen group in Customization settings: (SPRO)


Screen group --> Z1

Subscreen no --> 4000

Pushbutton function code--> FC1

2. Implement the BADI customer_add_data'

method IF_EX_CUSTOMER_ADD_DATA~CHECK_ADD_ON_ACTIVE .

if i_screen_group = 'Z1'.

e_add_on_active = 'X'.

endif.

endmethod.

3. Plug the additional fields in the standard table 'KNA1'

Base table: KNA1 Append structure: zcmp

Fields:

zzcompname zcompname char

zzcompaddr zcompaddr char

4. Implement the standard BAdi 'customer_add_data_cs'

method IF_EX_CUSTOMER_ADD_DATA_CS~GET_TAXI_SCREEN .

if i_taxi_fcode = 'FC1'.

e_screen = '4000'.

e_program = 'ZCUSTPROG'.

endif.

endmethod.

5. Executable Program: zcustprog

call screen 4000. (4000 should be created as subscreen)

Layout:
Standard BADI's:

Definition of badi, Badi Triggering(Calling BADI) ---> SAP

Implementation of BADI --> Developer

Custom BADI Creation: (New BADI / Kernel BADI):

Definition, Implementation, Triggering ---> Developer

1. Create Enhancement Spot--> Container of BADI definitions

2. Create BADI definition as part of Enhancement Spot

a) BADI Name

b) BADI Interface

c) BADI Interface methods

d) Single Use / Multiple use

e) filter dependent / filter independent

3. Create BADI Implementations as part of Custom Enhancement Implementations

4. Trigger the BADI

Procedure:

1. Declare the reference for BADI definition

2. Create the object for BADI definition (get badi...)


3. Using the Object, Call the appropriate BADI interface method

(Call badi....)

Example 1: Custom Badi (Filter Independent, Multiple use)(EHP7)

Step 1: create/consider Enhancement spot (zespot)

Step 2 : Create BADI definition as part of Enhancement spot (zcstbadi)

badi interface --> zif_ex_cstbadi

badi interface methods --> m1

Step 3 : Create First Badi implementation

Enhancement implementation :- zespot_enhimpl

Badi implementation : zcstbadiimpl1

Badi implementation class : zcl_im_cstbadiimpl1

Implementation for method 'm1':

method ZIF_EX_CSTBADI~M1.

message 'First Implementation' type 'I'.

endmethod.

Step 4: Create Second Badi implementation

Enhancement implementation :- zespot_enhimpl

Badi implementation : zcstbadiimpl2

Badi implementation class : zcl_im_cstbadiimpl2

Implementation for method 'm1':

method ZIF_EX_CSTBADI~M1.

message 'Second Implementation' type 'I'.

endmethod.

Step 6: Trigerring the custom badi

data ob type ref to zcstbadi.

get badi ob.


call badi ob->m1.

30th Aug Summary :

Screen Enhancements using BADI's: (XD01)

CUSTOMER_ADD_DATA_CS --> filter dependent ---> cust_scgrp

Requirements :-

1. SPRO ---> custom screen group --> Z1 ---> button (appl.toolbar) --> invisible

2. check_add_on_active ---> customer_add_data --> button --> visible(appl.toolbar)

3. KNA1 --> append str --> zCMP --> 2 fields --> activate

4. get_taxi_screen ---> customer_add_data_cs ---> analysis

5. custom program ---> design subscreen with own fields

6. implement get_taxi_screen --->

7. implementation ---> fltval ---> Z1

std.badi :-

badi definition ---> SAP

badi interface --> SAP

filter type --> SAP

badi implementation --> developer

badi impl.class ---> developer

filter value --> developer

badi triggering ---> SAP as part of transaction based on user actions

custom.badi :-

badi definition ---> developer

badi interface --> developer

filter type --> developer

badi implementation --> developer

badi impl.class ---> developer


filter value --> developer

badi triggering ---> developer

t-code:- spro --->

t134 ---> material types --> 100

mp01

se51 --->

Custom Filter Dependent BADI's in EHP7 (Kernel Badi's):

Example 1: Filter Dependent BADI s  Single Filter Type

1. Create / consider enhancement spot (zespot)

2. Create badi definition as part of above enhancement spot

badi definition : zftbadi

badi interface : zif_Ex_ftbadi

Badi Filter names : uname

Filter type : c

Select automatic through dictionary , provide dictionary object XUBNAME

3. Create first badi implementation

enhancement implementation : zespot_enhimpl

badi implementation name : zftbadiimpl1

badi implementation class : zcl_im_ftbadiimpl1

badi filter values : SAPUSER, ACCOUTANT

4. Create second badi implementation

enhancement implementation : zespot_enhimpl

badi implementation name : zftbadiimpl2

badi implementation class : zcl_im_ftbadiimpl2

badi filter values : ACCOUNTANT1, ACCOUNTANT2


5. Create third badi implementation

enhancement implementation : zespot_enhimpl

badi implementation name : zftbadiimpl3

badi implementation class :zcl_im_ftbadiimpl3

badi filter values : SAPUSER

Fallback class implementation (implemented as part of BADI definition):

method ZIF_EX_FTBADI~M1.
message 'Default implementation' type 'I'.
endmethod.

6. Trigger custom filter dependent badi as part executable program/std.badi


implementation/customer-exit implementation/source code enhancement implementation

Executable Program:

REPORT ZTRIGGER_FTBADI.

data ob type ref to zftbadi.


*get badi ob. "syntax error

*get badi ob filters uname = sy-uname. "(or)


*get badi ob filters uname = 'ACCOUNTANT'. "(or)
*get badi ob filters uname = 'ACCOUNTANT1'. "(or)
get badi ob filters uname = 'ACCOUNTANT3'.

call badi ob->m1.

Standard Filter dependent badi's:

filter type ---> provided by SAP

filter values --> Developer (implementation)

Custom filter dependent badi's

filter type --> provided by developer

filter values --> Developer (implementation, Triggering the badi)

Example 2: Filter Dependent BADI s  Multiple Filter Type

1. Create / consider enhancement spot (zespot)

2. Create badi definition as part of above enhancement spot

badi definition : zfltbadi

badi interface : zif_Ex_fltbadi

Badi Filter name : uname

Filter type : c

Select no check

Create one more BADI filter type:

Badi Filter name : pwd

Filter type : c

Select no check

3. Create first badi implementation


enhancement implementation : zespot_enhimpl

badi implementation name : zfltbadiimpl1

badi implementation class : zcl_im_fltbadiimpl1

badi filter values :

Combination 1: Uname  U1, PWD  P1

Combination 2: Uname  U2, PWD  P2

4. Create second badi implementation

enhancement implementation : zespot_enhimpl

badi implementation name : zfltbadiimpl2

badi implementation class : zcl_im_fltbadiimpl2

badi filter values : ACCOUNTANT1, ACCOUNTANT2

badi filter values :

Combination 1: Uname  U3, PWD  P3

5. Trigger custom filter dependent badi as part executable program/std.badi


implementation/customer-exit implementation/source code enhancement implementation

Executable Program:

REPORT ZTRIGGER_FLTBADI.

data ob type ref to zfltbadi.

*get badi ob. "syntax error


*get badi ob filters uname = 'U1'. "syntax error
*get badi ob filters uname = 'U1' pwd = 'P3'.
*get badi ob filters uname = 'U1' pwd = 'p1'.
get badi ob filters uname = 'U3' pwd = 'P3'.

call badi ob->m1.

31st Aug Summary :

filter type ---> cust_scgr --------------> data element


va01 ---> create sales order --> std. badi

cmod ---> include --->logic to trigger custom badi

se19 ---> std badi interface method impl ---> logic to trigger badi

custom badi ===> m1 ---> business logic

impl1 ---> 20% ---> sales representive --> u1,u34

impl2 ---> 25% --> manager --> u2

impl3 --> 30 % --> sr.manager --> u3

impl4 ---> 40% --> director --> u4

impl5 ---> end users ---> u5,u6,u7.... ---> 10 % ---> fallback class impl.

---> badi def...

mm01 ---> std.customer exit --> std. badi

IDOCS

ALE/IDOCS

ALE  APPLICATION LINK ENABILING

IDOCS INTERMEDIATE DOCUMENT

ALE is a technology of SAP used for implementing distributed processing.

Distributed process means sharing the process between multiple systems.

NOTE

ALE is a technology used for generating, distributing and posting the idoc s.

IDOC is a SAP owns format used for carrying a data (container of data) from one place to other
place.

IDOC RELATED OBJECTS:


1. Message Type: It indicates the type of data stored in the IDOC . Message type is
client independent.

Transaction code  WE81 .

Table  Edmsg (Logical message types).

2. Idoc type: it is a template which is a collection of segments. A segment is a structure


which is the collection of fields.

Note: Each Message type can be associated with multiple IDOC TYPES .

Each idoc types differ in number of segments and fields.

Transaction code WE30 .

Table  EDIDO (Value table for Idoc types).

3. Idoc: Idoc is a runtime component which holds the data. Table  EDIMSG (Output
Types and Assignment to IDoc Types).

4. Logical systems: These are the alternative names provided for the systems involved
in IDOC communication. A logical system is a client independent object.

Transaction code  BD54 .

Table  TBDLS (Logical system).

Note: The No. of Logical systems depends on the No. of systems involved in IDOC
Communication.

5. Port number:- it is a unique number used for identify your resource on the system.

Transaction code  WE21 .

Table  EDIPO (Table for description of ports for EDI).

6. Partner profile:- contains the information of partner system. Partner profile is


always created on top of partner logical system. It is client dependent object.

A partner profile for sender is a collection of receiver logical system, message type,
port number and IDOC type.

A partner profile for receiver is a collection of sender logical system, message type
and inbound process code. It is client dependent object.

Transaction code WE20 .


Table  EDPP1 (EDI Partner (general partner profiles - inbound. and outbound)).

7. Model view: It binds the sender and receivers logical systems along with the
message types.

Transaction code BD64 .

Table  TBD00/ TBD05 (Distribution model for message types).

8. Selection program (outbound program):- It is always executed in the sender system.


It is responsible for reading the data from sender database and generating the
IDOC s , distributing the idoc s.

Example:

Objects Transaction Selection program

Material BD10 RBDSEMAT

Customer BD12 RBDSEDEB

VENDOR BD14 RBDSECRE

9. Posting program (inbound program):- This is executed at receiver side and it is


responsible for reading the incoming IDOC data & posting (updating) the same to
the receiver database.

The inbound program can be the function module / it can be work flow task.

10. Process code:- It acts as a identifier for inbound program. It is generally the first
four characters of message type .

Transaction code  WE42 (inbound process code).

Transaction code WE47 (outbound process code).

Scenario:

Distributing master data (material data) from one client to another client through IDOC s
Setting at sender side:

1. Create two logical systems, one for sender and another on behalf of receiver.

Transaction code: BD54.

Note:

Since logical systems are client independent we can create both logical systems
in one client itself, as both clients belongs to same server.

2. Assign logical systems to client (scc4).

3. Create RFC destination for holding the details of receiver client (sm59).

4. Create TRFC port (we21).

5. Identify message type for material master (we81).

6. Identify appropriate idoc type for material master (we82).

7. Create model view (bd64).

8. Assign message types to model view.

9. Create partner profile for sender (we20).

10. Assign outbound parameters (we20).

14. Identify material/s to be distributed.

15. Run the selection program for distributing materials (BD10).

16. Check the idoc s generated (we02/we05/we09).

17. Process the idoc s if any errors in distributing.

Settings at receiver side:

11. Create partner profile for receiver.

12. Identify inbound process code for material master (we42).

13. Assign inbound parameter (we20).

18. Check the idoc received.

19. Process the idocs if any error s in posting setting at sender side.
Structure of IDOC / Components of IDOC:

Every IDOC contains the following 3 records.

1. Control record: Table (EDIDC).

2. Data record: Table (EDID2).

3. Status record: Table (EDIDS).

1. Control record:

It is like a envelope of a letter which contains the sender and receiver s information
which includes part er u er, essage type, ido type, port u er, et ….. .

2. Data record:

It contains two sections admin section and data section.

i. Admin section contains: the segment information like segment name and
segment number.

ii. Data section: It contains the actual data of idoc.

3. Status record:

It contains status of the idoc during it s journey from source to destination. Each
checkpoint is associated with status code.

All the status codes can be viewed in Transaction code: WE47.

00-49 sender side status code.

50-75 receiver side status code.

IDOC Filtering:

It is a processing of filtering the IDOC s before distributing to the receivers. It can be filtered in 2
ways.

a) Data level filtering b) segment level filtering

Data level filtering: This is configured as part of Model View in Sender System.

This is configured at sender side module view level.


Whenever the selection program is executed, SAP retrieves the data from corresponding tables
and generates the appropriate number of Master Idoc s. The No. of master Idoc s corresponds
to the no of objects specified in the selection-screen of selection-program. These master idoc s
are stored at operating system level. These master idoc s are sent to ALE layer which is
responsible for executing the filter conditions maintained at model view level.Based on the
filter conditions, SAP generates the appropriate no of communication Idoc s which are sent to
communication layer which is responsible for distributing the Idoc s to the configured
recipients.

This communication Idoc s are stored at database level.

Segment Filtering (BD56):

It is a process of filtering the segment/s between the sender and receiver.

The pre-requisite for the segment filtering is the partner profiles of both sender and receiver
must exist in the sender system. It is always configure at sender side.

Make sure, the above partner profile 830SENDL is also created in 800 client (WE20).
Mandatory Segments cannot be filtered.
Processing error IDOC s:

Procedure: Analyze the error of IDOC & identify whether it is functional or technical issue. If it is
a functional issue, the functional consultant should configure the required settings and if it is a
technical issue, the ABAP consultant should address the same and then the ABAP consultant
can process the error IDOC by using Transaction code -> BD87/WE19.

BD87 Processes the existing error idoc without generating new IDOC.

WE19 ignores the existing error IDOC & generates new IDOC.

LSMW using IDOC:

LSMW tool is used for migrating the data from legacy system to SAP.

In LSMW using IDOC, the LSMW tool picks the data from legacy system, generates IDOC s using
ALE technology and distributes the IDOC s to the configured SAP system.

Legacy system LSMW IDOC SAP R/3

In LSMW using IDOC, we require only one set of ALE objects which are specific to receiver.

Receiver related objects:

1. Create logical system (LSMWREC)

2. Assign logical system to client. (LSMWREC800)

3. Create file port.(LSMWRECPRT)

4. Create partner profile. (LSMWREC)

5. Assign inbound parameters. (message type-matmas, inbound process code-matm).


LSMW SETTINGS:

Create project (830LIPRJ), sub project (830LISPRJ) and object (830LIOBJ ).

Configure the idoc inbound processing (settings->IDoc inbound processing)


Click on Activate IDOC Inbound Processing .

Click on execute and configure the steps:

1. Maintain object attribute: In this, choose the type of technique as IDOC and provide
appropriate message type and IDOC type.

2. Maintain source attribute: In this, we declare the structures corresponding to the


number of flat files.

3. Maintain source fields: In this, we need to declare the fields for the above structure
corresponding to the flat file fields.

4. Maintain structure relation: In this, we need to map the custom source structure with
the corresponding segment structure.

5. Maintain field mapping and conversion rule: In this, we need to MAP the fields of the
custom structure with the fields OF standard segment structure. We can also define the
rules FOR the mapped fields.

6. Maintain fixed values translations user define routines: In this, we implement the rules
which are defined above.

7. Specify files: In this, we need to specify the path of the files AND ITS PROPERTIES.

8. Assign files: In this, map the uploaded files to the corresponding source structures.

9. Read data: In this, data is read from flat file and it is stored in application server file
(LSMW.READ).

10. Display read data: In this, data is displayed from LSMW.READ file.

11. Convert data: In this, rules are executed on LSMW.READ file and converted data is
stored in LSMW.CONV file.

12. Display converted data: In this, data from LSMW.CONV file is displayed.

13. Start IDOC generation: In this, LSMW.CONV file is sent for IDOC generations.

14. Start IDOC processing: It processes the generated IDOCS and distributes to the
receiver.

15. Create IDOC Overview: It takes the control to WE02 and displays the generated IDOCS.

16. Start IDOC Follow-up: In this, we can re-process the error IDOC s (if-any) after
configuring the functional settings.

LSMW using BAPI:

LSMW tool is used for Migrating the data from legacy system to SAP.
In LSMW using BAPI, the LSMW tool picks the data from legacy system, generates IDOC s using
ALE technology and BAPI API method and distributes the IDOC s to the configured SAP system.

In LSMW using BAPI, we require only one set of ALE objects which are specific to receiver.

Receiver related objects:

1. Create logical system (830LSMWREC)

2. Assign logical system to client. (830LSMWREC800)

3. Create file port.(830LSMWPRT)

4. Create partner profile. (830LSMWREC)

5. Assign inbound parameters. (message type-matmas, inbound process code-bapi).

LSMW SETTINGS:

Create project (830LBPRJ), sub project (830LBSPRJ) and object (830LBOBJ ).

Configure the idoc inbound processing (settings->IDoc inbound processing)


Click on Activate IDOC Inbound Processing .

Click on execute and configure the steps:

1. Maintain object attribute: In this, choose the type of technique as BAPI and provide
business object type BUS1011 and method as Create , SAP proposes corresponding
message type (BANK_CREATE) and IDOC type (BANK_CREATE01).

2. Maintain source attribute: In this, we declare the structures corresponding to the


number of flat files.

3. Maintain source fields: In this, we need to declare the fields for the above structure
corresponding to the flat file fields.

4. Maintain structure relation: In this, we need to map the custom source structure
with the corresponding segment structure.

5. Maintain field mapping and conversion rule: In this, we need to MAP the fields of
the custom structure with the fields OF standard segment structure. We can also
define the rules FOR the mapped fields.

6. Maintain fixed values translations user define routines: In this, we implement the
rules which are defined above.

7. Specify files: In this, we need to specify the path of the files AND ITS PROPERTIES.
8. Assign files: In this, map the uploaded files to the corresponding source structures.

9. Read data: In this, data is read from flat file and it is stored in application server file
(LSMW.READ).

10. Display read data: In this, data is displayed from LSMW.READ file.

11. Convert data: In this, rules are executed on LSMW.READ file and converted data is
stored in LSMW.CONV file.

12. Display converted data: In this, data from LSMW.CONV file is displayed.

13. Start IDOC generation: In this, LSMW.CONV file is sent for IDOC generations.

14. Start IDOC processing: It processes the generated IDOCS and distributes to the
receiver.

15. Create IDOC Overview: It takes the control to WE02 and displays the generated
IDOCS.

16. Start IDOC Follow-up: In this, we can re-process the error IDOC s (if-any) after
configuring the functional settings.

Custom IDOC Creation:

We go for custom IDOC creation whenever we need to distribute customer specific data. For
this, we need to create all the IDOC related objects from the scratch.

Settings at sender side:

Step 1: Create two logical systems (BD54).

Step 2: Assign logical systems to client (SCC4).

Step 3: Create RFC Destination (SM59).

Step 4: Create TRFC port (WE21).

Step 5: Creates segment (WE31).

Step 6: Creates IDOC type (WE30).

Step 5: Create the message type (WE81).

NOTE

If the segment is a qualified segment, than the first field value of the SEGMENT will be
displayed as part of data record when the IDOCS are displayed.
Whenever a segment is created, a corresponding dictionary structure gets created with the
name of the segment.

Step 8: Plug the segment to the IDOC type (WE30).

Step 9: link the message type and IDOC type (WE82).

Step 10: Create the model view (BD64).

Step 11: Assign message type to model view (BD64).

Step 12: Create partner profile for sender (WE20).

Step 13: Assign outbound parameters at partner profile level (WE20).

Settings at receiver side:

Step 14: Create partner profile for receiver (WE20).

Step 15: Create inbound program (function module).

Step 16: Link message type, IDOC type and function module (WE57).

Step 17: Register the function module as inbound (BD51).

Step 18: Create the process code (WE42).

Step 19: Assign inbound parameter at partner profile level (WE20).

Procedure for selection program:

1. Create a selection screen for accepting the range of employees, defaulting the
message type and a field for accepting receiver logical system.

2. Prepare the control record (EDIDC).

3. Prepare the data record. In this prepare the segment name in the admin section and
actual data of the IDOC. After preparing the data record, pass the control record as
well as data record as a parameter to the function module
IDOC_MASTER_DISTRIBUTE , it generates a communication IDOC and returns the
same in an internal table which is of type EDIDC .

Procedure for inbound program:

As part of inbound function module, there will be an internal table which carries the IDOC data.
We need to read this internal table corresponding to the segment and update the same to the
corresponding database table. If the update is successful, set the status code to 53 (application
document posted successfully) otherwise 51 (application document not posted successfully)

Change pointers:
- Change pointers are used for tracking the changes made to master data.

- To track these changes, change pointers must be activated at three levels.

- The 3 levels they are:

1. Globally (BD61).

2. Message type level (BD50).

3. Field level (BD52).

RBDMIDOC (BD21):

It is the executable program which retrieves changes made to the master data and distributes
those changes to receivers.

Note:

Once change pointers are activated, the changes made to master data will be stored in
following tables.

1. CDHDR CHANGE DOCUMENT HEADER.

2. CDPOS CHANGE DOCUMENT ITEMS.

3. BDCP CHANGE POINTER.

4. BDCPS CHANGE POINTER STATUS.

Note: Whenever we run the program RBDMIDOC, SAP picks the data from above tables
and generates the appropriate no. of IDOC S and distributes these IDOC S to configure
receivers.

After distribution, the field PROCESS in the table BDCPS is set to X indicating that
the changes are distributed.

 Not distributed.

IDOC archiving:

It is a process of compressing the IDOC s which are not in use. The purpose of archiving is to
improve the performance of application server and also to increase the disk space.

The IDOC s which are not in use as to be deleted on the regular basis. The IDOC s cannot be
deleted directly, so we must archive it before deletion. Whenever an IDOC is archived, an
archive file will be generated which is an input for deleting the IDOCS.

To archive the IDOC s we need to configure the physical path, so that the archived files are
stored in that path.
Procedure for archiving:

RSEXARCA is a report program for archiving the IDOC.

RSEXARCR is report program for reading the IDOC archiving file.

RSEXARCL is a report program for reloading the IDOCs from an archive file.

RSEXARCD is a report program for deleting the IDOCs stored in the archive file.

Note: we can use the t-code SARA for archiving the IDOC s. This T-code will schedule the
program RSEXARCA in the background for archiving the IDOC s based on the variant input
values.

Note:

The IDOC S that are in error status cannot be archived.

RC1_IDOC_SET_STATUS is a report program for changing the status of the IDOC.

At Receiver side, we need to change the status to 68 and at sender side; we need to change the
status to 31 which indicates ERROR IDOC-NO FURTHER PROCESSING .

IDOC Reduction (Transaction code BD53):

- It is a process of creating a new message type from the existing message type.

- As part of this, all the corresponding IDOC types will be assigned to the new message
type automatically.

- As part of this new message type creation, we can select/deselect the required segment
and fields.

- Mandatory segments and fields cannot be deselected.

- This new message type needs to specify at relevant places.

Distributing transaction data through IDOC s: This is done by configuring Message control.

Transaction data  Pur hase Order data, Sales Order data, I voi e data…

Message Control in Idoc s:

- Message control is used for triggering outputs from applications and to control the
timing of output triggering

- It is generally configured for distributing transaction data through IDOC s.


- The master data IDOC s are triggered from selection programs and for triggering the
transaction data of an application we need to configure the message control in the
outbound parameters.
idoc types

inbound process code


model view

Port
SAP TO SAP using IDOC

SAP-NONSAP
Distrubuting Master IDOC - Material IDOC- Single Recipient-22nd Nov 2016 :

Requirement : Distributing material data(master data) from sender to receiver

sender :- 800 client , receiver --> 810 client

sapuser,sapabap123 sapuser,sapabap123

Steps at sender side :- (800)

1. Create two logical systems (tcode : sale/bd54)

(table : TBDLS / TBDLST)

8AMSEND, 8AMRECV

2. Assign logical systems to source and receiver clients (T-CODE : sale / scc4)

800 --> 8AMSEND

810 --> 8AMRECV

3. Create RFC destination (tcode : sale / sm59)

(table : RFCDES)

8AMIDOCRFCDEST

4. Create TRFC port (tcode : we21)

(table : EDIPO)

A000000057

5. Identify message type and idoc type for material idoc

MESSAGE TYPE :- (tcode : WE81)

(table : EDMSG)

business objects message type

material matmas

customer debmas

vendor cremas

p.o data orders


------

message type for material --> matmas

IDOC Type :- (t-code :- we30 --> creation

we82 --> to identify idoc types for a message type)

tables :- EDIDO (for idoc types)

EDIMSG (table for links between message type and idoc types)

business object message type idoc type release

material matmas matmas01 2.1

material matmas matmas02 2.2

material matmas matmas03 2.3

idoc type --> matmas05 (we82)

6. Create Model view (tcode : sale / bd64)

(table : TBD00)

8AMMODEL

7. Assign message type to model view (sale / bd64)

model view --> 8AMMODEL

sender --> 8AMSEND

receiver --> 8AMRECV

message type --> MATMAS

8. Create partner profile for sender (T-Code : we20)

(Table : EDPP1)

partner profile for sender --> receiver logical system +

outbound parameters

8AMRECV

9. Assign outbound parameters (T-code : WE20)


outbound parameters --> message type + receiver port + idoc type

--> MATMAS + A00000057 + MATMAS05

10. identify the objects (materials) which needs to be distributed

Standard material --> 100-100 (MARA,MAKT,MARC,MARD....)

Custom materials --> 8AMMAT1 (MARA,MAKT)

note :- check(confirm) whether above materials are not available in receiver client (810)

13. Run the selection program /outbound program FOR distributing the material data
through idoc

(program --> RBDSEMAT /

T-code --> BD10)

Object Selection program T-code

material RBDSEMAT BD10

customer RBDSEDEB BD12

vendor RBDSECRE BD14

-----

14. Check the idocs generated (t-code : we02/ we05)

15. If any error idocs are generated, analyse the error idoc and configure the functional
settings if required

16. Re-process the error idocs for distributing using t-code 'BD87'

Steps at receiver side (810) :-

11. Create partner profile for receiver (t-code : we20)

partner profile for receiver = sender logical system

+ inbound parameters

8AMSEND

12. Assign inbound parameters (we20)

inbound parameters = message type +

inbound process code


message type --> matmas, process code = matm

Identify the inbound processcode we42 ie MATM

17. Check the idocs received (we02 / we05)

18. If any error idocs are received, analyse the error idoc and configure the
functional settings if required

19. Re-process the error idocs for posting using 'BD87'

2nd Sep IDOC Objects :

800 client : (sender)

1. Create Two Logical Systems (8AMSEND, 8AMRECV1)

2. Assign Logical Systems to Sender Client and Receiver Client

8AMSEND --> 800 CLIENT

8AMRECV1 -> 810 CLIENT

3.Create RFC Destination (8AMIDOCDEST_810)

4. Create TRFC Port (A000000055)

5. Identify Message type --> MATMAS

6. Identify Idoc type --> MATMAS05

7. Create Model View --> 8AMMODEL

8. Assign Message type to Model View

sender --> 8AMSEND

receiver --> 8AMRECV1

msg type --> MATMAS

9. Create Partner profile for sender ---> 8AMRECV1

10. Assign outbound parameters for the above partner

message type ---> matmas

receiver port --> A000000055

idoc type ---> matmas05


14.Identify material/s to be distributed --> GST100, GST101, 100-100

15. Run the selection program for distributing materials (BD10).

16. Check the idoc s generated (we02/we05).

17. Process the idoc s if any errors in distributing

810 CLIENT : (receiver)

11. Create Partner profile for receiver ---> 8AMSEND

12. Identify inbound process code (WE42) --> MATM

13. Assign inbound parameters for the above partner

message type ---> matmas

inbound process code --> matm

18. Check the idoc received.

19. Process the idoc s if any errors in POSTING

2nd Sep Notes :

IDOC: (intermediate document)

IDOC --> Container of data which can be used to carry the data from one System to another
System (SAP / NON-SAP)

IDOC data --> can be master data / transaction data / customer specific data

To Configure, Generate, Distribute and Post the IDOC's , we use ALE Technology.

ALE --> Application Link Enabling

In case of std. Master data / std. Transaction data , idoc related objects are provided by SAP
itself.

In case of customer specific data, idoc related objects should be manually created by ABAP
consultants.

idoc related objects :- idoc type, segment, message type, selection/outbound program,
inbound process code, posting / inbound program...

Eg: material data

1. Message type --> indicates what type of data is stored inside idoc.
Business Objects Message Type

Material matmas

customer debmas

vendor cremas

purchaseorder(transaction data) orders

---- ----

customer specific data custom message type

t-code for message types --> WE81

table for message types --> EDMSG

2. idoc type --> is a collection of segments(structure)

--> Each segment is a collection of fields

--> One message type can be associated with 'n' of idoc types

--> is a design time component which only provides template of fields

--> it provides the organized structure of the fields related to business object

Business object Message type idoc type release

Material matmas matmas01 4.1

Material matmas matmas02 4.2

t-code for creating custom idoc type --> we30

t-code for viewing the link between message type and idoc type --> we82

table for viewing the link between message type and idoc type --> EDIMSG

table for idoc types --> EDIDO

3.Logical System : It is a unique name(alias name) assigned for the sender and receiver system
involved in idoc communication. They are client independent.

t-code : SALE / BD54

table : TBDLS / TBDLST

4. RFC Destination: It stores the details of receiver system like receiver ipaddress/hostname,
client no and logon credentials.
T-code: SALE / SM59

table: RFCDES

5. TRFC port (Transactional RFC port) : It is a unique no generated and it is used for identifying
a resource on the target system.

TRFC port is created on behalf of receiver and it is created on TOP of RFC destination.

T-code : WE21

Table: EDIPO

6. Model View: Is an object which stores sender and Receiver's info along with message type
and idoc filtering configuration.

T-code: SALE / BD64

Table: TBD00

7. Partner Profile: Stores information about partner system. It is created on top of partner
logical system. It is client dependent.

partner profile for sender --> receiver logical system +

outbound parameters (message type + idoc type + port no)

T-code: WE20

Table: EDPP1

8. Inbound process code : It is an identifier for inbound program. i.e it provides the link to the
inbound program for reading the incoming idoc. It is generally first four characters of
message type.

T-code: WE42
enhanement-idoc,bapi,transaction,table

screen groups in xd01

Example: Enhancing Customer Master Transaction (XD01) to Capture Additional data specific
to business and also enhance the corresponding standard IDOC related to customer master to
distribute customer specific fields through IDOC

Screen Enhancements using BADI:

1. Enhance the base table of customer master (KNA1)


Append Structure: YCOMPETITOR

Additional Fields:
yycompname ycompname char 20
yycompaddr ycompaddr char 20

2. Identify the screen enhancements related to customer master (XD01)

BADI s: CUSTOMER_ADD_DATA AND


CUSTOMER_ADD_DATA_CS

3. As part of implementing above BADI s, Read the documentation to understand what


methods has to implemented and also the pre-requisites before implementing the
BADI methods.

Pre-requisites:

Create Custom Screen group in customization of customer master(SPRO T-code)

Screen Group  Y1 ( 8 AM SCREEN GROUP)


Label Tab pages
Subscreen - 4000
Fctcode  FC1
Description  Competitor Fields

Actual BADI Implementations: (SE19)

a) Implement the method check_add_on_active of the badi


CUSTOMER_ADD_DATA

BADI Implementation: ZCSTIMPL

Enhancement Implementation: ZCSTENHIMPL

method IF_EX_CUSTOMER_ADD_DATA~CHECK_ADD_ON_ACTIVE.
if i_screen_group = 'Y1'.
e_add_on_active = 'X'.
endif.
endmethod.

b) Now, Create a custom module program (ZMYCSTPROG) with subscreen 4000 and
place above customer specific fields
c) Implement the method get_taxi_screen of the badi CUSTOMER_ADD_DATA_CS

BADI Implementation: ZCSTIMPL_CS

Enhancement Implementation: ZCSTENHIMPL_CS

method IF_EX_CUSTOMER_ADD_DATA_CS~GET_TAXI_SCREEN.
if i_taxi_fcode = 'FC1'.
e_screen = '4000'.
e_program = 'ZMYCSTPROG'.
endif.
endmethod.

Note: Before implementing the above BADI method, In SE19 Properties tab provide
the filter value Y1

d) Activate and test by creating new customer in XD01 transaction. As part of this,
capture data for customer specific fields. Check the entry in KNA1 table.

IDOC Extension:

STANDARD IDOC: standard segments (std.fields)

ENHANCED IDOC: standard segments (std.fields) + custom segment (customer specific fields)

Requirement: Enhance customer IDOC to plug additional segments

sender --> 800


receiver --> 810

Step 1: Add customer specific fields in the db table (APPEND STRUCTURE OR CUSTOMER
INCLUDE)
Table: KNA1

Append structure: ZCMP

Additional Fields:
zzcompname zcompname char 20
zzcompaddr zcompaddr char 20
Step 2: Enhance the standard transaction (XD01) to display the above additional fields.

NOTE: use the badi 'customer_add_data_cs' and 'customer_add_data'

Step 3: create the additional segment/s (we31).

Segment name: YCMPSEG


Fields:
zcompname zcompname
zcompaddr zcompaddr

save and release the segment

Step 4: Create the extended IDOC type with additional segment (we30).

Extended IDOC type: YCMPIDOC (LINKED WITH BASIC TYPE 'DEBMAS05')

Note: plug the above segment (YCMPSEG) under root segment 'E1KNA1M'
Save and release the extended idoc type
Step 5: link all objects (message type + basic idoc type + extended idoc type + release) (we82).
debmas + debmas07 + YCMPIDOC + 480

ALE SETTINGS:

Step 6: specify extended idoc type in outbound parameters (we20).

Step 7: identify the enhancements (if available) in the standard selection program for capturing
the additional fields data while generating idocs.

Selection program: RBDSEDEB (BD12)

Package: CGV

Enhancement (Customer-exit): VSV00001

Function exits:
EXIT_SAPLVV01_001 --> Sender side (logic for retrieving additional data and appending to
standard IDOC data)

EXIT_SAPLVV02_001 --> Receiver side (logic for reading incoming data from customer specific
segments and updating the same to the relevant tables)

Implement the above two function exits by assigning the customer exit to a project using
CMOD t-code

Sender side enhancement program:

types : begin of ty_kna1,


zzcompname type zcompname,
zzcompaddr type zcompaddr,
end of ty_kna1.

data : wa_kna1 type ty_kna1.

data : wa_data type edidd.


data : wa_e1kna1m type e1kna1m,
wa_mapping type ycmpseg.

case segment_name.
when 'E1KNA1M'.
read table idoc_data into wa_data
with key segnam = 'E1KNA1M'.
wa_e1kna1m = wa_data-sdata.

select single zzcompname zzcompaddr from kna1


into wa_kna1 where kunnr = wa_e1kna1m-kunnr.
if sy-subrc eq 0.
wa_mapping-zcompname = wa_kna1-zzcompname.
wa_mapping-zcompaddr = wa_kna1-zzcompaddr.

wa_data-segnam = 'YCMPSEG'.
wa_data-sdata = wa_mapping.
append wa_data to idoc_data.
endcase.

idoc_cimtype = 'YCMPIDOC'.

Receiver side enhancement program:


data : wa_idoc_data type edidd,
wa_mapping type ycmpseg.

loop at idoc_data into wa_idoc_data.


case wa_idoc_data-segnam.
when 'YCMPSEG'.
wa_mapping = wa_idoc_data-sdata.
update kna1 set zzcompname = wa_mapping-zcompname
zzcompaddr = wa_mapping-zcompaddr.
endcase.
endloop.

Activate the customer-exit implementation and generate the IDOC using the t-code BD12 ,
provide customer no as input, output type (message type), receiver logical system. Now, in the
IDOC generated, check whether custom segment is plugged in the data record of the IDOC.

6th Sep :

Sender side :-

Structure of idoc :-

sender side :-

control record --> edidc ---> work area --> prepared by developer

data record --> edid2 / edid3 /edid4 (tables)

--> edidd (structure)

--> internal table based on EDIDD --> prepared by developer

a) admin section

i) segment name --> developer

ii) segment no --> generated by SAP in the runtime

b) data section --> holds actual idoc data

--> concatenated data retrieved from dataBASE

-->'sdata' field --> contains concatenated data(empno+ename+empdesig)

status record --> dynamically generated by SAP

logic for concatenating data into 'SDATA' field :-


1. get data from database fields and store the same in corresponding fields

2. declare work area based on segment structure and assign the retrieved data to
segment work area fields

3. Assign segment work area to 'SDATA' field

Fields based on database table :-

lv_empno --> 3 (integer)

lv_ename --> raju

lv_empdesig --> ceo

Work area based on structure :-

work area based on segment structure(wa_emp)

wa_emp-empno = lv_empno.

wa_emp-ename = lv_ename.

wa_emp-empdesig = lv_empdesig.

Assignment :-

sdata = wa_emp.

custom idoc steps :

standard idoc ---> material

standard idoc objects :- message type (matmas)

idoc type(matmas05)

segments(e1maram,e1maktm,e1marmm)

selection program (RBDSEMAT) (bd10)

inbound process code (MATM)

inbound program(idoc_input_matmas01)

Custom IDOC Creation and Distribution:

sender : 800 Receiver : 810

Settings at sender side :


1. Consider a db table in sender client

table : zidocemp

fields :-

mandt mandt clnt

empno zempno int4

ename zename char10

empdesig zempdesig char20

empno's : 1,2,3,4

Steps at sender side (800) :

1. Create two logical systems

8AMSEND,8AMRECV1

2. Assign logical systems to client

8AMSEND --> 800

8AMRECV1 --> 810

3. Create rfc destination

8AMIDOCDEST_810

4. create tRFC port

A000000067

5. Create segment (we31)

ZEMPSEG

fields :

empno zempnum char10

ename zename char10

empdesig zempdesig char20

release the segment (initial screen, choose edit-set release) and


save
Note: As part of segment creation, if we select the checkbox
'qualified segment' and when the idocs are displayed, the qualifier value

(first field value of the segment) will be suffixed with the segment
name.

6. Create the idoc type (we30)

zempidoc

6.b) Assign segment/s to idoc type (we30)

save and release the idoc type

Note: As part of associating segments with idoc type, we need to


specify min.no and max. no which controls the no. of copies of the
segment

when the idoc is generated. We get multiple copies of the


segments only, when the segment data is maintained in multiple
languages.

7. Create the message type (we81)

EMPMSG

8. Assign message type to idoc type (we82)

MESSAGE TYPE IDOC TYPE RELEASE

EMPMSG ZEMPIDOC 700

9. Create Model view (bd64)

EMPMODEL

10. Assign message type to model view (bd64)

SENDER --> 8AMSEND

RECEIVER --> 8AMRECV1

MESSAGE TYPE --> EMPMSG

11. Create Partner profile for sender (we20)

8AMRECV1

12. Assign outbound parameters (we20)

message type --> EMPMSG


portno --> A...067

idoc type --> ZEMPIDOC

13. Create selection program / OUTBOUND


PROGRAM(ZSENDEMPLOYEEIDOC) (by harish for creating outbound
prosses code for sender we41)

Procedure : 758745

1. Create the selection screen for reading range of primary key fields
(empno), default message type(EMPMSG) ,and a field for reading partner
logical system(8AMRECV)

2. Prepare control record of type 'EDIDC'. As part of this, set


message type, idoc type....

3. Retrieve the corresponding data from the base table/s and


store the same in the internal table

4. Process (loop) the internal table.

a) As part of this , prepare work area of type 'EDIDD' in which set


the fields 'segnam' and 'SDATA' and append the work area to the internal
table of type 'EDIDD'

b) Pass the 'EDIDD' internal table and 'EDIDC' internal


table(empty) to the function module 'MASTER_IDOC_DISTRIBUTE' which
generates communication idocs and returns the same to the internal
table of type 'EDIDC'.

5. Display the communication idocs for reference.

Sender program :-

report zsendemployeeidoc.

REPORT ZSENDEMPLOYEEIDOC.

REPORT ZSENDEMPLOYEEIDOC.

*** SELECTION SCREEN FOR ACCEPTING THE USER INPUT ***

data : p_empno type zidocemp-empno.

selection-screen begin of block b1 with frame title abc.

select-options : so_empno for p_empno.

parameters : p_mestyp type edmsg-msgtyp


obligatory default 'EMPMSG',

p_logsys like tbdls-logsys.

selection-screen end of block b1.

initialization.

abc = 'SEND EMPLOYEE'.

start-of-selection.

****** PREPARE CONTROL RECORD ****

data : ls_ctrl_rec type edidc.

ls_ctrl_rec-rcvprt = 'LS'.

ls_ctrl_rec-rcvprn = p_logsys.

ls_ctrl_rec-mestyp = p_mestyp.

ls_ctrl_rec-idoctp = 'ZEMPIDOC'.

***** END OF CONTROL RECORD ****

* prepare master idoc data

data : ls_data_rec type edidd,

ls_comm_idocs type edidc.

data : lt_data_rec type table of edidd,

lt_comm_idocs type table of edidc.

types : begin of ty_emp.

include structure zidocemp.

types end of ty_emp.

data : lt_emp type table of ty_emp,

ls_emp type ty_emp.

data ls_emp_seg type zempseg.

***** READ THE APPN DATA FROM DB ****

select * from zidocemp into table lt_emp


where empno in so_empno.

if sy-subrc eq 0.

loop at lt_emp into ls_emp.

clear ls_emp_seg.

ls_emp_seg-empno = ls_emp-empno.

ls_emp_seg-ename = ls_emp-ename.

ls_emp_seg-empdesig = ls_emp-empdesig.

clear ls_data_rec.

ls_data_rec-segnam = 'ZEMPSEG'.

ls_data_rec-sdata = ls_emp_seg.

append ls_data_rec to lt_data_rec.

* call F.M 'MASTER_IDOC_DISTRIBUTE' to generate


communication idocs

call function 'MASTER_IDOC_DISTRIBUTE'

exporting

master_idoc_control = ls_ctrl_rec

tables

communication_idoc_control = lt_comm_idocs

master_idoc_data = lt_data_rec.

if sy-subrc eq 0.

commit work.

refresh lt_data_rec.

endif.

endloop.
endif.

* Display generated communication idocs

if lt_comm_idocs is not initial.

loop at lt_comm_idocs into ls_comm_idocs.

write : / ls_comm_idocs-docnum.

endloop.

endif.

Settings at receiver side :- (810)

1. Create Partner profile for receiver (we20)

8AMSEND

Note : Create Function group for holding Function module


(zidocfgrp)

2. Create function module (ACTS AS inbound program) se37

ZREADEMPLOYEEIDO

Note: Copy the parameters(import,export,tables,exceptions...) of


material inbound F.M (idoc_input_matmas01) to the above custom
function module

3. Link message type and idoc type with the function module
(we57)

function module -> ZREADEMPLOYEEIDOC

function type ---> function module

basic type ---> ZEMPIDOC

message type --> EMPMSG

direction --> inbound

4. Register Function module as inbound (BD51)


function module ---> ZREADEMPLOYEEIDOC

input type ---> 1 (individual input)

5. Create inbound process code (we42)

EMPM

Navigation : provide process code (EMPM), description , choose


processing type

(processing by F.M), save, prompts for providing F.M --> provide


F.M IN THE DROPDOWN (ZREADEMPLOYEEIDOC), save

6. Assign inbound parameters (WE20)

message type --> EMPMSG

inbound process code --> EMPM

Receiver program :-

Procedure :

1. loop the incoming idoc internal table (IDOC_DATA)

2. Update each record of the internaltable to the corresponding


base table/s and set the status code to '53' (posted) and '51' (not posted).

Logic : (Function Module Source code)

data : wa_data type edidd,

wa_status type bdidocstat,

wa_emp_seg type zempseg,

wa_emp_table type zidocemp.

loop at idoc_data into wa_data.

case wa_data-segnam.

when 'ZEMPSEG'.

wa_emp_seg = wa_data-sdata.
move-corresponding wa_emp_seg to wa_emp_table.

endcase.

endloop.

modify zidocemp from wa_emp_table.

if sy-subrc eq 0.

wa_status-docnum = wa_data-docnum.

wa_status-status = 53.

wa_status-msgty = 'EMPMSG'.

append wa_status to idoc_status.

else.

wa_status-docnum = wa_data-docnum.

wa_status-status = 51.

wa_status-msgty = 'EMPMSG'.

append wa_status to idoc_status.

endif.

IDOC Filtering :

Filtering the idoc's :

1. data level filtering --> configured as part of model view (sender side)

8AMMAT100,P,ROH

8AMMAT101,F,AEM

8AMMAT102,P,FERT

8AMMAT103,I,COUP

8AMMAT104,O,P01
8ammat105,P,FERT

default: bd10 ---> 6 materials ---> 6 master idocs / 6 communication idocs

filter : filter cond ---> distribute ONLY those materials whose material type is either 'FERT' (or)
'COUP'

filter object ---> material type

filter values --> FERT/COUP

bd10 ---> 6 materials ----> 6 master idocs / 3 communication idocs

2. Segment level filtering (bd56)

pre-requisite: 1. partner profile of both sender and receiver should be in sender system

2. MANDATORY SEGMENTS CANNOT BE FILTERED (check in we30..)

client logical system partner profile(EDPP1)

sender 800 8AMSEND 8AMRECV1

receiver 810 8AMRECV1 8AMSEND

SEGMENT TO BE EXCLUDED ---> E1MAKTM ---> MATMAS05 ---> MATMAS

8AMMAT100 P PLM

8AMMAT101 F VKHM

8AMMAT102 P FERT

8AMMAT103 B COUP

8AMMAT104 W FOOD

8AMMAT105 P FERT
lsmw using idoc

LSMW(Legacy System Migration workbench):

LSMW Tool is used for migrating data from legacy system file to SAP.

LSMW Techniques :-

1. Direct input --> core abap

2. Batch input recording --> core abap

3. IDOC --> cross apps

4. BAPI --> cross apps

LSMW using IDOC :-

t-code : LSMW

Files (Contains material data) : d:\mara.txt, d:\makt.txt

mara.txt --> contains data related to segment 'E1MARAM'

--> Fields considered

--> MSGFN,MATNR,MTART,MBRSH,MATKL,MEINS,GEWEI
makt.txt --> contains data related to segment 'E1MAKTM'

--> Fields considered

--> MSGFN,SPRAS,MAKTX,SPRAS_ISO

Sender --> text file (D:\mara.txt,D:\makt.txt)

receiver --> SAP Client (800)

Interface --> LSMW Tool

Receiver Related objects :-

1. Create Logical system (LSMWREC)

2. Assign Logical system to client (LSMWREC -->800)

3. Create File Port (LSMWRECPRT)

4. Create Partner Profile (LSMWREC)

5. Assign inbound parameters

message type --> MATMAS

inbound process code --> MATM

LSMW.READ ---> LSMW.CONV

MAKT File: .text

005,E,THIS IS 8AMIDOCMAT100,EN

MARA File: .text

005,8AMIDOCMAT100,ROH,P,001,KG,KG
ENHANCEMENT FRAMEWORK CLASSIFICATION

Enhancement Framework: is the new technique provided by SAP for enhancing SAP repository
objects. As part of this, there are 4 types of enhancements.

1. Source code enhancements

2. Function group enhancements

3. Class enhancements

4. Kernel BADI s

Source code enhancements: It is the process of enhancing the standard SAP source code by
plugging customer specific source code. There are 2 types of source code enhancements.

a) Implicit source code enhancements

b) Explicit source code enhancements

Implicit source code enhancements: In this, the enhancements can be done in the source code
of the standard SAP Repository objects and for this SAP has provided the enhancement options
at the following areas

a) Begin and end of Subroutines, F.M's, methods

b) At the end of Include programs and Report programs


c) Inside the events

d) At the end of Visibility sections in the local class definition

Explicit source code enhancements: In this, the enhancement options have to defined and
implemented by Developer itself. It exists in two forms

a) Enhancement point: supports multiple implementations

Syntax:

enhancement-point <point name> spots <enhancement spot name>.

b) Enhancement section: supports single implementation

Syntax:

enhancement-section <section name> spots <enhancement spot name>.

statements.

end-enhancement-section.

Note: Whenever we implement enhancement-section, the code between enhancement-section


and end-enhancement-section will be ignored and instead it executes the code inside the
implementation.

Note: To implement Source code, function group and class enhancements, the object must be
opened in enhanceable mode.

Function Group Enhancements: In this, we can enhance standard function modules provided
by SAP. As part of this, we can do following enhancements

1. We can add additional parameters (Always Optional)


2. We can plug additional source code in the standard source code of the F.M based on
additional parameters.

Você também pode gostar