You are on page 1of 84

ABAP Objects

ABAP OOP

Definitions
Public attributes
Public attributes are defined in the PUBLIC section and can be viewed and changed from outside the
class. There is direct access to public attributes. As a general rule, as few public attributes should be
defined as possible.
PUBLIC SECTION.
DATA: Counter type i.

Private attributes
Private attributes are defined in the PRIVATE section. The can only be viewes and changed from within
the class. There is no direct access from outside the class.
PRIVATE SECTION.
DATA: name(25) TYPE c,
planetype LIKE saplane-planetyp,

Instance attributes
There exist one instance attribute for each instance of the class, thus they exist seperately for each object.
Instance attributes are declared with the DATA keyword.
Static attributes
Static attributes exist only once for each class. The data are the same for all instances of the class, and
can be used e.g. for instance counters. Static attributes are defined with the keyword CLASS-DATA.
PRIVATE SECTION.
CLASS-DATA: counter type i,

Public methods
Can called from outside the class
PUBLIC SECTION.
METHODS: set_attributes IMPORTING p_name(25) TYPE c,
p_planetype LIKE saplane-planetyp,

Private methods
Can only be called from inside the class. They are placed in the PRIVATE section of the class.

Constructor method
Implicitly, each class has an instance constructor method with the reserved name constructor and a static
constructor method with the reserved name class_constructor.
The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT
statement, while the class constructor is executed exactly once before you first access a class.
The constructors are always present. However, to implement a constructor you must declare it explicitly
with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING
parameters and exceptions. You must pass all non-optional parameters when creating an object. Static
constructors have no parameters.
Static constructor
The static constructor is always called CLASS_CONSTRUCTER, and is called autmatically before the clas
is first accessed, that is before any of the following actions are executed:
Creating an instance using CREATE_OBJECT
Adressing a static attribute using <classname>-><attrbute>
Calling a ststic attribute using CALL METHOD
Registering a static event handler
Registering an evetm handler method for a static event
The static constructor cannot be called explicitly.
Protected components
When we are talking subclassing and enheritance there is one more component than Public and Private,
the Protected component. Protected components can be used by the superclass and all of the subclasses.
Note that Subclasses cannot access Private components.
Polymorphism
Polymorphism: When the same method is implemented differently in different classes. This can be done
using enheritance, by redefining a method from the superclass in subclasses and implement it differently.

Syntax
Template for making a class
Delete the parts that should not be used
******************************************

* Definition part
******************************************
CLASS xxx DEFINITION.
*-----------------------------* Public section
*-----------------------------PUBLIC SECTION.
TYPES:
DATA:
* Static data
CLASS-DATA:
* Methods
METHODS:
* Using the constructor to initialize parameters
constructor IMPORTING xxx type yyy,
*

Method with parameters


mm1 IMPORTING iii TYPE ttt.
* Method without parameters
mm2.
* Static methods
CLASS-METHODS:
*---------------------------------------------------*
* Protected section. Also accessable by subclasses
*--------------------------------------------------PROTECTED SECTION.
*--------------------------------------------------* Private section. Not accessable by subclasses
*--------------------------------------------------PRIVATE SECTION.
ENDCLASS.
******************************************
* Implementation part
******************************************
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
ENDMETHOD.
METHOD mm1.
ENDMETHOD.
METHOD mm2.
ENDMETHOD.
ENDCLASS.

Template for calling a class


* Create reference to class lcl_airplane
DATA: airplane1 TYPE REF TO lcl_airplane.
START-OF-SELECTION.
* Create instance using parameters in the cosntructor method
CREATE OBJECT airplane1 exporting im_name = 'Hansemand'
im_planetype = 'Boing 747'.

* Calling a method with parameters


CALL METHOD: airplane1->display_n_o_airplanes,
airplane1->display_attributes.

Subclass
CLASS xxx DEFINITION INHERITING FROM yyy.

Using af class as a parameter for a method


The class LCL_AIRPLANE is used as a parameter for method add_a_new_airplane:
METHODS:

add_a_new_airplane importing im_airplane TYPE REF to lcl_airplane.

Interfaces
In ABAP interfaces are implemented in addition to, and independently of classes. An interface only has a declaration part, and
do not have visibillity sections. Components (Attributes, methods, constants, types) can be defined the same way as in classes.
Interfaces are listed in the definition part lof the class, and must always be in the PUBLIC

SECTION.
Operations defined in the interface atre impemented as methods of the class. All methods of the
interface must be present in the
implementation part of the class.
Attributes, events, constants and types defined in the interface are automatically available to the
class carying out the implementation.
Interface components are adresse in the class by <interface name>~<component name>

Example of how to implement an interface:


INTERFACE lif_document
DATA:
author type ref to lcl_author.
METHODS: print,
display.
ENDINTERFACE.

CLASS lcl_text_document DEFINITION.


PUBLIC SECTION.
INTERFACES lif_document.
METHODS display.
ENDCLASS.
CLASS lcl_text_document IMPLEMENTTION.
METHOD lif_document~print.
ENDMETHOD.
METHOD lif_document~display
ENDMETHOD.
METHOD display.
ENDMETHOD.
ENDCLASS.
REPORT zzz.

DATA: text_doc TYPE REF TO lcl_document.


Start-of-selection.
CREATE OBJECT text_doc.
CALL METHOD text_doc->lif_document~print.

CALL METHOD text_doc->lif_document~display.


CALL METHOD text_doc->display.
Events
For events of controls, refer to How to use controls.
Events can only have EXPORTING parameters
When an event is triggerede, only those events handlers

that have registred themselves using SET

HANDLER by this point of runtime are


executed. You can register an event using ACTIVATION 'X' and derigert it by using ACTIVATION
'SPACE'.
Defining events:
CLASS <classname> DEFINITION.
EVENTS: <event> EXPORTING VALUE (<ex_par>) TYPE type.
CLASS <classname> IMPLEMENTATION.
METHOD <m>:
RAISE EVENT <event> EXPORTING <ex_par> = <act_par>.
Handling events:
CLASS <classname> DEFINITION.
METHODS: <on_event> FOR <event> OF <classname> ! <interface> IMPORTING
<imp_par1>...<imp_parN> SENDER.
Setting handler
SET HANDLER <ref_handle> <on_event> FOR <ref_sender> ! FOR ALL INSTANCES
[ACTIVATION <var>]

Examples
Define, implement and use simple class
***INCLUDE ZBC404_HF_LCL_AIRPLANE .
******************************************
* Definition part
******************************************
CLASS lcl_airplane DEFINITION.
*-----------------------------* Public section
*-----------------------------PUBLIC SECTION.
TYPES: t_name(25) TYPE c.
METHODS:
constructor,
set_attributes IMPORTING p_name
TYPE t_name
p_planetype TYPE saplane-planetype,
display_attributes,

display_n_o_airplanes.
*-----------------------------* Private section
*-----------------------------PRIVATE SECTION.
* Private attributes
DATA: name(25) TYPE c,
planetype TYPE saplane-planetype.
* Private static attribute
CLASS-DATA n_o_airplanes TYPE i.
ENDCLASS.
******************************************
* Implementation part
******************************************
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
* Counts number of instances
n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD set_attributes.
name
= p_name.
planetype = p_planetype.
ENDMETHOD.
METHOD display_attributes.
WRITE:/ 'Name:', name, 'Planetype:', planetype.
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: / 'No. planes:', n_o_airplanes.
ENDMETHOD.
ENDCLASS.
REPORT zbc404_hf_maintain_airplanes .
INCLUDE zbc404_hf_lcl_airplane.
* Create reference to class lcl_airplane
DATA: airplane1 TYPE REF TO lcl_airplane,
airplane2 TYPE REF TO lcl_airplane.
START-OF-SELECTION.
* Create instance
CREATE OBJECT airplane1.
CALL METHOD: airplane1->display_n_o_airplanes.
CREATE OBJECT airplane2.
* Setting attributes using a method with parameters
CALL METHOD airplane1->set_attributes EXPORTING p_name
p_planetype = 'MD80'.

= 'Kurt'

END-OF-SELECTION.
* Using methods
CALL METHOD: airplane1->display_n_o_airplanes,
airplane1->display_attributes.

The resulting report:


Maintain airplanes
No. planes:
No. planes:
Name: Kurt

1
2
Planetype: MD80

Use constructor to create an object with parameters


CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
TYPES: t_name(25) TYPE c.
METHODS:
constructor

importing p2_name
type t_name
p2_planetype TYPE saplane-planetype,
..... more code .......
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
name
= p2_name.
planetype = p2_planetype.
..... more code .......
START-OF-SELECTION.
CREATE OBJECT airplane1 exporting p2_name = 'Hansemand'
p2_planetype = 'Boing 747'.

Subclassing
This example uses a superclass LCL_AIRPLANE and subclasses it into LCL_PASSENGER_AIRPLANE
and LCL_CARGO_PLANE.
LCL_AIRPLANE has a method display_n_o_airplanes that displays the number of object instances.
LCL_PASSENGER_AIRPLANE has the private instance attribute n_o_seats, and redefines the superclass
method display_attributes, so it also displays n_o_seats.
LCL_CARGO_PLANE has the private instance attribute cargomax, and redefines the superclass method
display_attributes, so it also displays cargomax.
All instance attributes are provided by the cunstructor method.
Superclass LCL_AIRPLANE
***INCLUDE ZBC404_HF_LCL_AIRPLANE .
******************************************
* Definition part
******************************************
CLASS lcl_airplane DEFINITION.
*-----------------------------* Public section

*-----------------------------PUBLIC SECTION.
TYPES: t_name(25) TYPE c.
METHODS:
constructor

IMPORTING im_name
TYPE t_name
im_planetype TYPE saplane-planetype,
display_attributes.

* Static methods
CLASS-METHODS:
display_n_o_airplanes.
*-----------------------------* Protected section
*-----------------------------PROTECTED SECTION.
* Private attributes
DATA: name(25) TYPE c,
planetype TYPE saplane-planetype.
* Private static attribute
CLASS-DATA n_o_airplanes TYPE i.
ENDCLASS.
******************************************
* Implementation part
******************************************
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
name
= im_name.
planetype = im_planetype.
* Counts number of instances
n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD display_attributes.
WRITE:/ 'Name:', name, 'Planetype:', planetype.
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: / 'No. planes:', n_o_airplanes.
ENDMETHOD.
ENDCLASS.

Sub class LCL_PASSENGER_AIRPLANE


***INCLUDE ZBC404_HF_LCL_PASSENGER_PLANE .
*******************************************************************
* This is a subclass of class lcl_airplane
*******************************************************************
CLASS lcl_passenger_airplane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
* The constructor contains the parameters from the superclass
* plus the parameters from the subclass
METHODS:
constructor IMPORTING im_name
TYPE t_name

im_planetype TYPE saplane-planetype


im_n_o_seats TYPE sflight-seatsmax,
Redefinition of superclass method display_attributes
display_attributes REDEFINITION.

PRIVATE SECTION.
DATA: n_o_seats TYPE sflight-seatsmax.
ENDCLASS.
CLASS lcl_passenger_airplane IMPLEMENTATION.
METHOD constructor.
* The constructor method of the superclass MUST be called withing the
* construtor
CALL METHOD super->constructor
EXPORTING im_name
= im_name
im_planetype = im_planetype.
n_o_seats = im_n_o_seats.
ENDMETHOD.
* The redefined display_attributes method
METHOD display_attributes.
CALL METHOD super->display_attributes.
WRITE: / 'No. seats:', n_o_seats.
ENDMETHOD.
ENDCLASS.

Sub class LCL_CARGO_PLANE


***INCLUDE ZBC404_HF_LCL_CARGO_PLANE .
*******************************************************************
* This is a subclass of class lcl_airplane
*******************************************************************
CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
METHODS:
* The constructor contains the parameters from the superclass
* plus the parameters from the subclass
constructor IMPORTING im_name
TYPE t_name
im_planetype TYPE saplane-planetype
im_cargomax type scplane-cargomax,
* Redefinition of superclass method display_attributes
display_attributes REDEFINITION.
PRIVATE SECTION.
DATA:cargomax TYPE scplane-cargomax.
ENDCLASS.
CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor.
* The constructor method of the superclass MUST be called withing the
* constructor
CALL METHOD super->constructor
EXPORTING im_name
= im_name
im_planetype = im_planetype.
cargomax = im_cargomax.
ENDMETHOD.
METHOD display_attributes.
* The redefined display_attributes method
CALL METHOD super->display_attributes.
WRITE: / 'Cargo max:', cargomax.
ENDMETHOD.

ENDCLASS.

The Main program that uses the classes


REPORT zbc404_hf_main .
* Super class
INCLUDE zbc404_hf_lcl_airplane.
* Sub classes
INCLUDE zbc404_hf_lcl_passenger_plane.
INCLUDE zbc404_hf_lcl_cargo_plane.
DATA:
* Type ref to sub classes. Note: It is not necesssary to make typeref to the superclass
o_passenger_airplane TYPE REF TO lcl_passenger_airplane,
o_cargo_plane
TYPE REF TO lcl_cargo_plane.
START-OF-SELECTION.
* Display initial number of instances = 0
CALL METHOD lcl_airplane=>display_n_o_airplanes.
* Create objects
CREATE OBJECT o_passenger_airplane
EXPORTING
im_name
= 'LH505'
im_planetype = 'Boing 747'
im_n_o_seats = 350.
CREATE OBJECT o_cargo_plane
EXPORTING
im_name
= 'AR13'
im_planetype = 'DC 3'
im_cargomax = 35.
* Display attributes
CALL METHOD o_passenger_airplane->display_attributes.
CALL METHOD o_cargo_plane->display_attributes.
* Call static method display_n_o_airplanes
* Note: The syntax for calling a superclass method, differs from the syntax when calling a subclass method.
* When calling a superclass => must be used instead of ->
CALL METHOD lcl_airplane=>display_n_o_airplanes.

Result:
No. planes: 0
Name: LH505 Planetype: Boing 747
No. seats: 350
Name: AR13 Planetype: DC 3
Cargo max: 35,0000
No. planes: 2

Polymorphism
Polymorphism: When the same method is implemented differently in different classes. This can be done
using enheritance, by redefining a method from the superclass in subclasses and implement it differently.
Classes:
lcl_airplane Superclass
lcl_cargo_airplane Subclass
lcl_passenger_airplane Subclass

The method estimate_fuel_consumption is implemented differently in the 3 classes, as it depends on the


airplane type.

Object from different classes are stored in an internal table (plane_list) consisting of references
to the superclass, and the processed
identically for all the classes.
What coding for the estimate_fuel_consumption method taht is actually executed, depends on
the dynamic type of the plane reference variable,
that is, depends on which object plane points to.
DATA: cargo_plane
TYPE REF to lcl_cargo_airplane,
passenger_plane TYPE REF to lcl_passenger_airplane,
plane_list
TYPE TABLE OF REF TO lcl_airplane.
* Creating the list of references
CREATE OBJECT cargo_plane.
APPEND cargo_plane to plane_list.
CREATE OBJECT passenger_plane
APPEND passenger_plane to plane list.
* Generic method for calucalting required fuel
METHOD calculate required_fuel.
DATA: plane TYPE REF TO lcl_airplane.
LOOP AT plane_list INTO plane.
re_fuel = re_fuel + plane->estimate_fuel_consumption( distance ).
ENDLOOP.
ENDMETHOD.
Working example:
This example assumes that the classes lcl_airplane, lcl_passnger_airplane and lcl_cargo
plane (Se Subcallsing) exists.
Create objects of type lcl_cargo_plane and lcl_passenger_airplane, adds them to a list in
lcl_carrier, and displays the list.
*&---------------------------------------------------------------------*
*& Include ZBC404_HF_LCL_CARRIER
*
*&
*
*&---------------------------------------------------------------------*
*
CLASS lcl_carrier DEFINITION
*
*----------------------------------------------------------------------*
CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
TYPES: BEGIN OF flight_list_type,
connid TYPE sflight-connid,
fldate TYPE sflight-fldate,
airplane TYPE REF TO lcl_airplane,
seatsocc TYPE sflight-seatsocc,
cargo(5) TYPE p DECIMALS 3,
END OF flight_list_type.
METHODS: constructor IMPORTING im_name TYPE string,
get_name RETURNING value(ex_name) TYPE string,
add_a_new_airplane IMPORTING
im_airplane TYPE REF TO lcl_airplane,
create_a_new_flight importing
im_connid type sflight-connid
im_fldate type sflight-fldate
im_airplane type ref to lcl_airplane

