Monday, August 1, 2011

ALV Checkbox, Select All & Filter

Often in editable ALV, we come across a requirement to add a checkbox and have select all & deselect all buttons in ALV toolbar. This blog is not about how to add a check box or buttons to the toolbar. Even the code for select all button is easy i.e. just loop at the internal table, mark the checkbox column as 'X' and then use method refresh_table_display to show it. However there is a small hiccup when one uses the filter option. Lets say we are displaying 10 Purchase Orders(PO) 101...110 and we want to update the PO quantity. And we use the filter option to select the POs 106 till 110. This can be esily done using the standard filter option. But what now if you use the select all option??? All the POs will be selected i.e. 101 till 110 instead of 106 till 110. And when you update the quantity and press the save button, all the 10 POs will get updated. However we want to update only 5 POs. The trick over here to select only the non filtered entries is to use the method get_filtered_entries of class cl_gui_alv_grid to get the filtered entries(i.e. hidden) and then mark 'X' against those records which are not filtered. 

Following code should be written on clicking the select all button.

  DATA: wa_out             TYPE ty_out,                  " Output Table for Display
              i_filter_entries  TYPE lvc_t_fidx,             " Filtered entries
              l_tabix              TYPE sy-tabix,                " Index
              l_valid              TYPE c,                          " Flag     
              ls_stable          TYPE lvc_s_stbl.            " WA for LVC_S_STBL

Note - 1. g_grid is the object reference for CL_GUI_ALV_GRID class.
           2. it_out is the internal table for display.

  CALL METHOD g_grid->check_changed_data
    IMPORTING
      e_valid = l_valid. 
 IF l_valid EQ 'X'.
    CALL METHOD g_grid->get_filtered_entries
      IMPORTING
        et_filtered_entries = i_filter_entries.
    LOOP AT it_out INTO wa_out.
      l_tabix = sy-tabix.
      READ TABLE i_filter_entries FROM l_tabix TRANSPORTING NO FIELDS.
      IF sy-subrc IS NOT INITIAL.
        wa_out-chk = 'X'.
        MODIFY it_out INDEX l_tabix FROM wa_out TRANSPORTING chk.
      ENDIF.
    ENDLOOP.
   
    ls_stable-row = 'X'.
    ls_stable-col  = 'X'.

    CALL METHOD g_grid->refresh_table_display
      EXPORTING
        is_stable = ls_stable.

  ENDIF.

5 comments: