How To Create Events in Local Class ABAP OOPS

Events in Local Class

Events are used to raise a message if any condition is met.

For example, in our program we have a code where we need to fetch vendor details based on vendor entered in input. If the vendor is not found, then we can display the error message by triggering the event.

Similarly, the events can be raised when some cutoff limit is not reached, or when the sum of amounts of table crosses some threshold limit.

Like methods, Events are also of two types - Instance Event and Static Event.

Instance events are declared using keyword EVENTS and can be triggered only in instance methods.
Static events are declared using keyword CLASS-EVENTS and can be triggered only in static methods.

Steps involved in Event Handling:

1. Declare Event in class definition

CLASS <class-name> DEFINITION.
  PUBLIC SECTION.
    EVENTS: <event_name>.
ENDCLASS.

2. Declare Event Handler Method for event of that class.

CLASS <class-name> DEFINITION.
  PUBLIC SECTION.
    METHODS: <event-handler-method> FOR EVENT <event_name> OF <class-name>.
ENDCLASS.

3. Implement Event Handler Method code in Class Implementation
 
CLASS <class-name> IMPLEMENTATION.
  METHOD <event-handler-method>.
	---
  ENDMETHOD.
ENDCLASS.

4. Set handler for the event handler method

DATA(lo_obj) = NEW <class-name>( ). " class-name in which the event method is created
SET HANDLER lo_obj-><event-handler-method> FOR <class-name>. " class name where event is defined

5. Trigger event using keyword Raise event if any condition is not met based on requirement
 
RAISE EVENT <event_name>.

CODE:

The below program displays the No vendor found message if the vendor entered in screen input doesn't exist in LFA1 table.

REPORT zprogram_vend.

PARAMETERS: p_lifnr TYPE lifnr.

CLASS lcl_main DEFINITION.
  PUBLIC SECTION.
    EVENTS: no_vendor_found.
    METHODS: get_vendor_details
      IMPORTING iv_lifnr TYPE lifnr
      EXPORTING es_lfa   TYPE lfa1.
ENDCLASS.

CLASS lcl_event_handler DEFINITION.
  PUBLIC SECTION.
    METHODS: event_handler FOR EVENT no_vendor_found OF lcl_main.
ENDCLASS.

START-OF-SELECTION.

  DATA(lo_main) = NEW lcl_main( ).
  DATA(lo_event_handler) = NEW lcl_event_handler( ).
  SET HANDLER lo_event_handler->event_handler FOR lo_main.

  lo_main->get_vendor_details(
    EXPORTING
      iv_lifnr = p_lifnr
    IMPORTING
      es_lfa = DATA(ls_lfa)
  ).

CLASS lcl_main IMPLEMENTATION.
  METHOD get_vendor_details.

    SELECT SINGLE * FROM lfa1
      INTO es_lfa
     WHERE lifnr = iv_lifnr.
    IF sy-subrc NE 0.
      RAISE EVENT no_vendor_found.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

CLASS lcl_event_handler IMPLEMENTATION.
  METHOD event_handler.

    WRITE: 'NO VENDOR FOUND'.
  ENDMETHOD.
ENDCLASS.

Post a Comment

Previous Post Next Post