im_seatsocc type sflight-seatsocc


optional
im_cargo type p optional,
display_airplanes.
PRIVATE SECTION.
DATA: name
TYPE string,
list_of_airplanes TYPE TABLE OF REF TO lcl_airplane,
list_of_flights TYPE TABLE OF flight_list_type.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_carrier IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_carrier IMPLEMENTATION.
METHOD constructor.
name = im_name.
ENDMETHOD.
METHOD get_name.
ex_name = name.
ENDMETHOD.
METHOD create_a_new_flight.
DATA: wa_list_of_flights TYPE flight_list_type.
wa_list_of_flights-connid = im_connid.
wa_list_of_flights-fldate = im_fldate.
wa_list_of_flights-airplane = im_airplane.
IF im_seatsocc IS INITIAL.
wa_list_of_flights-cargo = im_cargo.
ELSE.
wa_list_of_flights-seatsocc = im_seatsocc.
ENDIF.
APPEND wa_list_of_flights TO list_of_flights.
ENDMETHOD.
METHOD add_a_new_airplane.
APPEND im_airplane TO list_of_airplanes.
ENDMETHOD.
METHOD display_airplanes.
DATA: l_airplane TYPE REF TO lcl_airplane.
LOOP AT list_of_airplanes INTO l_airplane.
CALL METHOD l_airplane->display_attributes.
ENDLOOP.
ENDMETHOD.
ENDCLASS.
REPORT zbc404_hf_main .
*******************************************************************
* This reprort uses class LCL_AIRPLNAE and subclasses
* LCL_CARGO_PLANE and LCL_PASSENGER_AIRPLANE and class LCL_CARRIER
*******************************************************************
* Super class for airplanes
INCLUDE zbc404_hf_lcl_airplane.
* Sub classes for airplanes
INCLUDE zbc404_hf_lcl_passenger_plane.
INCLUDE zbc404_hf_lcl_cargo_plane.
* Carrier class
INCLUDE zbc404_hf_lcl_carrier.
DATA:
* Type ref to classes
o_passenger_airplane TYPE REF TO lcl_passenger_airplane,
o_passenger_airplane2 TYPE REF TO lcl_passenger_airplane,
o_cargo_plane
TYPE REF TO lcl_cargo_plane,
o_cargo_plane2
TYPE REF TO lcl_cargo_plane,

o_carrier
TYPE REF TO lcl_carrier.
START-OF-SELECTION.
* Create objects
CREATE OBJECT o_passenger_airplane
EXPORTING
im_name
= 'LH505'
im_planetype = 'Boing 747'
im_n_o_seats = 350.
CREATE OBJECT o_passenger_airplane2
EXPORTING
im_name
= 'SK333'
im_planetype = 'MD80'
im_n_o_seats = 110.
CREATE OBJECT o_cargo_plane
EXPORTING
im_name
= 'AR13'
im_planetype = 'DC 3'
im_cargomax = 35.
CREATE OBJECT o_cargo_plane2
EXPORTING
im_name
= 'AFL124'
im_planetype = 'Iljutsin 2'
im_cargomax = 35000.
CREATE OBJECT o_carrier
EXPORTING im_name = 'Spritisch Airways'.
* Add passenger and cargo planes to the list of airplanes
CALL METHOD o_carrier->add_a_new_airplane
EXPORTING im_airplane = o_passenger_airplane.
CALL METHOD o_carrier->add_a_new_airplane
EXPORTING im_airplane = o_passenger_airplane2.
CALL METHOD o_carrier->add_a_new_airplane
EXPORTING im_airplane = o_cargo_plane.
CALL METHOD o_carrier->add_a_new_airplane
EXPORTING im_airplane = o_cargo_plane2.
* Display list of airplanes
call method o_carrier->display_airplanes.

Result:
Name: LH505
Planetype: Boing 747
No. seats:
350
Name: SK333
Planetype: MD80
No. seats:
110
Name: AR13
Planetype: DC 3
Cargo max:
35,0000
Name: AFL124
Planetype: Iljutsin 2
Cargo max:
35.000,0000
Events
Below is a simple example of how to implement an event.
REPORT zbc404_hf_events_5.
*---------------------------------------------------------------------*
*
CLASS lcl_dog DEFINITION
*---------------------------------------------------------------------*
CLASS lcl_dog DEFINITION.
PUBLIC SECTION.
* Declare events

EVENTS:
dog_is_hungry
EXPORTING value(ex_time_since_last_meal) TYPE i.
METHODS:
constructor
IMPORTING im_name TYPE string,
set_time_since_last_meal
IMPORTING im_time TYPE i,
on_dog_is_hungry FOR EVENT dog_is_hungry OF lcl_dog
IMPORTING ex_time_since_last_meal.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_dog IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_dog IMPLEMENTATION.
METHOD constructor.
WRITE: / 'I am a dog and my name is', im_name.
ENDMETHOD.
METHOD set_time_since_last_meal.
IF im_time < 4.
SKIP 1.
WRITE: / 'You fool, I am not hungry yet'.
ELSE.
* Subsrcribe for event:
* set handler <Event handler method>
* FOR <ref_sender>!FOR ALL INSTANCES [ACTIVATION <var>]
SET HANDLER on_dog_is_hungry FOR ALL INSTANCES ACTIVATION 'X'.
* Raise event
RAISE EVENT dog_is_hungry
EXPORTING ex_time_since_last_meal = im_time.
ENDIF.
ENDMETHOD.
METHOD on_dog_is_hungry.
* Event method, called when the event dog_is_hungry is raised
SKIP 1.
WRITE: / 'You son of a bitch. I have not eaten for more than',
ex_time_since_last_meal, ' hours'.
WRITE: / 'Give me something to eat NOW!'.
ENDMETHOD.
ENDCLASS.
*---------------------------------------------------------------------*
*
REPORT
*---------------------------------------------------------------------*
DATA: o_dog1 TYPE REF TO lcl_dog.
START-OF-SELECTION.
CREATE OBJECT o_dog1 EXPORTING im_name = 'Beefeater'.
CALL METHOD o_dog1->set_time_since_last_meal
EXPORTING im_time = 2.
* This method call will raise the event dog_is_hungy
* because time > 3
CALL METHOD o_dog1->set_time_since_last_meal
EXPORTING im_time = 5.

Result:
I am a dog and my name is Beefeater
You fool, I am not hungry yet
You son of a bitch. I have not eaten for more than 5 hours
Give me something to eat NOW!

The employee example - Step by step example


This example is a step by step example, moving from a simple clas to more sophisticated classes, and
covers inheritance, interfaces and events.
1.
2.
3.
4.

Simple class
Inheritance and ploymorphism
Interfaces
Events

1. Simple class
This example shows how to create a simple employee class. The constructor method is used to initialize
number and name of thje employee when the object is created. A display_employee method can be called
to show the attributes of the employee, and CLASS-METHOD dosplay_no_of_employees can be called to
show the total number of employees (Number of instances of the employee class).
REPORT zbc404_hf_events_1.
*********************************************************************
*LCL_EMPLOYEE
*********************************************************************
*---- LCL Employee - Definition
CLASS lcl_employee DEFINITION.
PUBLIC SECTION.
*-------------------------------------------------------------------* The public section is accesible from outside
*-------------------------------------------------------------------TYPES:
BEGIN OF t_employee,
no TYPE i,
name TYPE string,
END OF t_employee.
METHODS:
constructor
IMPORTING im_employee_no TYPE i
im_employee_name TYPE string,
display_employee.
* Class methods are global for all instances
CLASS-METHODS: display_no_of_employees.
PROTECTED SECTION.
*-------------------------------------------------------------------* The protecetd section is accesible from the class and its subclasses
*-------------------------------------------------------------------* Class data are global for all instances
CLASS-DATA: g_no_of_employees TYPE i.
PRIVATE SECTION.
*-------------------------------------------------------------------* The private section is only accesible from within the classs
*--------------------------------------------------------------------

DATA: g_employee TYPE t_employee.


ENDCLASS.
*--- LCL Employee - Implementation
CLASS lcl_employee IMPLEMENTATION.
METHOD constructor.
g_employee-no = im_employee_no.
g_employee-name = im_employee_name.
g_no_of_employees = g_no_of_employees + 1.
ENDMETHOD.
METHOD display_employee.
WRITE:/ 'Employee', g_employee-no, g_employee-name.
ENDMETHOD.
METHOD display_no_of_employees.
WRITE: / 'Number of employees is:', g_no_of_employees.
ENDMETHOD.
ENDCLASS.
************************************************************************
*REPORT
*********************************************************************
DATA: g_employee1 TYPE REF TO lcl_employee,
g_employee2 TYPE REF TO lcl_employee.
START-OF-SELECTION.
CREATE OBJECT g_employee1
EXPORTING im_employee_no = 1
im_employee_name = 'John Jones'.
CREATE OBJECT g_employee2
EXPORTING im_employee_no = 2
im_employee_name = 'Sally Summer'.
CALL METHOD g_employee1->display_employee.
CALL METHOD g_employee2->display_employee.
CALL METHOD g_employee2->display_no_of_employees.

2. Inheritance and polymorphism


This example uses a superclass lcl_company_employees and two subclasses lcl_bluecollar_employee
and lcl_whitecollar_employee to add employees to a list and then display a list of employees and there
wages. The wages are calcukated in the method add_employee, but as the wages are calculated
differently for blue collar employees and white collar emplyees, the superclass method add_employee is
redeifined in the subclasses.
Principles:
Create super class LCL_CompanyEmployees.
The class has the methods:
Constructor
Add_Employee - Adds a new employee to the list of employees
Display_Employee_List - Displays all employees and there wage
Display_no_of_employees - Displays total number of employees
Note the use of CLASS-DATA to keep the list of employees and number of employees the same from
instance to instance.
Create subclasses lcl_bluecollar_employee and lcl_whitecollar_employee. The calsses are identical,
except for the redifinition of the add_employee method, where the caclculation of wage is different.
Methodes:
Constructor. The constructor is used to initialize the attributes of the employee. Note that the
constructor in the supclasss has to be called from within the constructor of the subclass.

Add_Employee. This is a redinition of the same method in the superclass. In the redefined class the
wage is calcuated, and the superclass method is called to add the employees to the emploee list.:

The program
REPORT zbc404_hf_events_2 .
*******************************************************
* Super class LCL_CompanyEmployees
*******************************************************
CLASS lcl_company_employees DEFINITION.
PUBLIC SECTION.
TYPES:
BEGIN OF t_employee,
no TYPE i,
name TYPE string,
wage TYPE i,
END OF t_employee.
METHODS:
constructor,
add_employee
IMPORTING im_no TYPE i
im_name TYPE string
im_wage TYPE i,
display_employee_list,
display_no_of_employees.
PRIVATE SECTION.
CLASS-DATA: i_employee_list TYPE TABLE OF t_employee,
no_of_employees TYPE i.
ENDCLASS.
*-- CLASS LCL_CompanyEmployees IMPLEMENTATION
CLASS lcl_company_employees IMPLEMENTATION.
METHOD constructor.
no_of_employees = no_of_employees + 1.
ENDMETHOD.
METHOD add_employee.
* Adds a new employee to the list of employees
DATA: l_employee TYPE t_employee.
l_employee-no = im_no.
l_employee-name = im_name.
l_employee-wage = im_wage.
APPEND l_employee TO i_employee_list.
ENDMETHOD.
METHOD display_employee_list.
* Displays all employees and there wage
DATA: l_employee TYPE t_employee.
WRITE: / 'List of Employees'.
LOOP AT i_employee_list INTO l_employee.
WRITE: / l_employee-no, l_employee-name, l_employee-wage.
ENDLOOP.
ENDMETHOD.
METHOD display_no_of_employees.
* Displays total number of employees
SKIP 3.
WRITE: / 'Total number of employees:', no_of_employees.
ENDMETHOD.
ENDCLASS.
*******************************************************

* Sub class LCL_BlueCollar_Employee


*******************************************************
CLASS lcl_bluecollar_employee DEFINITION
INHERITING FROM lcl_company_employees.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING im_no
TYPE i
im_name
TYPE string
im_hours
TYPE i
im_hourly_payment TYPE i,
add_employee REDEFINITION.
PRIVATE SECTION.
DATA:no
TYPE i,
name
TYPE string,
hours
TYPE i,
hourly_payment TYPE i.
ENDCLASS.
*---- CLASS LCL_BlueCollar_Employee IMPLEMENTATION
CLASS lcl_bluecollar_employee IMPLEMENTATION.
METHOD constructor.
* The superclass constructor method must be called from the subclass
* constructor method
CALL METHOD super->constructor.
no = im_no.
name = im_name.
hours = im_hours.
hourly_payment = im_hourly_payment.
ENDMETHOD.
METHOD add_employee.
* Calculate wage an call the superclass method add_employee to add
* the employee to the employee list
DATA: l_wage TYPE i.
l_wage = hours * hourly_payment.
CALL METHOD super->add_employee
EXPORTING im_no = no
im_name = name
im_wage = l_wage.
ENDMETHOD.
ENDCLASS.
*******************************************************
* Sub class LCL_WhiteCollar_Employee
*******************************************************
CLASS lcl_whitecollar_employee DEFINITION
INHERITING FROM lcl_company_employees.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING im_no
TYPE i
im_name
TYPE string
im_monthly_salary TYPE i
im_monthly_deductions TYPE i,
add_employee REDEFINITION.
PRIVATE SECTION.
DATA:
no
TYPE i,
name
TYPE string,
monthly_salary
TYPE i,
monthly_deductions TYPE i.

ENDCLASS.
*---- CLASS LCL_WhiteCollar_Employee IMPLEMENTATION
CLASS lcl_whitecollar_employee IMPLEMENTATION.
METHOD constructor.
* The superclass constructor method must be called from the subclass
* constructor method
CALL METHOD super->constructor.
no = im_no.
name = im_name.
monthly_salary = im_monthly_salary.
monthly_deductions = im_monthly_deductions.
ENDMETHOD.
METHOD add_employee.
* Calculate wage an call the superclass method add_employee to add
* the employee to the employee list
DATA: l_wage TYPE i.
l_wage = monthly_salary - monthly_deductions.
CALL METHOD super->add_employee
EXPORTING im_no = no
im_name = name
im_wage = l_wage.
ENDMETHOD.
ENDCLASS.
*******************************************************
*REPORT
*******************************************************
DATA:
* Object references
o_bluecollar_employee1 TYPE REF TO lcl_bluecollar_employee,
o_whitecollar_employee1 TYPE REF TO lcl_whitecollar_employee.
START-OF-SELECTION.
* Create bluecollar employee obeject
CREATE OBJECT o_bluecollar_employee1
EXPORTING im_no = 1
im_name = 'Gylle Karen'
im_hours = 38
im_hourly_payment = 75.
* Add bluecollar employee to employee list
CALL METHOD o_bluecollar_employee1->add_employee
EXPORTING im_no = 1
im_name = 'Gylle Karen'
im_wage = 0.
* Create whitecollar employee obeject
CREATE OBJECT o_whitecollar_employee1
EXPORTING im_no = 2
im_name = 'John Dickens'
im_monthly_salary = 10000
im_monthly_deductions = 2500.
* Add bluecollar employee to employee list
CALL METHOD o_whitecollar_employee1->add_employee
EXPORTING im_no = 1
im_name = 'Karen Johnson'
im_wage = 0.
* Display employee list and number of employees. Note that the result
* will be the same when called from o_whitecollar_employee1 or
* o_bluecolarcollar_employee1, because the methods are defined
* as static (CLASS-METHODS)
CALL METHOD o_whitecollar_employee1->display_employee_list.
CALL METHOD o_whitecollar_employee1->display_no_of_employees.

The resulting report

