abapalv

Event for header click in ALV grid?


Is it possible to catch single button click on the ALV Grid column header ? I know about possibilities to catch double_click, create event for the hotspot on the cell. I have not found yet one header click. (I do not want to provide sort or any other data options). Only thing I found is event click_col_header OF cl_gui_alv_grid but it is protected so I am not able to provide my action. Thank you in advance !


Solution

  • Yes. Here is how to do it with CL_GUI_ALV_GRID:

    • Set the ALV layout setting SGL_CLK_HD = 'X' (this activates the sorting of rows based on the clicked column)
    • Redefine the sorting behavior with your own code, by handling the event BEFORE_USER_COMMAND and set a new command with the method SET_USER_COMMAND
    • Define the new behavior you want during the event USER_COMMAND
    • Use the method GET_SELECTED_COLUMNS to know which column has been clicked

    (PS: if one wonders, CL_GUI_ALV_GRID has the event CLICK_COL_HEADER, but it's never triggered)

    Here is a demo (also posted below Raymond answer in the SAP forum):

    CLASS lcl_alv DEFINITION.
      PUBLIC SECTION.
        METHODS constructor.
        METHODS free.
        METHODS on_before_user_command FOR EVENT before_user_command OF cl_gui_alv_grid IMPORTING e_ucomm.
        METHODS on_user_command FOR EVENT user_command OF cl_gui_alv_grid IMPORTING e_ucomm.
        DATA go_alv TYPE REF TO cl_gui_alv_grid.
        DATA gt_sflight TYPE TABLE OF sflight.
    ENDCLASS.
    
    CLASS lcl_alv IMPLEMENTATION.
    
      METHOD constructor.
        CREATE OBJECT go_alv
          EXPORTING
            i_parent = cl_gui_container=>screen0.
    
        SET HANDLER on_user_command FOR go_alv.
        SET HANDLER on_before_user_command FOR go_alv.
    
        SELECT * FROM sflight INTO TABLE gt_sflight.
        go_alv->set_table_for_first_display(
            EXPORTING
              i_structure_name = 'SFLIGHT'
              is_layout = VALUE #( sgl_clk_hd = abap_true )
            CHANGING
              it_outtab = gt_sflight ).
      ENDMETHOD.
    
      METHOD free.
        go_alv->free( ).
      ENDMETHOD.
    
      METHOD on_before_user_command.
        CASE e_ucomm.
          WHEN go_alv->mc_fc_sort.
            go_alv->set_user_command( i_ucomm = 'ZZSORT' ).
        ENDCASE.
      ENDMETHOD.
    
      METHOD on_user_command.
        CASE e_ucomm.
          WHEN 'ZZSORT'.
            go_alv->get_selected_columns( IMPORTING et_index_columns = data(columns) ).
            MESSAGE |Columns: { COND #( WHEN lines( columns ) > 0 THEN columns[ 1 ]-fieldname ) }| TYPE 'I'.
        ENDCASE.
      ENDMETHOD.
    
    ENDCLASS.
    
    DATA go_alv TYPE REF TO lcl_alv.
    
    PARAMETERS dummy.
    
    AT SELECTION-SCREEN OUTPUT.
      IF go_alv IS NOT BOUND.
        go_alv = NEW lcl_alv( ).
      ENDIF.
    
    AT SELECTION-SCREEN ON EXIT-COMMAND.
      go_alv->free( ).
      FREE go_alv.