List of Employees
1 Karen Johnson 2.850
2 John Dickens 7.500
Total number of employees: 2
3. Interfaces
This example is similiar to th eprevious example, however an interface is implemented with the method
add_employee. Note that the interface is only implemented in the superclass ( The INTERFACE stament),
but also used in the subclasses.
The interface in the example only contains a method, but an iterface can also contain attrbutes, constants,
types and alias names.
The output from example 3 is similiar to the output in example 2.
All changes in the program compared to example 2 are marked with red.
REPORT zbc404_hf_events_3 .
*---------------------------------------------------------------------*
*
INTERFACE lif_employee
*---------------------------------------------------------------------*
INTERFACE lif_employee.
METHODS:
add_employee
IMPORTING im_no TYPE i
im_name TYPE string
im_wage TYPE i.
ENDINTERFACE.
*******************************************************
* Super class LCL_CompanyEmployees
*******************************************************
CLASS lcl_company_employees DEFINITION.
PUBLIC SECTION.
INTERFACES lif_employee.
TYPES:
BEGIN OF t_employee,
no TYPE i,
name TYPE string,
wage TYPE i,
END OF t_employee.
METHODS:
constructor,
*
add_employee
"Removed
IMPORTING im_no TYPE i
im_name TYPE string
im_wage TYPE i,
display_employee_list,
display_no_of_employees.
PRIVATE SECTION.
CLASS-DATA: i_employee_list TYPE TABLE OF t_employee,
no_of_employees TYPE i.
ENDCLASS.
*-- CLASS LCL_CompanyEmployees IMPLEMENTATION
CLASS lcl_company_employees IMPLEMENTATION.
METHOD constructor.
no_of_employees = no_of_employees + 1.
ENDMETHOD.

METHOD lif_employee~add_employee.
* Adds a new employee to the list of employees
DATA: l_employee TYPE t_employee.
l_employee-no = im_no.
l_employee-name = im_name.
l_employee-wage = im_wage.
APPEND l_employee TO i_employee_list.
ENDMETHOD.
METHOD display_employee_list.
* Displays all employees and there wage
DATA: l_employee TYPE t_employee.
WRITE: / 'List of Employees'.
LOOP AT i_employee_list INTO l_employee.
WRITE: / l_employee-no, l_employee-name, l_employee-wage.
ENDLOOP.
ENDMETHOD.
METHOD display_no_of_employees.
* Displays total number of employees
SKIP 3.
WRITE: / 'Total number of employees:', no_of_employees.
ENDMETHOD.
ENDCLASS.
*******************************************************
* Sub class LCL_BlueCollar_Employee
*******************************************************
CLASS lcl_bluecollar_employee DEFINITION
INHERITING FROM lcl_company_employees.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING im_no
TYPE i
im_name
TYPE string
im_hours
TYPE i
im_hourly_payment TYPE i,
lif_employee~add_employee REDEFINITION..
PRIVATE SECTION.
DATA:no
TYPE i,
name
TYPE string,
hours
TYPE i,
hourly_payment TYPE i.
ENDCLASS.
*---- CLASS LCL_BlueCollar_Employee IMPLEMENTATION
CLASS lcl_bluecollar_employee IMPLEMENTATION.
METHOD constructor.
* The superclass constructor method must be called from the subclass
* constructor method
CALL METHOD super->constructor.
no = im_no.
name = im_name.
hours = im_hours.
hourly_payment = im_hourly_payment.
ENDMETHOD.
METHOD lif_employee~add_employee.
* Calculate wage an call the superclass method add_employee to add
* the employee to the employee list
DATA: l_wage TYPE i.
l_wage = hours * hourly_payment.
CALL METHOD super->lif_employee~add_employee

EXPORTING im_no = no
im_name = name
im_wage = l_wage.
ENDMETHOD.
ENDCLASS.
*******************************************************
* Sub class LCL_WhiteCollar_Employee
*******************************************************
CLASS lcl_whitecollar_employee DEFINITION
INHERITING FROM lcl_company_employees.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING im_no
TYPE i
im_name
TYPE string
im_monthly_salary TYPE i
im_monthly_deductions TYPE i,
lif_employee~add_employee REDEFINITION.
PRIVATE SECTION.
DATA:
no
TYPE i,
name
TYPE string,
monthly_salary
TYPE i,
monthly_deductions TYPE i.
ENDCLASS.
*---- CLASS LCL_WhiteCollar_Employee IMPLEMENTATION
CLASS lcl_whitecollar_employee IMPLEMENTATION.
METHOD constructor.
* The superclass constructor method must be called from the subclass
* constructor method
CALL METHOD super->constructor.
no = im_no.
name = im_name.
monthly_salary = im_monthly_salary.
monthly_deductions = im_monthly_deductions.
ENDMETHOD.
METHOD lif_employee~add_employee.
* Calculate wage an call the superclass method add_employee to add
* the employee to the employee list
DATA: l_wage TYPE i.
l_wage = monthly_salary - monthly_deductions.
CALL METHOD super->lif_employee~add_employee
EXPORTING im_no = no
im_name = name
im_wage = l_wage.
ENDMETHOD.
ENDCLASS.
*******************************************************
*REPORT
*******************************************************
DATA:
* Object references
o_bluecollar_employee1 TYPE REF TO lcl_bluecollar_employee,
o_whitecollar_employee1 TYPE REF TO lcl_whitecollar_employee.
START-OF-SELECTION.
* Create bluecollar employee obeject
CREATE OBJECT o_bluecollar_employee1
EXPORTING im_no = 1
im_name = 'Gylle Karen'
im_hours = 38

im_hourly_payment = 75.
* Add bluecollar employee to employee list
CALL METHOD o_bluecollar_employee1->lif_employee~add_employee
EXPORTING im_no = 1
im_name = 'Karen Johnson'
im_wage = 0.
* Create whitecollar employee obeject
CREATE OBJECT o_whitecollar_employee1
EXPORTING im_no = 2
im_name = 'John Dickens'
im_monthly_salary = 10000
im_monthly_deductions = 2500.
* Add bluecollar employee to employee list
CALL METHOD o_whitecollar_employee1->lif_employee~add_employee
EXPORTING im_no = 1
im_name = 'Gylle Karen'
im_wage = 0.
* Display employee list and number of employees. Note that the result
* will be the same when called from o_whitecollar_employee1 or
* o_bluecolarcollar_employee1, because the methods are defined
* as static (CLASS-METHODS)
CALL METHOD o_whitecollar_employee1->display_employee_list.
CALL METHOD o_whitecollar_employee1->display_no_of_employees.

4. Events
This is the same example as example 4. All changes are marked with red. There have been no canges to
the subclasses, only to the superclass and the report, sp the code for th esubclasses is not shown.
For a simple example refer to Events in Examples.
REPORT zbc404_hf_events_4 .
*---------------------------------------------------------------------*
*
INTERFACE lif_employee
*---------------------------------------------------------------------*
INTERFACE lif_employee.
METHODS:
add_employee
IMPORTING im_no TYPE i
im_name TYPE string
im_wage TYPE i.
ENDINTERFACE.
*******************************************************
* Super class LCL_CompanyEmployees
*******************************************************
CLASS lcl_company_employees DEFINITION.
PUBLIC SECTION.
TYPES:
BEGIN OF t_employee,
no TYPE i,
name TYPE string,
wage TYPE i,
END OF t_employee.
* Declare event. Note that declaration could also be placed in the
* interface
EVENTS: employee_added_to_list
EXPORTING value(ex_employee_name) TYPE string.
* CLASS-EVENTS: Events can also be defined as class-events
INTERFACES lif_employee.
METHODS:

constructor,
display_employee_list,
display_no_of_employees,
* Declare event method
on_employee_added_to_list FOR EVENT employee_added_to_list OF lcl_company_employees
IMPORTING ex_employee_name sender.
PRIVATE SECTION.
CLASS-DATA:
i_employee_list TYPE TABLE OF t_employee,
no_of_employees TYPE i.
ENDCLASS.
*-- CLASS LCL_CompanyEmployees IMPLEMENTATION
CLASS lcl_company_employees IMPLEMENTATION.
METHOD constructor.
no_of_employees = no_of_employees + 1.
ENDMETHOD.
METHOD lif_employee~add_employee.
* Adds a new employee to the list of employees
DATA: l_employee TYPE t_employee.
l_employee-no = im_no.
l_employee-name = im_name.
l_employee-wage = im_wage.
APPEND l_employee TO i_employee_list.
* Raise event employee_added_to_list
RAISE EVENT employee_added_to_list
EXPORTING ex_employee_name = l_employee-name.
ENDMETHOD.
METHOD display_employee_list.
* Displays all employees and there wage
DATA: l_employee TYPE t_employee.
WRITE: / 'List of Employees'.
LOOP AT i_employee_list INTO l_employee.
WRITE: / l_employee-no, l_employee-name, l_employee-wage.
ENDLOOP.
ENDMETHOD.
METHOD display_no_of_employees.
* Displays total number of employees
SKIP 3.
WRITE: / 'Total number of employees:', no_of_employees.
ENDMETHOD.
METHOD on_employee_added_to_list.
* Event method
WRITE: / 'Employee added to list', ex_employee_name.
ENDMETHOD.
ENDCLASS.
*******************************************************
* Sub class LCL_BlueCollar_Employee
*******************************************************
CLASS lcl_bluecollar_employee DEFINITION
INHERITING FROM lcl_company_employees.

See code in example 3...


ENDCLASS.
CLASS lcl_bluecollar_employee IMPLEMENTATION.

See code in example 3...


ENDCLASS.
*******************************************************
* Sub class LCL_WhiteCollar_Employee
*******************************************************
CLASS lcl_whitecollar_employee DEFINITION

See code in example 3...


ENDCLASS.
CLASS lcl_whitecollar_employee IMPLEMENTATION.

See code in example 3...


ENDCLASS.
*******************************************************
*REPORT
*******************************************************
DATA:
* Object references
o_bluecollar_employee1 TYPE REF TO lcl_bluecollar_employee,
o_whitecollar_employee1 TYPE REF TO lcl_whitecollar_employee.
START-OF-SELECTION.
* Create bluecollar employee obeject
CREATE OBJECT o_bluecollar_employee1
EXPORTING im_no = 1
im_name = 'Karen Johnson'
im_hours = 38
im_hourly_payment = 75.
* Register event for o_bluecollar_employee1
SET HANDLER o_bluecollar_employee1->on_employee_added_to_list
FOR o_bluecollar_employee1.
* Add bluecollar employee to employee list
CALL METHOD o_bluecollar_employee1->lif_employee~add_employee
EXPORTING im_no = 1
im_name = 'Gylle Karen'
im_wage = 0.
* Create whitecollar employee obeject
CREATE OBJECT o_whitecollar_employee1
EXPORTING im_no = 2
im_name = 'John Dickens'
im_monthly_salary = 10000
im_monthly_deductions = 2500.
* Register event for o_whitecollar_employee1
SET HANDLER o_whitecollar_employee1->on_employee_added_to_list
FOR o_whitecollar_employee1.
* Add bluecollar employee to employee list
CALL METHOD o_whitecollar_employee1->lif_employee~add_employee
EXPORTING im_no = 1
im_name = 'Gylle Karen'
im_wage = 0.
* Display employee list and number of employees. Note that the result
* will be the same when called from o_whitecollar_employee1 or
* o_bluecolarcollar_employee1, because the methods are defined
* as static (CLASS-METHODS)
CALL METHOD o_whitecollar_employee1->display_employee_list.
CALL METHOD o_whitecollar_employee1->display_no_of_employees.

Result:
Employee added to list Karen Johnson
Employee added to list John Dickens
List of Employees
1 Karen Johnson 2.850
2 John Dickens 7.500

Total number of employees: 2

Control Technology

How to use controls


General
Control Framework and enheritance hierarchy
The control framework consists of 2 parts:
CL_GUI_CFW contains methods that provide services for communication with the frontend, and
can be used both by control wrapper calsses and by control progtrammers
The CL_GUI_OBJECT encapsulates ActiveX or JavaBeans methods, while CL_GUI_CONTROL is
responsible for displaying the control on the screen.
CL_GUI_OBJECT -> CL_GUI_CONTROL -> CL_GUI_* (Wrapper class)
These classes contains methods that are enherited by subsequent classes in the enheritance tree.
Synchronization/Flush
RFC calls is used to synchronize the front and backend. This synchronization takes palce at some
predifined points in the program flow. However you should not rely entirely on automatic synchronization,
but force synchronization with the Flush method when necessary.
Bear in mind that the synchronization/RFC calls represenmts a bottleneck, so you should keep the not use
the Flush method to a minimum.
Syntax:
CALL METHOD cl_gui_cfw=>FLUSH
Set up event handling for controls
There are two types of events:
Application events. T
The flow logic of the screen is processed after the event (The PAI module is processed).
In the events table the event must be registred as an application event by setting then field appl_event to
'X':
wa_events-eventid = cl_gui_textedit=>event_double_click.
wa_events-appl_event = 'X'.
append wa_events to i_events.
Important: The dispatch method of cl_gui_cfw must be called in the PAI module:
CALL METHOD cl_gui_cfw=>dispatch.
System events.

For system events the flow-logic of the screen is not executed. That means that the PAI and PBO modules
are not processed.
In the events table the the field appl_event must be set to SAPCE:
wa_events-eventid = cl_gui_textedit=>event_double_click.
wa_events-appl_event = space.
append wa_events to i_events.
The dispatch method of cl_gui_cfw must NOT be called.
Example
It is presumed that a SAP toolbar control named go_toolbar of class cl_gui_toolbar has been defined. To
see a complete example of how to handle events, refer to The SAP toolbar control.
Data:
* 1. Define and instance of the eventhandler class.
*
If the event handler class is defined after the data decalaration
*
the class must be declared as DEFERRED in the top of the program: CLASS cls_event_handler
DEFINITION DEFERRED.
go_event_handler TYPE REF TO cls_event_handler,
* 2. Define table for registration of events.
* Note that a TYPE REF to cls_event_handler must be created before you can
* reference types cntl_simple_events and cntl_simple_event
gi_events TYPE cntl_simple_events,
* Workspace for table gi_events
g_event TYPE cntl_simple_event.
* 3. Define and implement eventhandler class
CLASS cls_event_handler DEFINITION.
PUBLIC SECTION.
METHODS:
* Syntax:
* <method name> FOR EVENT <event of control - see the control documentation>
*
OF <class of object> <importing parameters l - see the control documentation>
on_function_selected
FOR EVENT function_selected OF cl_gui_toolbar
IMPORTING fcode,
ENDCLASS.
CLASS cls_event_handler IMPLEMENTATION.
METHOD on_function_selected.
* Do something when the event is raised
ENDMETHOD.
ENDCLASS.
* 4. Append events to the events table
* The Event Id can be found in the control documentation. Note that The event below is registred as an
application event
g_event-eventid
= go_toolbar->m_id_function_selected.
g_event-appl_event = 'X'. "This is an application event
APPEND g_event TO gi_events.
.... append more events i necessary...
* 5. Use the events table to register events for the control
CALL METHOD go_toolbar->set_registered_events
EXPORTING
events = gi_events.
* 6. Create event handler

CREATE OBJECT go_event_handler.


* Syntax:
* SET HANDLER <event handler class> -> <Event handler method>
* FOR <control>
SET HANDLER go_event_handler->on_function_selected
FOR go_toolbar.

Declare a reference variable before the class has been defined


Scenario:
DATA: o_my_class TYPE REF TO lcl_myclass.
CLASS lcl_myclass.....
ENDCLASS.
This will cause an error because the definition of class lcl_myclass is after the declaration.
Solution:
Define the class in the beginning of the program with DEFINITION DEFERRED:
CLASS lcl_myclass DEFINITION DEFERRED.
DATA: o_my_class TYPE REF TO lcl_myclass.
CLASS lcl_myclass.....
ENDCLASS.
Set focus to a control
Set the focus to a control named go_grid:
CALL METHOD cl_gui_control=>set_focus
EXPORTING control = go_grid.

The TextEdit control


Example 1: Creating the TextEdit control
This is a simple example of how to implement a text edit control.
Steps
1. Create a report
2. In the start of selection event add: SET SCREEN '100'.
3. Create screen 100
4. Place a custom control on the screen by choosing the custom control icon which can be recognized
by the letter 'C', and give it the name MYCONTAINER1.
5. To be able to exit the program, add a pushbutton with the function code EXIT.
6. In the elements list enter the name OK_CODE for the element of type OK.
The code

REPORT sapmz_hf_controls1 .
CONSTANTS:
line_length TYPE i VALUE 254.
DATA: ok_code LIKE sy-ucomm.
DATA:
* Create reference to the custom container
custom_container TYPE REF TO cl_gui_custom_container,
* Create reference to the TextEdit control
editor TYPE REF TO cl_gui_textedit,
repid LIKE sy-repid.
START-OF-SELECTION.
SET SCREEN '100'.
*---------------------------------------------------------------------*
*
MODULE USER_COMMAND_0100 INPUT
*---------------------------------------------------------------------*
MODULE user_command_0100 INPUT.
CASE ok_code.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
* The TextEdit control shoul only be initialized the first time the
* PBO module executes
IF editor IS INITIAL.
repid = sy-repid.
* Create obejct for custom container
CREATE OBJECT custom_container
EXPORTING
container_name
= 'MYCONTAINER1'
EXCEPTIONS
cntl_error
=1
cntl_system_error
=2
create_error
=3
lifetime_error
=4
lifetime_dynpro_dynpro_link = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Create obejct for the TextEditor control
CREATE OBJECT editor
EXPORTING
wordwrap_mode
=
cl_gui_textedit=>wordwrap_at_fixed_position
wordwrap_position
= line_length
wordwrap_to_linebreak_mode = cl_gui_textedit=>true
parent
= custom_container
EXCEPTIONS
error_cntl_create
=1
error_cntl_init
=2
error_cntl_link
=3
error_dp_create
=4
gui_type_not_supported = 5
others
=6

.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
ENDIF.
ENDMODULE.
" STATUS_0100 OUTPUT

The result

Example 2: Event handling - Application event


There are 2 types of events:
System events. These events are triggerede irrespective of the screen flow-logic.
Application events. The PAI module is processed after an event. The method
CL_GUI_CFW=>DISPATCH must be called to initiate event handling
In this example an application event is added to the program in example 1. New code is marked with red.
Steps:
1. Create an input/output field on screen 100, where the event type can be output. Name it
EVENT_TYPE
The code:
REPORT sapmz_hf_controls1 .
CONSTANTS:
line_length TYPE i VALUE 254.
DATA: ok_code LIKE sy-ucomm.
DATA:
* Create reference to the custom container

custom_container TYPE REF TO cl_gui_custom_container,


* Create reference to the TextEdit control
editor TYPE REF TO cl_gui_textedit,
repid LIKE sy-repid.
**********************************************************************
* Impmenting events
**********************************************************************
DATA:
event_type(20) TYPE c,
* Internal table for events that should be registred
i_events TYPE cntl_simple_events,
* Structure for oneline of the table
wa_events TYPE cntl_simple_event.
*---------------------------------------------------------------------*
*
CLASS lcl_event_handler DEFINITION
*---------------------------------------------------------------------*
CLASS lcl_event_handler DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
catch_dblclick FOR EVENT dblclick
OF cl_gui_textedit IMPORTING sender.
ENDCLASS.
CLASS lcl_event_handler IMPLEMENTATION.
METHOD catch_dblclick.
event_type = 'Event DBLCLICK raised'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
CLEAR wa_events. refresh i_events.
SET SCREEN '100'.
*---------------------------------------------------------------------*
*
MODULE USER_COMMAND_0100 INPUT
*
*---------------------------------------------------------------------*
MODULE user_command_0100 INPUT.
CASE ok_code.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
WHEN OTHERS.
* Call the Dispacth method to initiate application event handling
call method cl_gui_cfw=>Dispatch.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
* The TextEdit control shoul only be initialized the first time the
* PBO module executes
IF editor IS INITIAL.
repid = sy-repid.
* Create obejct for custom container
CREATE OBJECT custom_container
EXPORTING
container_name
= 'MYCONTAINER1'
EXCEPTIONS
cntl_error
=1
cntl_system_error
=2

create_error
=3
lifetime_error
=4
lifetime_dynpro_dynpro_link = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Create obejct for the TextEditor control
CREATE OBJECT editor
EXPORTING
wordwrap_mode
=
cl_gui_textedit=>wordwrap_at_fixed_position
wordwrap_position
= line_length
wordwrap_to_linebreak_mode = cl_gui_textedit=>true
parent
= custom_container
EXCEPTIONS
error_cntl_create
=1
error_cntl_init
=2
error_cntl_link
=3
error_dp_create
=4
gui_type_not_supported = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Link the event handler method to the event and the
* TextEdit control
SET HANDLER lcl_event_handler=>catch_dblclick FOR editor.
* Register the event in the internal table i_events
wa_events-eventid = cl_gui_textedit=>event_double_click.
wa_events-appl_event = 'X'. "This is an application event
append wa_events to i_events.
* Pass the table to the TextEdit control using method
* set_registred_events
call method editor->set_registered_events
exporting events = i_events.
ENDIF.
ENDMODULE.
" STATUS_0100 OUTPUT

Result:
When you double click on the TextEdit control, the input/ouput field should show the text: Event
DBLCLICK
Example 3: Event handling - System event
System events are passed irrespective of the flow-logic of the screen. To implement a system event
change the code from example 2 as follows:
Code:
CLASS lcl_event_handler IMPLEMENTATION.
METHOD catch_dblclick.
*--- event_type = 'Event DBLCLICK raised'.
* Reacting to the system event
call method cl_gui_cfw=>set_new_ok_code
exporting new_code = 'SHOW'.

MODULE user_command_0100 INPUT.


CASE ok_code.
code.........
WHEN 'SHOW'.
event_type = 'System dblclick'.
WHEN OTHERS.
*---- call method cl_gui_cfw=>Dispatch.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
MODULE status_0100 OUTPUT.
Code ................
*--- wa_events-appl_event = 'X'. "This is an application event
wa_events-appl_event = space. "This is a system event
ENDIF.
ENDMODULE.
" STATUS_0100 OUTPUT

Result:
When you double clicks on the TextEdit control nothing happens, since the flow-logic of the screen an dthe
fielde transport is ignore.
Example 4: Calling methods of the control
In this exercise a function that loads the texts of an internal table into the text window, is implemented.
Steps:
Define anoterh pushbutton on the screen, that activates the method that fills the TextEdit control. Give
itname PUSHBUTTON_IMPORT and function code IMP.
Define a form CREATE_TEXTS that carries out the text import.
Only changes to the code in example 2 is show.
Code:
MODULE user_command_0100 INPUT.
CASE ok_code.
code.........
WHEN 'IMP'.
perform load_texts.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Form load_texts
*&---------------------------------------------------------------------*
* This form creates an internal table with texts. The the contents of
* the table is instered into the TextEdit control using method
* set_text_as_r3table
*----------------------------------------------------------------------*
FORM load_texts.
TYPES:
BEGIN OF t_texttable,
line(line_length) TYPE c,
END OF t_texttable.
DATA
i_texttable TYPE TABLE OF t_texttable.
* Create internal table with texts
APPEND 'This a method that fills the TextEdit control' TO i_texttable.
APPEND 'with a text.' TO i_texttable.
DO 10 TIMES.
APPEND 'hallo world !' TO i_texttable.

ENDDO.
* Load TextEdit control with texts
CALL METHOD editor->set_text_as_r3table
EXPORTING table = i_texttable.
IF sy-subrc > 0.
* Display an error message
EXIT.
ENDIF.
* All methods that operates on controls are transferred to the frontend
* by a RFC calls. the method FLUSH is used to determine when this is done.
CALL METHOD cl_gui_cfw=>flush.
IF sy-subrc > 0.
* Display an error message
ENDIF.
ENDFORM.
" create_texts

Example 5: Responding to an event


When you double click on a text line in the TextEdit control, you want it to be prefixed with a '*'.
The line number of the TextEdit control that is double clicked, is retreived using method
GET_SELECTION_POS. The internal text table is reloaded froim the TextEdit control with method
GET_TEXT_AS_R3TABLE. The position of the double click in the TextEdit control is used to find the entry
in the table, and the entry is prefixed with '*' and loaded into the TextEdit control again.
The program should be changed so that the internal table i_texttable is global, and a global flag g_loaded
added. The load of the table should be moved to the PBO module. The changes in thje code are marked
with red. The whole program now looks like this:
Code
REPORT sapmz_hf_controls1 .
CONSTANTS:
line_length TYPE i VALUE 254.
DATA: ok_code LIKE sy-ucomm.
DATA:
* Create reference to the custom container
custom_container TYPE REF TO cl_gui_custom_container,
* Create reference to the TextEdit control
editor TYPE REF TO cl_gui_textedit,
repid LIKE sy-repid.
**********************************************************************
* Utillity table to load texts
**********************************************************************
TYPES:
BEGIN OF t_texttable,
line(line_length) TYPE c,
END OF t_texttable.
DATA:
i_texttable TYPE TABLE OF t_texttable,
g_loaded(1) TYPE c.
**********************************************************************
* Impmenting events
**********************************************************************
DATA:
event_type(20) TYPE c,
* Internal table for events that should be registred
i_events TYPE cntl_simple_events,
* Structure for oneline of the table
wa_events TYPE cntl_simple_event.

*---------------------------------------------------------------------*
*
CLASS lcl_event_handler DEFINITION
*---------------------------------------------------------------------*
CLASS lcl_event_handler DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
catch_dblclick FOR EVENT dblclick
OF cl_gui_textedit IMPORTING sender.
ENDCLASS.
CLASS lcl_event_handler IMPLEMENTATION.
METHOD catch_dblclick.
DATA:
from_line TYPE i,
from_pos TYPE i,
to_line TYPE i,
to_pos TYPE i,
wa_texttable TYPE t_texttable.
* Used for the sytem event
call method cl_gui_cfw=>set_new_ok_code
exporting new_code = 'SHOW'.
* Read the position of the double click
CALL METHOD sender->get_selection_pos
IMPORTING
from_line = from_line
from_pos = from_pos
to_line = to_line
to_pos = to_pos.
* Texts in the TextEdit control can have been changed, so
* first reload text from the control into the internal
* table that contains text
IF NOT g_loaded IS INITIAL.
CALL METHOD sender->get_text_as_r3table
IMPORTING table = i_texttable.
* Read the line of the internal table that was clicked
READ TABLE i_texttable INDEX from_line INTO wa_texttable.
IF sy-subrc <> 0.
EXIT.
ENDIF.
IF wa_texttable+0(1) CS '*'.
SHIFT wa_texttable.
ELSEIF wa_texttable+0(1) NS '*'.
SHIFT wa_texttable RIGHT.
wa_texttable+0(1) = '*'.
ENDIF.
modify i_texttable from wa_texttable index from_line.
* Reload texts from h einternal table
perform load_texts.
ENDIF.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
CLEAR wa_events.
REFRESH: i_events.
SET SCREEN '100'.
*---------------------------------------------------------------------*
*
MODULE USER_COMMAND_0100 INPUT
*---------------------------------------------------------------------*
MODULE user_command_0100 INPUT.
CASE ok_code.

WHEN 'EXIT'.
LEAVE TO SCREEN 0.
WHEN 'SHOW'.
event_type = 'System dblclick'.
WHEN 'IMP'.
PERFORM Load_texts.
WHEN OTHERS.
* CALL METHOD cl_gui_cfw=>dispatch. "Not used for system events
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
* The TextEdit control shoul only be initialized the first time the
* PBO module executes
IF editor IS INITIAL.
repid = sy-repid.
* Create object for custom container
CREATE OBJECT custom_container
EXPORTING
container_name
= 'MYCONTAINER1'
EXCEPTIONS
cntl_error
=1
cntl_system_error
=2
create_error
=3
lifetime_error
=4
lifetime_dynpro_dynpro_link = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Create obejct for the TextEditor control
CREATE OBJECT editor
EXPORTING
wordwrap_mode
=
cl_gui_textedit=>wordwrap_at_fixed_position
wordwrap_position
= line_length
wordwrap_to_linebreak_mode = cl_gui_textedit=>true
parent
= custom_container
EXCEPTIONS
error_cntl_create
=1
error_cntl_init
=2
error_cntl_link
=3
error_dp_create
=4
gui_type_not_supported = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Link the event handler method to the event and the
* TextEdit control
SET HANDLER lcl_event_handler=>catch_dblclick FOR editor.
* Register the event in the internal table i_events
wa_events-eventid = cl_gui_textedit=>event_double_click.
* wa_events-appl_event = 'X'. "This is an application event

wa_events-appl_event = space. "This is a system event


APPEND wa_events TO i_events.
* Pass the table to the TextEdit control uding method
* set_registred_events
CALL METHOD editor->set_registered_events
EXPORTING events = i_events.
* Create internal table with texts taht can be uploaded to
* the TextEdit control
APPEND 'This a method that fills the TextEdit control' TO i_texttable.
APPEND 'with a text.' TO i_texttable.
DO 10 TIMES.
APPEND 'hallo world !' TO i_texttable.
ENDDO.
ENDIF.
ENDMODULE.
" STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
*&
Form Load_texts
*&---------------------------------------------------------------------*
* This form loads the lines of the internal table i_texttable into
* the TextEdit control
*----------------------------------------------------------------------*
FORM Load_texts.
* Load TextEdit control with texts
CALL METHOD editor->set_text_as_r3table
EXPORTING table = i_texttable.
IF sy-subrc > 0.
* Display an error message
EXIT.
ENDIF.
* All methods that operates on controls are transferred to the frontend
* by a RFC calls. the method FLUSH is used to determine when this is
* done.
CALL METHOD cl_gui_cfw=>flush.
IF sy-subrc > 0.
* Display an error message
ENDIF.
g_loaded = 'X'.
ENDFORM.
" create_texts

Example 6: Protect a line in the TextEdit control and the importance of FLUSH
All methods that operates on controls are transfered to the fronend by RFC calls. The FLUSH method is
used to synchronize control execution and the frontend. This is very important when working e.g. with
export parameters from a method, as the parmeters will not be correct before the FLUSH method has
been called.
The example below portects selected lines in the TextEdit and uses FLUSH to ensure that the correct
parameters are returned from method GET_SELECTION_POS.
Note: Instead of using method PROTECT_LINES, the method PROTECT_SELECTION could be used.
This method does not need line numbers or a FLUSH statement
Steps
Add a new pushbutton to the screen with the function code PROTECT.
Code
Add the following code to the example:

* Global variables

DATA:
from_idx TYPE i,
to_idx TYPE i,
index TYPE i.
MODULE user_command_0100 INPUT.
CASE ok_code.
code.......................
WHEN 'PROTECT'.
PERFORM protect.
.

.......................
ENDCASE.

*&---------------------------------------------------------------------*
*&
Form protect
*&---------------------------------------------------------------------*
* Protects marked lines in a TextEdit control
*----------------------------------------------------------------------*
FORM protect.
* Determine the area selected by the user
CALL METHOD editor->get_selection_pos
IMPORTING
from_line = from_idx
to_line = to_idx
EXCEPTIONS
error_cntl_call_method = 1.
* Synchronize execution in the control with the ABAP program.
* Without this synchronization the variables from_idx and
* to_idx will have obsolutete values (The initial value for
* both, are 0)
CALL METHOD cl_gui_cfw=>flush.
IF sy-subrc > 0.
* Errormessage: Error in flush
ENDIF.
* Protect the selected lines
IF to_idx > from_idx.
to_idx = to_idx - 1.
ENDIF.
CALL METHOD editor->protect_lines
EXPORTING
from_line = from_idx
to_line = to_idx.
* The PROTECT_SELECTION method could be used instead, eliminating the
* need of line numbers and the last FLUSH
* call method editor->protect_selection.
* Flush again to protect immidiately
CALL METHOD cl_gui_cfw=>flush.
IF sy-subrc > 0.
* Errormessage: Error in flush
ENDIF.
ENDFORM.

" protect

Example 7: Using multiple controls

In this example a second TextEdit control will be added to the screen. The new TextEdit control will be
designed to act as a clipboard for short texts.
Steps:
Add a new container to the screen and name it MYCONTAINER2.
Code:
Insert global datadeclaration:
**********************************************************************
* Implementing a second Scratch TextEdit control
**********************************************************************
DATA:
scratch
TYPE REF TO cl_gui_textedit,
custom_container2 TYPE REF TO cl_gui_custom_container.

Insert the following code in the PBO module:


*-----------------------------------------------------* The SCRATCH TextEdit control
*-----------------------------------------------------IF scratch IS INITIAL.
* Create obejct for custom container2
CREATE OBJECT custom_container2
EXPORTING
container_name
= 'MYCONTAINER2'
EXCEPTIONS
cntl_error
=1
cntl_system_error
=2
create_error
=3
lifetime_error
=4
lifetime_dynpro_dynpro_link = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Create obejct for the SCRATCH TextEditor control
CREATE OBJECT scratch
EXPORTING
parent
= custom_container2
wordwrap_mode =
cl_gui_textedit=>wordwrap_at_windowborder
wordwrap_to_linebreak_mode = cl_gui_textedit=>true.
* Remove the staus bar
CALL METHOD scratch->set_statusbar_mode
EXPORTING statusbar_mode = cl_gui_textedit=>false.
ENDIF.

Result:

SAPMZ_HF_CONTROLS1
1 REPORT sapmz_hf_controls1 .
2
3 CONSTANTS:
4 line_length TYPE i VALUE 254.
5
6 DATA: ok_code LIKE sy-ucomm.
7
8 DATA:
9 * Create reference to the custom container
10 custom_container TYPE REF TO cl_gui_custom_container,
11 * Create reference to the TextEdit control
12 editor TYPE REF TO cl_gui_textedit,
13 repid LIKE sy-repid.
14
15 **********************************************************************
16 * Utillity table to load texts

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

**********************************************************************
TYPES:
BEGIN OF t_texttable,
line(line_length) TYPE c,
END OF t_texttable.
DATA:
i_texttable TYPE TABLE OF t_texttable,
wa_texttable TYPE t_texttable,
g_loaded(1) TYPE c.
**********************************************************************
* Data for the protection example
**********************************************************************
DATA:
from_idx TYPE i,
to_idx TYPE i,
index TYPE i.
**********************************************************************
* Implementing a second Scratch TextEdit control
**********************************************************************
DATA:
scratch
TYPE REF TO cl_gui_textedit,
custom_container2 TYPE REF TO cl_gui_custom_container.
**********************************************************************
* Implementing events
**********************************************************************
DATA:
event_type(20) TYPE c,
* Internal table for events that should be registred
i_events TYPE cntl_simple_events,
* Structure for oneline of the table
wa_events TYPE cntl_simple_event.
*---------------------------------------------------------------------*
*
CLASS lcl_event_handler DEFINITION
*---------------------------------------------------------------------*
*
........
*
*---------------------------------------------------------------------*
CLASS lcl_event_handler DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
catch_dblclick FOR EVENT dblclick
OF cl_gui_textedit IMPORTING sender.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_event_handler IMPLEMENTATION
*---------------------------------------------------------------------*
*
........
*
*---------------------------------------------------------------------*
CLASS lcl_event_handler IMPLEMENTATION.
METHOD catch_dblclick.
DATA:
from_line TYPE i,
from_pos TYPE i,

77
to_line TYPE i,
78
to_pos TYPE i.
79
80
81 * Used for the sytem event
82
CALL METHOD cl_gui_cfw=>set_new_ok_code
83
EXPORTING new_code = 'SHOW'.
84
85
86 * Read the position of the double click
87
CALL METHOD sender->get_selection_pos
88
IMPORTING
89
from_line = from_line
90
from_pos = from_pos
91
to_line = to_line
92
to_pos = to_pos.
93
94 * Texts in the TextEdit control can have been changed, so
95 * first reload text from the control into the internal
96 * table that contains text
97
IF NOT g_loaded IS INITIAL.
98
CALL METHOD sender->get_text_as_r3table
99
IMPORTING table = i_texttable.
100 * Read the line of the internal table that was clicked
101
READ TABLE i_texttable INDEX from_line INTO wa_texttable.
102
IF sy-subrc <> 0.
103
EXIT.
104
ENDIF.
105
106
IF wa_texttable+0(1) CS '*'.
107
SHIFT wa_texttable.
108
ELSEIF wa_texttable+0(1) NS '*'.
109
SHIFT wa_texttable RIGHT.
110
wa_texttable+0(1) = '*'.
111
ENDIF.
112
MODIFY i_texttable FROM wa_texttable INDEX from_line.
113 * Reload texts from h einternal table
114
PERFORM load_texts.
115
116
117
ENDIF.
118
119
120 ENDMETHOD.
121 ENDCLASS.
122
123
124
125 START-OF-SELECTION.
126 CLEAR wa_events.
127 REFRESH: i_events.
128
129 SET SCREEN '100'.
130
131
132
133 *---------------------------------------------------------------------*
134 *
MODULE USER_COMMAND_0100 INPUT
135 *---------------------------------------------------------------------*
136 MODULE user_command_0100 INPUT.

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

CASE ok_code.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
WHEN 'SHOW'.
event_type = 'System dblclick'.
WHEN 'IMP'.
PERFORM load_texts.
WHEN 'PROTECT'.
PERFORM protect.
*

WHEN OTHERS.
CALL METHOD cl_gui_cfw=>dispatch. "Not used for system events
ENDCASE.

ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
* The TextEdit control shoul only be initialized the first time the
* PBO module executes
IF editor IS INITIAL.
repid = sy-repid.
* Create obejct for custom container
CREATE OBJECT custom_container
EXPORTING
container_name
= 'MYCONTAINER1'
EXCEPTIONS
cntl_error
=1
cntl_system_error
=2
create_error
=3
lifetime_error
=4
lifetime_dynpro_dynpro_link = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Create obejct for the TextEditor control
CREATE OBJECT editor
EXPORTING
wordwrap_mode
=
cl_gui_textedit=>wordwrap_at_fixed_position
wordwrap_position
= line_length
wordwrap_to_linebreak_mode = cl_gui_textedit=>true
parent
= custom_container
EXCEPTIONS
error_cntl_create
=1
error_cntl_init
=2
error_cntl_link
=3
error_dp_create
=4
gui_type_not_supported = 5
others
=6
.
IF sy-subrc <> 0.

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno


WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Link the event handler method to the event and the
* TextEdit control
SET HANDLER lcl_event_handler=>catch_dblclick FOR editor.
* Register the event in the internal table i_events
wa_events-eventid = cl_gui_textedit=>event_double_click.
*

wa_events-appl_event = 'X'. "This is an application event


wa_events-appl_event = space. "This is a system event

APPEND wa_events TO i_events.


* Pass the table to the TextEdit control uding method
* set_registred_events
CALL METHOD editor->set_registered_events
EXPORTING events = i_events.
* Create internal table with texts taht can be uploaded to
* the TextEdit control
APPEND 'This a method that fills the TextEdit control' TO i_texttable.
APPEND 'with a text.' TO i_texttable.
DO 10 TIMES.
APPEND 'hallo world !' TO i_texttable.
ENDDO.
ENDIF.
*-----------------------------------------------------* The SCRATCH TextEdit control
*-----------------------------------------------------IF scratch IS INITIAL.
* Create obejct for custom container2
CREATE OBJECT custom_container2
EXPORTING
container_name
= 'MYCONTAINER2'
EXCEPTIONS
cntl_error
=1
cntl_system_error
=2
create_error
=3
lifetime_error
=4
lifetime_dynpro_dynpro_link = 5
others
=6
.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Create obejct for the SCRATCH TextEditor control
CREATE OBJECT scratch
EXPORTING
parent
= custom_container2
wordwrap_mode =
cl_gui_textedit=>wordwrap_at_windowborder
wordwrap_to_linebreak_mode = cl_gui_textedit=>true.
* Remove the staus bar

257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

CALL METHOD scratch->set_statusbar_mode


EXPORTING statusbar_mode = cl_gui_textedit=>false.
ENDIF.
ENDMODULE.

" STATUS_0100 OUTPUT

*&---------------------------------------------------------------------*
*&
Form Load_texts
*&---------------------------------------------------------------------*
* This form loads the lines of the internal table i_texttable into
* the TextEdit control
*----------------------------------------------------------------------*
FORM load_texts.
* Load TextEdit control with texts
CALL METHOD editor->set_text_as_r3table
EXPORTING table = i_texttable.
IF sy-subrc > 0.
* Display an error message
EXIT.
ENDIF.
* All methods that operates on controls are transferred to the frontend
* by a RFC calls. the method FLUSH is used to determine when this is
* done.
CALL METHOD cl_gui_cfw=>flush.
IF sy-subrc > 0.
* Display an error message
ENDIF.
g_loaded = 'X'.
ENDFORM.
" create_texts
*&---------------------------------------------------------------------*
*&
Form protect
*&---------------------------------------------------------------------*
* Protects marked lines in a TextEdit control
*----------------------------------------------------------------------*
FORM protect.
* Determine the area selected by the user
CALL METHOD editor->get_selection_pos
IMPORTING
from_line = from_idx
to_line = to_idx
EXCEPTIONS
error_cntl_call_method = 1.
* Synchronize execution in the control with the ABAP program.
* Without this synchronization the variables from_idx and
* to_idx will have obsolutete values (The initial value for
* both, are 0)
CALL METHOD cl_gui_cfw=>flush.
IF sy-subrc > 0.
* Errormessage: Error in flush
ENDIF.
* Protect the lines selected
IF to_idx > from_idx.
to_idx = to_idx - 1.
ENDIF.

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337

CALL METHOD editor->protect_lines


EXPORTING
from_line = from_idx
to_line = to_idx.
* The PROTECT_SELECTION method could be used instead, eliminating the
* need of line numbers and the last FLUSH
* call method editor->protect_selection.
* Flush again to protect immidately
CALL METHOD cl_gui_cfw=>flush.
IF sy-subrc > 0.
* Errormessage: Error in flush
ENDIF.

ENDFORM.

" protect

The ALV Grid control


Preface
Note that practical eaxmples of using the ALV grid can be found in development class SLIS.
Example of the fdisplay of an ALV grid:

Simple example of how to implement an ALV grid


Note that this example uses table ZSFLIGHT. The table is equivalent to the table SFLIGHT.
Steps:
1. Create an executable program (Report)
2. Create a screen (100) and palce a custom container named ALV_CONTAINER on the screen
3. Create a Pushbutton. Give it the text Exit and the functioncode EXIT
REPORT sapmz_hf_alv_grid .
TABLES: zsflight.
*-------------------------------------------------------------------*GLOBAL INTERN AL TABLES
*-------------------------------------------------------------------DATA: gi_sflight TYPE STANDARD TABLE OF sflight.
*-------------------------------------------------------------------*GLOBAL DATA
*-------------------------------------------------------------------DATA: ok_code LIKE sy-ucomm,
g_wa_sflight LIKE sflight.
* Declare reference variables to the ALV grid and the container
DATA:
go_grid
TYPE REF TO cl_gui_alv_grid,
go_custom_container TYPE REF TO cl_gui_custom_container.
*-------------------------------------------------------------------* S T A R T - O F - S E L E C T I O N.
*-------------------------------------------------------------------START-OF-SELECTION.
SET SCREEN '100'.
*&---------------------------------------------------------------------*
*&
Module USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
MODULE user_command_0100 INPUT.
CASE ok_code.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
* Create objects
IF go_custom_container IS INITIAL.
CREATE OBJECT go_custom_container
EXPORTING container_name = 'ALV_CONTAINER'.
CREATE OBJECT go_grid
EXPORTING
i_parent = go_custom_container.

PERFORM load_data_into_grid.
ENDIF.
ENDMODULE.
" STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
*&
Form load_data_into_grid
*&---------------------------------------------------------------------*
*
text
*----------------------------------------------------------------------*
* --> p1
text
* <-- p2
text
*----------------------------------------------------------------------*
FORM load_data_into_grid.
* Read data from table SFLIGHT
SELECT *
FROM zsflight
INTO TABLE gi_sflight.
* Load data into the grid and display them
CALL METHOD go_grid->set_table_for_first_display
EXPORTING i_structure_name = 'SFLIGHT'
CHANGING it_outtab
= gi_sflight.
ENDFORM.

" load_data_into_grid

Allow the user to save and reuse the layout


A button can be shown on the grid toolbar, allowing the user to save and reuse a layout. The button looks
like this:
See also example in SAP standard program BCALV_GRID_09.
To do this use the parameters IS_VARIANT and I_SAVE of the set_table_for_first_display method. Note
that the IS_VARIANT parameter must have the structure DISVARIANT.
The I_SAVE "Options for saving layouts" parameter can have the following values:
U Only user specific layouts can be saved
X Only global layouts can be saved
A Both user specific and global layouts can be saved
Space Layouts can not be saved
Add the following code to the example:
FORM load_data_into_grid.
DATA:
* For parameter IS_VARIANT
l_layout TYPE disvariant.
Code..........
* Load data into the grid and display them
l_layout-report = sy-repid.
CALL METHOD go_grid->set_table_for_first_display
EXPORTING i_structure_name = 'SFLIGHT'
is_variant
= l_layout
i_save
= 'A'
CHANGING it_outtab
= gi_

Integrate user defined functions in the grid toolbar

Posibillities:
Replace existing functions in the toolbar or context men with user defined functions
Add new functions to the toolbar or context menu
Note that the whole toolbar can be removed using the IT_TOOLBAR_EXCLUDING parameter of the
set_table_for_first_display method.
See also example in SAP standard program BCALV_GRID_05
1) To get access to the icons insert the following statement in the top of the program:
TYPE-POOLS: icon.
2) To allow the declaration of o_event_receiver before the lcl_event_receiver class is defined, declare it as
deferred in the
start of the program
* To allow the declaration of o_event_receiver before the lcl_event_receiver class is defined, declare it as
deferred in the
* start of the program
CLASS lcl_event_receiver DEFINITION DEFERRED.
3) Declare reference to the event handler class
DATA:

o_event_receiver TYPE REF TO lcl_event_receiver.


4) Class for event receiver. This class adds the new button to the toolbar and handles the
event when the button is pushed
CLASS lcl_event_receiver DEFINITION.
PUBLIC SECTION.
METHODS:
handle_toolbar FOR EVENT toolbar OF cl_gui_alv_grid
IMPORTING
e_object e_interactive,
handle_user_command FOR EVENT user_command OF cl_gui_alv_grid
IMPORTING e_ucomm.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_event_receiver IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_event_receiver IMPLEMENTATION.
METHOD handle_toolbar.
* Event handler method for event toolbar.
CONSTANTS:
* Constants for button type
c_button_normal
TYPE i VALUE 0,
c_menu_and_default_button TYPE i VALUE 1,
c_menu
TYPE i VALUE 2,
c_separator
TYPE i VALUE 3,
c_radio_button
TYPE i VALUE 4,

c_checkbox
c_menu_entry

TYPE i VALUE 5,
TYPE i VALUE 6.

DATA:
ls_toolbar TYPE stb_button.
* Append seperator to the normal toolbar
CLEAR ls_toolbar.
MOVE c_separator TO ls_toolbar-butn_type..
APPEND ls_toolbar TO e_object->mt_toolbar.
*
*
*
*

Append a new button that to the toolbar. Use E_OBJECT of


event toolbar. E_OBJECT is of type CL_ALV_EVENT_TOOLBAR_SET.
This class has one attribute MT_TOOLBAR which is of table type
TTB_BUTTON. The structure is STB_BUTTON
CLEAR ls_toolbar.
MOVE 'CHANGE'
TO ls_toolbar-function.
MOVE icon_change TO ls_toolbar-icon.
MOVE 'Change flight' TO ls_toolbar-quickinfo.
MOVE 'Change'
TO ls_toolbar-text.
MOVE ' '
TO ls_toolbar-disabled.
APPEND ls_toolbar TO e_object->mt_toolbar.
ENDMETHOD.
METHOD handle_user_command.
* Handle own functions defined in the toolbar
CASE e_ucomm.
WHEN 'CHANGE'.
LEAVE TO SCREEN 0.
ENDCASE.
ENDMETHOD.
ENDCLASS.
5) In the PBO module, crate object for event handler and set handler
CREATE OBJECT o_event_receiver.
SET HANDLER o_event_receiver->handle_user_command FOR go_grid.
SET HANDLER o_event_receiver->handle_toolbar FOR go_grid.
6) In the PBO module after the CALL METHOD go_grid->set_table_for_first_display, raise
event toolbar to show the modified toolbar
CALL METHOD go_grid->set_toolbar_interactive.
Set focus to the grid
After CALL METHOD go_grid->set_table_for_first_display insert the following stament:
CALL METHOD cl_gui_control=>set_focus EXPORTING control = go_grid.

Set the title of the grid


Fill the grid_title field of structure lvc_s_layo.
Note that the structure lvc_s_layo can be used for to customize the grid appearance in many ways.
DATA:
* ALV control: Layout structure
gs_layout TYPE lvc_s_layo.

* Set grid title


gs_layout-grid_title = 'Flights'.
CALL METHOD go_grid->set_table_for_first_display
EXPORTING i_structure_name = 'SFLIGHT'
is_layout
= gs_layout
CHANGING it_outtab
= gi_sflight.
Customize the appearence of the grid
The structure lvc_s_layo contains fields for setting graphical properties, displaying exceptions, calculating
totals and enabling specific interaction options.
Fill the apporpiate fields of structure lvc_s_layo and insert it as a parametrer in the CALL METHOD
go_grid->set_table_for_first_display. See the example under Set the title of the grid.
If you want to change apperance after list output, use the methods get_frontend_layout and
set_frontend_layout.
Examples of fields in structure lvc_s_layo:
GRID_TITLE Setting the title of the grid
SEL_MODE. Selection mode, determines how rows can be selected. Can have the follwing values:
A Multiple columns, multiple rows with selection buttons.
B Simple selection, listbox, Single row/column
C Multiple rows without buttons
D Multiple rows with buttons and select all ICON
Setting and getting selected rows (Columns) and read line contents
You can read which rows of the grid that has been selected, and dynamic select rows of the grid using
methods get_selected_rows and set_selected_rows. There are similiar methods for columns.
Note that the grid table always has the rows in the same sequence as displayed in the grid, thus you can
use the index of the selected row(s) to read the information in the rows fronm the table. In the examples
below the grid table is named gi_sflight.
Data declaratrion:
DATA:
* Internal table for indexes of selected rows
gi_index_rows TYPE lvc_t_row,
* Information about 1 row
g_selected_row LIKE lvc_s_row.
Example 1: Reading index of selected row(s) and using it to read the grid table

CALL METHOD go_grid->get_selected_rows


IMPORTING
et_index_rows = gi_index_rows.

DESCRIBE TABLE gi_index_rows LINES l_lines.


IF l_lines = 0.
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
EXPORTING
textline1 = 'You must choose a valid line'.
EXIT.
ENDIF.
LOOP AT gi_index_rows INTO g_selected_row.
READ TABLE gi_sflight INDEX g_selected_row-index INTO g_wa_sflight.
ENDIF.
ENDLOOP.
Example 2: Set selected row(s).
DESCRIBE TABLE gi_index_rows LINES l_lines.
IF l_lines > 0.
CALL METHOD go_grid->set_selected_rows
exporting
it_index_rows = gi_index_rows.
ENDIF.

Make an Exception field ( = Traffic lights)


There can be defined a column in the grid for display of traffic lights. This field is of type Char 1, and canb
contain the following values:
1 Red
2 Yellow
3 Green
The name of the traffic light field is supplied inh the gs_layout-excp_fname used by method
set_table_for_first_display.
Example

TYPES: BEGIN OF st_sflight.


INCLUDE STRUCTURE zsflight.
TYPES: traffic_light TYPE c.
TYPES: END OF st_sflight.
TYPES: tt_sflight TYPE STANDARD TABLE OF st_sflight.
DATA: gi_sflight TYPE tt_sflight.
* Set the exception field of the table
LOOP AT gi_sflight INTO g_wa_sflight.
IF g_wa_sflight-paymentsum < 100000.
g_wa_sflight-traffic_light = '1'.
ELSEIF g_wa_sflight-paymentsum => 100000 AND
g_wa_sflight-paymentsum < 1000000.
g_wa_sflight-traffic_light = '2'.
ELSE.

g_wa_sflight-traffic_light = '3'.
ENDIF.
MODIFY gi_sflight FROM g_wa_sflight.
ENDLOOP.
* Name of the exception field (Traffic light field)
gs_layout-excp_fname = 'TRAFFIC_LIGHT'.
* Grid setup for first display
CALL METHOD go_grid->set_table_for_first_display
EXPORTING i_structure_name = 'SFLIGHT'
is_layout
= gs_layout
CHANGING it_outtab
= gi_sflight.
Color a line
The steps for coloring a line i the grid is much the same as making a traffic light.

* To color a line the structure of the table must include a Char 4 field for color properties
TYPES: BEGIN OF st_sflight.
INCLUDE STRUCTURE zsflight.
*
Field for line color
types: line_color(4) type c.
TYPES: END OF st_sflight.
TYPES: tt_sflight TYPE STANDARD TABLE OF st_sflight.
DATA: gi_sflight TYPE tt_sflight.
* Loop trough the table to set the color properties of each line. The color properties field is
* Char 4 and the characters is set as follows:
* Char 1 = C = This is a color property
* Char 2 = 6 = Color code (1 - 7)
* Char 3 = Intensified on/of = 1 = on
* Char 4 = Inverse display = 0 = of
LOOP AT gi_sflight INTO g_wa_sflight.
IF g_wa_sflight-paymentsum < 100000.
g_wa_sflight-line_color = 'C610'.
ENDIF.
MODIFY gi_sflight FROM g_wa_sflight.
ENDLOOP.
* Name of the color field
gs_layout-info_fname = 'LINE_COLOR'.
* Grid setup for first display
CALL METHOD go_grid->set_table_for_first_display
EXPORTING i_structure_name = 'SFLIGHT'
is_layout
= gs_layout
CHANGING it_outtab
= gi_sflight.
Refresh grid display

Use the grid method REFRESH_TABLE_DISPLAY


Example:
CALL METHOD go_grid->refresh_table_display.
Complete code for the ALV grid example
This example shows and ALV grid with flights. After selecting a line a change button can be pushed to
display a change screen. After the changes have been saved, the ALV grid screen is displayed again, and
the grid is updated with the changes.
The example shows:
How to setup the ALV grid
How to ste focus to the grid
How to set the title of the grid
How to allow a user to save and resue a grid layout (Variant)
How to customize the ALV grid toolbar
Refresh the grid
Set and get row selection and read ine contents
Make and exception field (Traffic light)
Coloring a line
Steps:

Create screen 100 with the ALV grid. Remeber to include an exit button
Add a change button to the ALV grid toolbar
Create screen 200 the Change screen

The screens:

The code:
REPORT sapmz_hf_alv_grid .
* Type pool for icons - used in the toolbar
TYPE-POOLS: icon.
TABLES: zsflight.
* To allow the declaration of o_event_receiver before the
* lcl_event_receiver class is defined, decale it as deferred in the
* start of the program
CLASS lcl_event_receiver DEFINITION DEFERRED.

*-------------------------------------------------------------------*GLOBAL INTERN AL TABLES


*-------------------------------------------------------------------*DATA: gi_sflight TYPE STANDARD TABLE OF sflight.
* To include a traffic light and/or color a line the structure of the
* table must include fields for the traffic light and/or the color
TYPES: BEGIN OF st_sflight.
INCLUDE STRUCTURE zsflight.
*
Field for traffic light
TYPES: traffic_light TYPE c.
*
Field for line color
types: line_color(4) type c.
TYPES: END OF st_sflight.
TYPES: tt_sflight TYPE STANDARD TABLE OF st_sflight.
DATA: gi_sflight TYPE tt_sflight.
*-------------------------------------------------------------------*GLOBAL DATA
*-------------------------------------------------------------------DATA: ok_code
LIKE sy-ucomm,
* Work area for internal table
g_wa_sflight TYPE st_sflight,
* ALV control: Layout structure
gs_layout
TYPE lvc_s_layo.
* Declare reference variables to the ALV grid and the container
DATA:
go_grid
TYPE REF TO cl_gui_alv_grid,
go_custom_container TYPE REF TO cl_gui_custom_container,
o_event_receiver TYPE REF TO lcl_event_receiver.
DATA:
* Work area for screen 200
g_screen200 LIKE zsflight.
* Data for storing information about selected rows in the grid
DATA:
* Internal table
gi_index_rows TYPE lvc_t_row,
* Information about 1 row
g_selected_row LIKE lvc_s_row.

*-------------------------------------------------------------------*CLASSES
*-------------------------------------------------------------------CLASS lcl_event_receiver DEFINITION.
PUBLIC SECTION.
METHODS:
handle_toolbar FOR EVENT toolbar OF cl_gui_alv_grid
IMPORTING
e_object e_interactive,
handle_user_command FOR EVENT user_command OF cl_gui_alv_grid
IMPORTING e_ucomm.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_event_receiver IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_event_receiver IMPLEMENTATION.
METHOD handle_toolbar.
* Event handler method for event toolbar.
CONSTANTS:
* Constants for button type
c_button_normal
TYPE i VALUE 0,
c_menu_and_default_button TYPE i VALUE 1,
c_menu
TYPE i VALUE 2,
c_separator
TYPE i VALUE 3,
c_radio_button
TYPE i VALUE 4,
c_checkbox
TYPE i VALUE 5,
c_menu_entry
TYPE i VALUE 6.
DATA:
ls_toolbar TYPE stb_button.
* Append seperator to the normal toolbar
CLEAR ls_toolbar.
MOVE c_separator TO ls_toolbar-butn_type..
APPEND ls_toolbar TO e_object->mt_toolbar.
*
*
*
*

Append a new button that to the toolbar. Use E_OBJECT of


event toolbar. E_OBJECT is of type CL_ALV_EVENT_TOOLBAR_SET.
This class has one attribute MT_TOOLBAR which is of table type
TTB_BUTTON. The structure is STB_BUTTON
CLEAR ls_toolbar.
MOVE 'CHANGE'
TO ls_toolbar-function.
MOVE icon_change TO ls_toolbar-icon.
MOVE 'Change flight' TO ls_toolbar-quickinfo.
MOVE 'Change'
TO ls_toolbar-text.
MOVE ' '
TO ls_toolbar-disabled.
APPEND ls_toolbar TO e_object->mt_toolbar.
ENDMETHOD.
METHOD handle_user_command.

* Handle own functions defined in the toolbar


CASE e_ucomm.
WHEN 'CHANGE'.
PERFORM change_flight.
*
LEAVE TO SCREEN 0.
ENDCASE.
ENDMETHOD.
ENDCLASS.
*-------------------------------------------------------------------* S T A R T - O F - S E L E C T I O N.
*-------------------------------------------------------------------START-OF-SELECTION.
SET SCREEN '100'.
*&---------------------------------------------------------------------*
*&
Module USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
MODULE user_command_0100 INPUT.
CASE ok_code.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
DATA:
* For parameter IS_VARIANT that is sued to set up options for storing
* the grid layout as a variant in method set_table_for_first_display
l_layout TYPE disvariant,
* Utillity field
l_lines TYPE i.
* After returning from screen 200 the line that was selected before
* going to screen 200, should be selected again. The table gi_index_rows
* was the output table from the GET_SELECTED_ROWS method in form
* CHANGE_FLIGHT
DESCRIBE TABLE gi_index_rows LINES l_lines.
IF l_lines > 0.
CALL METHOD go_grid->set_selected_rows
EXPORTING
it_index_rows = gi_index_rows.
CALL METHOD cl_gui_cfw=>flush.
REFRESH gi_index_rows.
ENDIF.
* Read data and create objects
IF go_custom_container IS INITIAL.
* Read data from datbase table
PERFORM get_data.

* Create objects for container and ALV grid


CREATE OBJECT go_custom_container
EXPORTING container_name = 'ALV_CONTAINER'.
CREATE OBJECT go_grid
EXPORTING
i_parent = go_custom_container.
* Create object for event_receiver class
* and set handlers
CREATE OBJECT o_event_receiver.
SET HANDLER o_event_receiver->handle_user_command FOR go_grid.
SET HANDLER o_event_receiver->handle_toolbar FOR go_grid.
* Layout (Variant) for ALV grid
l_layout-report = sy-repid. "Layout fo report
*--------------------------------------------------------------* Setup the grid layout using a variable of structure lvc_s_layo
*--------------------------------------------------------------* Set grid title
gs_layout-grid_title = 'Flights'.
* Selection mode - Single row without buttons
* (This is the default mode
gs_layout-sel_mode = 'B'.
* Name of the exception field (Traffic light field) and the color
* field + set the exception and color field of the table
gs_layout-excp_fname = 'TRAFFIC_LIGHT'.
gs_layout-info_fname = 'LINE_COLOR'.
LOOP AT gi_sflight INTO g_wa_sflight.
IF g_wa_sflight-paymentsum < 100000.
*
Value of traffic light field
g_wa_sflight-traffic_light = '1'.
*
Value of color field:
*
C = Color, 6=Color 1=Intesified on, 0: Inverse display off
g_wa_sflight-line_color = 'C610'.
ELSEIF g_wa_sflight-paymentsum => 100000 AND
g_wa_sflight-paymentsum < 1000000.
g_wa_sflight-traffic_light = '2'.
ELSE.
g_wa_sflight-traffic_light = '3'.
ENDIF.
MODIFY gi_sflight FROM g_wa_sflight.
ENDLOOP.
* Grid setup for first display
CALL METHOD go_grid->set_table_for_first_display
EXPORTING i_structure_name = 'SFLIGHT'
is_variant
= l_layout
i_save
= 'A'
is_layout
= gs_layout
CHANGING it_outtab
= gi_sflight.
*-- End of grid setup -------------------------------------------

* Raise event toolbar to show the modified toolbar


CALL METHOD go_grid->set_toolbar_interactive.
* Set focus to the grid. This is not necessary in this
* example as there is only one control on the screen
CALL METHOD cl_gui_control=>set_focus EXPORTING control = go_grid.
ENDIF.
ENDMODULE.

" STATUS_0100 OUTPUT

*&---------------------------------------------------------------------*
*&
Module USER_COMMAND_0200 INPUT
*&---------------------------------------------------------------------*
*
text
*----------------------------------------------------------------------*
MODULE user_command_0200 INPUT.
CASE ok_code.
WHEN 'EXIT200'.
LEAVE TO SCREEN 100.
WHEN'SAVE'.
PERFORM save_changes.
ENDCASE.
ENDMODULE.

" USER_COMMAND_0200 INPUT

*&---------------------------------------------------------------------*
*&
Form get_data
*&---------------------------------------------------------------------*
*
text
*----------------------------------------------------------------------*
FORM get_data.
* Read data from table SFLIGHT
SELECT *
FROM zsflight
INTO TABLE gi_sflight.
ENDFORM.
" load_data_into_grid
*&---------------------------------------------------------------------*
*&
Form change_flight
*&---------------------------------------------------------------------*
* Reads the contents of the selected row in the grid, ans transfers
* the data to screen 200, where it can be changed and saved.
*----------------------------------------------------------------------*
FORM change_flight.
DATA:l_lines TYPE i.
REFRESH gi_index_rows.
CLEAR g_selected_row.
* Read index of selected rows
CALL METHOD go_grid->get_selected_rows
IMPORTING
et_index_rows = gi_index_rows.
* Check if any row are selected at all. If not
* table gi_index_rows will be empty
DESCRIBE TABLE gi_index_rows LINES l_lines.
IF l_lines = 0.
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'

EXPORTING
textline1 = 'You must choose a line'.
EXIT.
ENDIF.
* Read indexes of selected rows. In this example only one
* row can be selected as we are using gs_layout-sel_mode = 'B',
* so it is only ncessary to read the first entry in
* table gi_index_rows
LOOP AT gi_index_rows INTO g_selected_row.
IF sy-tabix = 1.
READ TABLE gi_sflight INDEX g_selected_row-index INTO g_wa_sflight.
ENDIF.
ENDLOOP.
* Transfer data from the selected row to screenm 200 and show
* screen 200
CLEAR g_screen200.
MOVE-CORRESPONDING g_wa_sflight TO g_screen200.
LEAVE TO SCREEN '200'.
ENDFORM.
" change_flight
*&---------------------------------------------------------------------*
*&
Form save_changes
*&---------------------------------------------------------------------*
* Changes made in screen 200 are written to the datbase table
* zsflight, and to the grid table gi_sflight, and the grid is
* updated with method refresh_table_display to display the changes
*----------------------------------------------------------------------*
FORM save_changes.
DATA: l_traffic_light TYPE c.
* Update traffic light field
* Update database table
MODIFY zsflight FROM g_screen200.
* Update grid table , traffic light field and color field.
* Note that it is necessary to use structure g_wa_sflight
* for the update, as the screen structure does not have a
* traffic light field
MOVE-CORRESPONDING g_screen200 TO g_wa_sflight.
IF g_wa_sflight-paymentsum < 100000.
g_wa_sflight-traffic_light = '1'.
* C = Color, 6=Color 1=Intesified on, 0: Inverse display off
g_wa_sflight-line_color = 'C610'.
ELSEIF g_wa_sflight-paymentsum => 100000 AND
g_wa_sflight-paymentsum < 1000000.
g_wa_sflight-traffic_light = '2'.
clear g_wa_sflight-line_color.
ELSE.
g_wa_sflight-traffic_light = '3'.
clear g_wa_sflight-line_color.
ENDIF.
MODIFY gi_sflight INDEX g_selected_row-index FROM g_wa_sflight.
* Refresh grid
CALL METHOD go_grid->refresh_table_display.

CALL METHOD cl_gui_cfw=>flush.


LEAVE TO SCREEN '100'.
ENDFORM.
" save_changes

The SAP picture control


Steps:

Create a screen
Place a custom container for the picture on the screen. Name the container
GO_PICTURE_CONTAINER.

* Type pool for using SAP icons


TYPE-POOLS: icon.
* Declarations
DATA:
go_picture
TYPE REF TO cl_gui_picture,
go_picture_container TYPE REF TO cl_gui_custom_container.
MODULE status_0100 OUTPUT.
IF go_picture_container IS INITIAL.
* Create obejcts for picture and container and
* setup picture control
CREATE OBJECT go_picture_container
EXPORTING
container_name = 'PICTURE_CONTAINER'.
CREATE OBJECT go_picture
EXPORTING
parent = go_picture_container.
* Set display mode (Stretching, original size etc.)
CALL METHOD go_picture->set_display_mode
EXPORTING
DISPLAY_MODE = CL_GUI_PICTURE=>display_mode_fit_center
EXCEPTIONS
= 1.
* Load picture from SAP Icons. To oad a picture from an URL use method
* load_picture_from_url
CALL METHOD go_picture->load_picture_from_sap_icons
EXPORTING
icon
= icon_delete
EXCEPTIONS error = 1.
ENDIF.
ENDMODULE.

The SAP Toolbar control

General
See also Set up event handling for controls for a general example of event handling
Note: To get a list of all icons, use program SHOWICON.
Add method

Adds a new button to the toolbar


CALL METHOD go_toolbar->add_button
EXPORTING fcode
= 'EXIT'
"Function Code for button
icon
= icon_system_end
"ICON name, You can use type pool ICON
is_disabled
=''
"Disabled = X
butn_type
= gc_button_normal
"Type of button, see below
text
= 'Exit'
"Text on button
quickinfo
= 'Exit program'
"Quick info
is_checked
= ' '.
"Button selected
Toolbar button types used in method ADD_BUTTON:
Value Constant
Meaning
0

cntb_btype_button

cntb_btype_dropdown Pushbutton with menu

cntb_btype_menu

Menu

cntb_btype_sep

Seperator

cntb_btype_group

Pushbutton group

cntb_btype_check

Checkbox

Button (normal)

Menu entry

Add_button_group method
This method is used to add a list of buttons to the toolbar. The buttons are defined in a table of type
TTB_BUTTON, and it can be filled witha button definitions using method fill_buttons_data_table of the
cl_gui_toolbar class. The button group is added to the toolbar using method add_button_group of the
toolbar object.
* 1. Declare a table for buttons
DATA: gi_button_group
TYPE ttb_button.
* 2. Create buttons in button table
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'Disable'
* icon
=
* DISABLED
=
butn_type
= cntb_btype_group
* TEXT
=
* QUICKINFO
=
* CHECKED
=
changing
data_table
= gi_button_group

* EXCEPTIONS
* CNTB_BTYPE_ERROR = 1
* others
=2
.
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table..... add more buttons to the table
*3. Add button group to toolbar
CALL METHOD go_toolbar->add_button_group
EXPORTING data_table = gi_button_group.
Set_button state method
Used to change the state of individual buttons at runtime. If the button should be removed, use the
delete_button method.
CALL METHOD go_toolbar->set_button_state
EXPORTING
* ENABLED
= 'X'
* CHECKED
=''
fcode
=
"Note: This is the function code of the button that should be changed
* EXCEPTIONS
* CNTL_ERROR
=1
* CNTB_ERROR_FCODE = 2
* others
=3
.
Simple example
This example shows how to create a toolbar with a single Exit button, used to exit the program.
Steps:
Create a screen and add a custom container named TOOLBAR_CONTAINER
Code:
REPORT sapmz_hf_toolbar .
TYPE-POOLS: icon.
CLASS cls_event_handler DEFINITION DEFERRED.
*GLOBAL DATA
DATA:
ok_code
LIKE sy-ucomm,
* Reference for conatiner
go_toolbar_container
TYPE REF TO cl_gui_custom_container,
* Reference for SAP Toolbar
go_toolbar
TYPE REF TO cl_gui_toolbar,
* Event handler
go_event_handler
TYPE REF TO cls_event_handler.
*GLOBAL TABLES
DATA:
* Table for registration of events. Note that a TYPE REF
* to cls_event_handler must be created before you can
* reference types cntl_simple_events and cntl_simple_event.

gi_events
TYPE cntl_simple_events,
* Workspace for table gi_events
g_event
TYPE cntl_simple_event.
*---------------------------------------------------------------------*
*
CLASS cls_event_handler DEFINITION
*---------------------------------------------------------------------*
*
........
*
*---------------------------------------------------------------------*
CLASS cls_event_handler DEFINITION.
PUBLIC SECTION.
METHODS:
on_function_selected
FOR EVENT function_selected OF cl_gui_toolbar
IMPORTING fcode,
on_dropdown_clicked
FOR EVENT dropdown_clicked OF cl_gui_toolbar
IMPORTING fcode posx posy.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS cls_event_handler IMPLEMENTATION
*---------------------------------------------------------------------*
*
........
*
*---------------------------------------------------------------------*
CLASS cls_event_handler IMPLEMENTATION.
METHOD on_function_selected.
CASE fcode.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
ENDCASE.
ENDMETHOD.
*

METHOD on_dropdown_clicked.
Not implented yet
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
SET SCREEN '100'.
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
*
text
*----------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
IF go_toolbar_container IS INITIAL.
* Create container
CREATE OBJECT go_toolbar_container
EXPORTING
container_name = 'TOOLBAR_CONTAINER'.
* Create toolbar
CREATE OBJECT go_toolbar
EXPORTING

parent = go_toolbar_container.
* Add a button
CALL METHOD go_toolbar->add_button
EXPORTING fcode
= 'EXIT'
"Function Code
icon
= icon_system_end "ICON name
is_disabled = ' '
"Disabled = X
butn_type = cntb_btype_button "Type of button
text
= 'Exit'
"Text on button
quickinfo = 'Exit program' "Quick info
is_checked = ' '.
"Button selected
* Create event table. The event ID must be found in the
* documentation of the specific control
CLEAR g_event.
REFRESH gi_events.
g_event-eventid = go_toolbar->m_id_function_selected.
g_event-appl_event = 'X'. "This is an application event
APPEND g_event TO gi_events.
g_event-eventid = go_toolbar->m_id_dropdown_clicked.
g_event-appl_event = 'X'.
APPEND g_event TO gi_events.
* Use the events table to register events for the control
CALL METHOD go_toolbar->set_registered_events
EXPORTING
events = gi_events.
* Create event handlers
CREATE OBJECT go_event_handler.
SET HANDLER go_event_handler->on_function_selected
FOR go_toolbar.
SET HANDLER go_event_handler->on_dropdown_clicked
FOR go_toolbar.
ENDIF.
ENDMODULE.

" STATUS_0100 OUTPUT

Advanced example
The toolbar in this example contains an Exit button, two buttons that enables/and disables a Print button,
and a Menu button with a context menu.
The Disable/Enable buttons are of type Pushbutton group which makes them act together, so when one of
the buttons are selected (Down) the other is deselected (Up).
Note that the context menu for the Menu button, must be created as a GUI status. You can create an
empty GUI sttaus of type context, and then manually add menus. The context menu instance is created
with type reference to class cl_ctmenu.
Steps:
Create a screen and add a custom container named TOOLBAR_CONTAINER
Create a GUI status of type Context and name it TOOLBAR. Note that you can not add any buttons
to the GUI sttaus at design time.

The screen:
In this screen shot the Disable button is activated which makes the Print button disabled:

This screenshot shows the context menu and sub menu:

The code:
REPORT sapmz_hf_toolbar .
TYPE-POOLS: icon.
CLASS cls_event_handler DEFINITION DEFERRED.
*--- G L O B A L D A T A
DATA:
ok_code
LIKE sy-ucomm,
* Global varables for position of context menu
g_posx
TYPE i,
g_posy
TYPE i,
* Reference for conatiner
go_toolbar_container
TYPE REF TO cl_gui_custom_container,
* Reference for SAP Toolbar
go_toolbar
TYPE REF TO cl_gui_toolbar,
* Event handler
go_event_handler
TYPE REF TO cls_event_handler,
* Context menu
go_context_menu
TYPE REF TO cl_ctmenu.
*--- G L O B A L T A B L E S
DATA:
* Table for registration of events. Note that a TYPE REF
* to cls_event_handler must be created before you can
* reference types cntl_simple_events and cntl_simple_event
gi_events
TYPE cntl_simple_events,
* Workspace for table gi_events
g_event
TYPE cntl_simple_event,
* Table for button group
gi_button_group
TYPE ttb_button.
*---------------------------------------------------------------------*
*
CLASS CLS_EVENT_HANDLER
*---------------------------------------------------------------------*
* This class handles the function_selected and dropdow_clicked events
* from the toolbar
*---------------------------------------------------------------------*

CLASS cls_event_handler DEFINITION.


PUBLIC SECTION.
METHODS:
on_function_selected
FOR EVENT function_selected OF cl_gui_toolbar
IMPORTING fcode,
on_dropdown_clicked
FOR EVENT dropdown_clicked OF cl_gui_toolbar
IMPORTING fcode posx posy.
ENDCLASS.
CLASS cls_event_handler IMPLEMENTATION.
METHOD on_function_selected.
*-- Actions for buttons and context menus
CASE fcode.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
WHEN 'ENABLE'.
* Enable the PRINT button
CALL METHOD go_toolbar->set_button_state
EXPORTING
enabled = 'X'
fcode = 'PRINT'.
WHEN 'DISABLE'.
* Disable the PRINT button
CALL METHOD go_toolbar->set_button_state
EXPORTING
enabled = ' '
fcode = 'PRINT'.
* Other menus and context menus
WHEN 'PRINT'.
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
EXPORTING
textline1 = 'Printing'.
WHEN 'CONTEXT1'.
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
EXPORTING
textline1 = 'Menu: Do something funny'.
WHEN 'CONTEXT2'.
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
EXPORTING
textline1 = 'Menu: Do something crazy'.
WHEN 'SUB1'.
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
EXPORTING
textline1 = 'Submenu: Do something boring'.
WHEN 'SUB2'.
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
EXPORTING
textline1 = 'Submenu: Do something good'.
ENDCASE.
ENDMETHOD.
METHOD on_dropdown_clicked.
*-- Fires when a dropdown menu is clicked. After it has been
*-- clicked a context menu is shown beside the button.
* Save x and y position of button for use with context menu

CLEAR: g_posx, g_posy.


g_posx = posx.
g_posy = posy.
* Create context menu for menu button
PERFORM create_context_menu.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
SET SCREEN '100'.
*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
*
text
*----------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
IF go_toolbar_container IS INITIAL.
* Create container
CREATE OBJECT go_toolbar_container
EXPORTING
container_name = 'TOOLBAR_CONTAINER'.
* Create toolbar
CREATE OBJECT go_toolbar
EXPORTING
parent = go_toolbar_container.
* Add a button to the toolbar
PERFORM add_button.
* Add a button group to the toolbar
PERFORM add_button_group.
* Create event table. Note that the event ID must be found in the
* documentation of the specific control
CLEAR g_event. REFRESH gi_events.
g_event-eventid = go_toolbar->m_id_function_selected.
g_event-appl_event = 'X'. "This is an application event
APPEND g_event TO gi_events.
CLEAR g_event.
g_event-eventid = go_toolbar->m_id_dropdown_clicked.
g_event-appl_event = 'X'.
APPEND g_event TO gi_events.
* Use the events table to register events for the control
CALL METHOD go_toolbar->set_registered_events
EXPORTING
events = gi_events.
* Create event handlers
CREATE OBJECT go_event_handler.

SET HANDLER go_event_handler->on_function_selected


FOR go_toolbar.
SET HANDLER go_event_handler->on_dropdown_clicked
FOR go_toolbar.
ENDIF.
ENDMODULE.
" STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
*&
Form add_button
*&---------------------------------------------------------------------*
* Adds one pushbutton to the toolbar
*----------------------------------------------------------------------*
FORM add_button.
CALL METHOD go_toolbar->add_button
EXPORTING fcode
= 'EXIT'
"Function Code
icon
= icon_system_end "ICON name
is_disabled = ' '
"Disabled = X
butn_type = cntb_btype_button "Type of button
text
= 'Exit'
"Text on button
quickinfo = 'Exit program' "Quick info
is_checked = ' '.
"Button selected
ENDFORM.
" add_button
*&---------------------------------------------------------------------*
*&
Form add_button_group
*&---------------------------------------------------------------------*
* Adds a button group to the toolbar.
* The buttons are added to table gi_button_group, and the table is used
* as input to the Add_button_group method. Note that method Fill_buttons
* is used to fill the table.
*----------------------------------------------------------------------*
FORM add_button_group.
* Add a seperator
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'SEP1'
icon
=''
butn_type
= cntb_btype_sep
CHANGING
data_table
= gi_button_group.
.
* Add an Enable button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'ENABLE'
icon
=''
butn_type
= cntb_btype_group
text
= 'Enable'
quickinfo
= 'Enable a print button'
checked
= 'X'
CHANGING
data_table
= gi_button_group.
.
* Add a Disable button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING

fcode
= 'DISABLE'
icon
= ''
butn_type
= cntb_btype_group
text
= 'Disable'
quickinfo
= 'Disable print button'
checked
=''
CHANGING
data_table
= gi_button_group.
* Add a seperator
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'SEP2'
icon
=''
butn_type
= cntb_btype_sep
CHANGING
data_table
= gi_button_group.
* Add print button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'PRINT'
icon
= icon_print
butn_type
= cntb_btype_button
text
= 'Print'
quickinfo
= 'Print something'
CHANGING
data_table
= gi_button_group.
* Add a menu button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'MENU'
icon
=''
butn_type
= cntb_btype_menu
text
= 'Menu'
quickinfo
= 'A menu buttonz'
CHANGING
data_table
= gi_button_group.
* Add button group to toolbar
CALL METHOD go_toolbar->add_button_group
EXPORTING data_table = gi_button_group.
ENDFORM.
" add_button_group
*&---------------------------------------------------------------------*
*&
Form create_context_menu
*&---------------------------------------------------------------------*
* This form creates a context menu and a submenu for the menu button.
*----------------------------------------------------------------------*
FORM create_context_menu.
DATA: lo_submenu TYPE REF TO cl_ctmenu.
IF go_context_menu IS INITIAL.
*-- Create context menu
CREATE OBJECT go_context_menu.

CALL METHOD go_context_menu->add_function


EXPORTING
fcode = 'CONTEXT1'
text = 'Do something funny'.
CALL METHOD go_context_menu->add_function
EXPORTING
fcode = 'CONTEXT2'
text = 'Do something crazy'.
CALL METHOD go_context_menu->add_separator.
* Create sub menu for the context menu
CREATE OBJECT lo_submenu.
CALL METHOD lo_submenu->add_function
EXPORTING
fcode = 'SUB1'
text = 'Do something boring'.
CALL METHOD lo_submenu->add_function
EXPORTING
fcode = 'SUB2'
text = 'Do something good'.
*-- Add sub menu to the context menu
CALL METHOD go_context_menu->add_submenu
EXPORTING
menu = lo_submenu
text = 'Do something else.....'.
ENDIF.
* Link menu to toolbar button. To position the context menu the
* x and y positions of the menu button is used.
* These values was retrieved in the On_dropdown_clicked
* method of cls_event_handler
CALL METHOD go_toolbar->track_context_menu
EXPORTING
context_menu = go_context_menu
posx
= g_posx
posy
= g_posy.
ENDFORM.

" create_context_menu

The SAP HTML viewer


Note that the SAP HTML viewer uses internet Explorer 4.0 or higher.
This example uses the SAP HTML viewer to browse the internet. The navigation buttons are placed on a
SAP Toolbar control. The Goto URL button and field are normal dynpro elements, and so is the Show URL
field.

Steps:

Create a screen and palce a container named go_html_container for the HTML viewer.
Create a dynpro button with ethe text GGoto url and functioncode GOTOURL.
Create a dynpro input/output field named G_SCREEN100_URL_TEXT. This field is used to key in
the url.
Create a dynpro input/output field named G_SCREEN100_DISPLAY_URL. This field is used to
show the current url

The screen:

The code

SAPMZ_HF_HTML_CONTROL
REPORT sapmz_hf_html_control .
TYPE-POOLS: icon.

CLASS cls_event_handler DEFINITION DEFERRED.


*------------------------------------------------------------------*GLOBAL VARIABLES
*------------------------------------------------------------------DATA:
ok_code
LIKE sy-ucomm,
* Container for html vieaer
go_html_container
TYPE REF TO cl_gui_custom_container,
* HTML viewer
go_htmlviewer
TYPE REF TO cl_gui_html_viewer,
* Container for toolbar
go_toolbar_container TYPE REF TO cl_gui_custom_container,
* SAP Toolbar
go_toolbar
TYPE REF TO cl_gui_toolbar,
* Event handler for toolbar
go_event_handler
TYPE REF TO cls_event_handler,
* Variable for URL text field on screen 100
g_screen100_url_text(255) TYPE c,
g_screen100_display_url(255) TYPE c.
*------------------------------------------------------------------*INTERNAL TABLES
*------------------------------------------------------------------DATA:
* Table for button group
gi_button_group
TYPE ttb_button,
* Table for registration of events. Note that a TYPE REF
* to cls_event_handler must be created before you can
* reference types cntl_simple_events and cntl_simple_event.
gi_events
TYPE cntl_simple_events,
* Workspace for table gi_events
g_event
TYPE cntl_simple_event.
START-OF-SELECTION.
SET SCREEN '100'.
*---------------------------------------------------------------------*
*
CLASS cls_event_handler DEFINITION
*--------------------------------------------------------------------* Handles events for the toolbar an the HTML viewer
*---------------------------------------------------------------------*
CLASS cls_event_handler DEFINITION.
PUBLIC SECTION.
METHODS:
* Handles method function_selected for the toolbar control
on_function_selected
FOR EVENT function_selected OF cl_gui_toolbar
IMPORTING fcode,
* Handles method navigate_complete for the HTML viewer control
on_navigate_complete
FOR EVENT navigate_complete OF cl_gui_html_viewer
IMPORTING url.
ENDCLASS.
CLASS cls_event_handler IMPLEMENTATION.

* Handles method function_selected for the toolbar control


METHOD on_function_selected.
CASE fcode.
WHEN 'BACK'.
CALL METHOD go_htmlviewer->go_back
EXCEPTIONS cntl_error = 1.
WHEN 'FORWARD'.
CALL METHOD go_htmlviewer->go_forward
EXCEPTIONS cntl_error = 1.
WHEN 'STOP'.
CALL METHOD go_htmlviewer->stop
EXCEPTIONS cntl_error = 1.
WHEN 'REFRESH'.
CALL METHOD go_htmlviewer->do_refresh
EXCEPTIONS cntl_error = 1.
WHEN 'HOME'.
CALL METHOD go_htmlviewer->go_home
EXCEPTIONS cntl_error = 1.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
ENDCASE.
ENDMETHOD.
* Handles method navigate_complete for the HTML viewer control
METHOD on_navigate_complete.
* Display current URL in a textfield on the screen
g_screen100_display_url = url.
ENDMETHOD.
ENDCLASS.

*&---------------------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
IF go_html_container IS INITIAL.
* Create container for HTML viewer
CREATE OBJECT go_html_container
EXPORTING
container_name = 'HTML_CONTAINER'.
* Create HTML viewer
CREATE OBJECT go_htmlviewer
EXPORTING parent = go_html_container.
* Create container for toolbar
CREATE OBJECT go_toolbar_container
EXPORTING
container_name = 'TOOLBAR_CONTAINER'.
* Create toolbar
CREATE OBJECT go_toolbar
EXPORTING
parent = go_toolbar_container.

* Add buttons to the toolbar


PERFORM add_button_group.
* Create event table. The event ID must be found in the
* documentation of the specific control
CLEAR g_event.
REFRESH gi_events.
g_event-eventid = go_toolbar->m_id_function_selected.
g_event-appl_event = 'X'. "This is an application event
APPEND g_event TO gi_events.
g_event-eventid = go_htmlviewer->m_id_navigate_complete.
APPEND g_event TO gi_events.
* Use the events table to register events for the control
CALL METHOD go_toolbar->set_registered_events
EXPORTING
events = gi_events.
CALL METHOD go_htmlviewer->set_registered_events
EXPORTING
events = gi_events.
* Create event handlers
CREATE OBJECT go_event_handler.
SET HANDLER go_event_handler->on_function_selected
FOR go_toolbar.
SET HANDLER go_event_handler->on_navigate_complete
FOR go_htmlviewer.
ENDIF.
ENDMODULE.
" STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
*&
Module USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
MODULE user_command_0100 INPUT.
* Handles the pushbutton for goto url
CASE ok_code.
WHEN 'GOTOURL'.
PERFORM goto_url.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Form add_button_group
*&---------------------------------------------------------------------*
* Adds a button group to the toolbar
*----------------------------------------------------------------------FORM add_button_group.
* BACK botton
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'BACK'
icon
= icon_arrow_left
butn_type
= cntb_btype_button

text
= ''
quickinfo
= 'Go back'
CHANGING
data_table
= gi_button_group.
* FORWARD botton
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'FORWARD'
icon
= icon_arrow_right
butn_type
= cntb_btype_button
text
= ''
quickinfo
= 'Go forward'
CHANGING
data_table
= gi_button_group.
* STOP button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'STOP'
icon
= icon_breakpoint
butn_type
= cntb_btype_button
text
= ''
quickinfo
= 'Stop'
CHANGING
data_table
= gi_button_group.
* REFRESH button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'REFRESH'
icon
= icon_refresh
butn_type
= cntb_btype_button
text
= ''
quickinfo
= 'Refresh'
CHANGING
data_table
= gi_button_group.
* Home button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'HOME'
icon
= ''
butn_type
= cntb_btype_button
text
= 'Home'
quickinfo
= 'Home'
CHANGING
data_table
= gi_button_group.
* Separator
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table
EXPORTING
fcode
= 'SEP1'
icon
=''
butn_type
= cntb_btype_sep
CHANGING
data_table
= gi_button_group.
* EXIT button
CALL METHOD cl_gui_toolbar=>fill_buttons_data_table

EXPORTING
fcode
= 'EXIT'
icon
= icon_close
butn_type
= cntb_btype_button
text
= ''
quickinfo
= 'Close porgram'
CHANGING
data_table
= gi_button_group.
* Add button group to toolbar
CALL METHOD go_toolbar->add_button_group
EXPORTING data_table = gi_button_group.
ENDFORM.
" add_button_group
*&---------------------------------------------------------------------*
*&
Form goto_url
*&---------------------------------------------------------------------*
* Calls method SHOW_URL to navigate to an URL
*---------------------------------------------------------------------FORM goto_url.
CALL METHOD go_htmlviewer->show_url
EXPORTING url = g_screen100_url_text.
ENDFORM.

" goto_url

The dialog box container and the splitter container


The dialog box container and the splitter container
This example shows how to use the dialogbox container and the splitter container.
A dialogbox container is created, and a splitter container with 2 rows and 1 column is placed on it.
To keep the example simple row 1 of the splitter container is not used, but you can use it to place a
control.
Row 2 is used to place a toolbar control in the buttom of the dialogbox. The toolbar has an OK and a
Cancel button. To keep the example simple, these 2 buttons only closes the dialog screen. The dialogbox
can also be closed by using the close button in the top right corner of the dialogbox. This button is
standard fucntionallity, however you have to do the coding for closing the dialogbox yourself.
Steps:
Create a screen
Place dynpro button on the screen that opens the dialogbox. Name: DIALOG_BUTTON. Caption:
Show dialog box. Function code: DIALOG
Place another dynpro on the screen to exit the program. Name: EXIT_BUTTON. Caption: Exit.
Function code: EXIT.
Place a custom control on the screen for the dialog box. Name: DIALOG_CONTAINER
Place a custom control on the screen for the toolbar control. Name: TOOLBAR_CONTAINER
The screen:

The code:
REPORT sapmz_hf_dialogbox_cont.
* Icons for the toolbar
TYPE-POOLS:icon.
* Predefinition of the event handler class. Necessary if
* you want to make references to the class before it is defined
CLASS lcl_event_handler DEFINITION DEFERRED.
*---------------------------------------------------------------------*GLOBAL DATA
*---------------------------------------------------------------------DATA:
ok_code LIKE sy-ucomm,
* Dialog container
go_dialog_container
TYPE REF TO cl_gui_dialogbox_container,
* Splitter container
go_splitter_container
TYPE REF TO cl_gui_splitter_container,
* Event handler class
go_event_handler
TYPE REF TO lcl_event_handler,
* SAP Toolbar
go_toolbar
TYPE REF TO cl_gui_toolbar.
*---------------------------------------------------------------------* Table and workarea for registration of events. Note that a TYPE REF
* to cls_event_handler must be created before you can
* reference types cntl_simple_events and cntl_simple_event.
*---------------------------------------------------------------------DATA:
gi_events
TYPE cntl_simple_events,
g_event
TYPE cntl_simple_event.
*---------------------------------------------------------------------*
*
CLASS lcl_event_handler
*---------------------------------------------------------------------*

* This class is used to handle events from the dialobox


* and the toolbar
*---------------------------------------------------------------------*
CLASS lcl_event_handler DEFINITION.
PUBLIC SECTION.
METHODS:
* Close event of the dialogbox
on_close
FOR EVENT close OF cl_gui_dialogbox_container
IMPORTING sender,
* Select event of the toolbar
on_function_selected
FOR EVENT function_selected OF cl_gui_toolbar
IMPORTING fcode.
ENDCLASS.
CLASS lcl_event_handler IMPLEMENTATION.
*---------------------------------------------------------------------* Handles the Close event of the dialogbox. The colse event is
* triggered when the close button in the top right corner of the
* dialogbox is pushed. Closes the dialog box
*---------------------------------------------------------------------METHOD on_close.
IF NOT sender IS INITIAL.
CALL METHOD sender->free
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
*
Error handling
ENDIF.
FREE go_dialog_container.
CLEAR go_dialog_container.
ENDIF.
ENDMETHOD.
*---------------------------------------------------------------------* Handles the Function Selected event of the toolbar, which is
* triggered when one of the buttons on the toolbar is pushed.
* Both pushbuttons closes the dialogbox
*---------------------------------------------------------------------METHOD on_function_selected.
CASE fcode.
WHEN 'OK'.
CALL METHOD go_dialog_container->free.
FREE go_dialog_container.
CLEAR go_dialog_container.
WHEN 'CANCEL'.
CALL METHOD go_dialog_container->free.
FREE go_dialog_container.
CLEAR go_dialog_container.
ENDCASE.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
* Necessary to get access to certain predefined constants

CLASS cl_gui_cfw DEFINITION LOAD.


SET SCREEN '100'.
*&---------------------------------------------------------------------*
*&
Module USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
* Handles the 2 dynpro pushbuttons on screen
*---------------------------------------------------------------------MODULE user_command_0100 INPUT.
CASE ok_code.
WHEN 'EXIT'.
LEAVE TO SCREEN 0.
WHEN 'DIALOG'.
PERFORM show_dialog_box.
ENDCASE.
ENDMODULE.
" USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
*&
Form show_dialog_box
*&---------------------------------------------------------------------*
* Performed when the Show dialog box button is pushed.
*----------------------------------------------------------------------*
FORM show_dialog_box.
IF go_dialog_container IS INITIAL.
*---------------------------------------------------------------------* Create Dialogbox
*---------------------------------------------------------------------CREATE OBJECT go_dialog_container
EXPORTING
*
PARENT
=
width
= 400
height
= 150
style
= cl_gui_control=>ws_sysmenu
*
REPID
=
*
dynnr
= '100'
*
LIFETIME
= lifetime_default
top
= 100
left
= 350
caption
= 'My dialog box'
*
NO_AUTODEF_PROGID_DYNNR =
*
METRIC
=0
*
NAME
=
EXCEPTIONS
CNTL_ERROR
=1
CNTL_SYSTEM_ERROR
=2
CREATE_ERROR
=3
LIFETIME_ERROR
=4
LIFETIME_DYNPRO_DYNPRO_LINK = 5
EVENT_ALREADY_REGISTERED = 6
ERROR_REGIST_EVENT
=7
others
= 8.
IF sy-subrc <> 0.
*
Do some error handling..............
ENDIF.

*----------------------------------------------------------------------

* Create Splitter container and configure


*---------------------------------------------------------------------CREATE OBJECT go_splitter_container
EXPORTING
parent
= go_dialog_container
rows
= 2
columns
=1
EXCEPTIONS
others = 1.
IF sy-subrc <> 0.
*
Do some error handling..............
ENDIF.
* Set row height for row 1
CALL METHOD go_splitter_container->set_row_height
EXPORTING
id
=1
height
= 90.
* The splitter container should not have a border
CALL METHOD go_splitter_container->set_border
EXPORTING
border = cl_gui_cfw=>false.
* Configure the splitter bar. The splitterbar is configures
* so that it can't be moved
CALL METHOD go_splitter_container->set_row_sash
EXPORTING
id
= 1 "Configure splitter bar no. 1
type
= 0 "Type_movable
value
= 0. "False

*---------------------------------------------------------------------* Create Toolbar and set parent to the Splitter container


*---------------------------------------------------------------------CREATE OBJECT go_toolbar
EXPORTING
parent = go_splitter_container
EXCEPTIONS
others = 1.
IF sy-subrc <> 0.
ENDIF.
* Add a buttons
CALL METHOD go_toolbar->add_button
EXPORTING
fcode
= 'OK'
"Function Code
icon
= icon_okay
"ICON name
is_disabled = ' '
"Disabled = X
butn_type = cntb_btype_button "Type of button
text
= 'OK'
"Text on button
is_checked = ' '
"Button selected
EXCEPTIONS
OTHERS
= 1.
IF sy-subrc <> 0.
*
Do some error handling..............

ENDIF.
CALL METHOD go_toolbar->add_button
EXPORTING
fcode
= 'CANCEL'
"Function Code
icon
= icon_cancel
"ICON name
is_disabled = ' '
"Disabled = X
butn_type = cntb_btype_button "Type of button
text
= 'Cancel'
"Text on button
is_checked = ' '
"Button selected
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
*
Do some error handling..............
ENDIF.
*---------------------------------------------------------------------* Add Toolbar control to row 2 of the Splitter container
*---------------------------------------------------------------------CALL METHOD go_splitter_container->add_control
EXPORTING row = 2
column = 1
control = go_toolbar.
*---------------------------------------------------------------------* Create object for the event handler class
*---------------------------------------------------------------------CREATE OBJECT go_event_handler.
*---------------------------------------------------------------------* Set Handler for the dialog container. Note that you don't have to
* register the events for this class
*---------------------------------------------------------------------SET HANDLER go_event_handler->on_close
FOR go_dialog_container.
*---------------------------------------------------------------------* Create event handler table for the toolbar control, and register
* the events
*---------------------------------------------------------------------* Create event table. The event ID must be found in the
* documentation of the specific control
CLEAR g_event.
REFRESH gi_events.
g_event-eventid = go_toolbar->m_id_function_selected.
g_event-appl_event = 'X'. "This is an application event
APPEND g_event TO gi_events.
* Use the events table to register events for the control
CALL METHOD go_toolbar->set_registered_events
EXPORTING
events = gi_events.
* Set handler
SET HANDLER go_event_handler->on_function_selected
FOR go_toolbar.
* Synchronization

CALL METHOD cl_gui_cfw=>flush.


ENDIF.
ENDFORM.

" show_dialog_box

You might also like