How to do Sorting and grouping in ALV Table through CL_SALV_SORTS

The sorting and grouping of data in ALV Table can be programmatically achieved. The method add_sort( ) of the class CL_SALV_SORTS can be used to sort or group the data. This sorting object is created from the get_sorts( ) method of the ALV Object.

DATA lr_salv_sorts TYPE REF TO cl_salv_sorts.

Lr_salv_sorts = lr_salv_table->get_sorts( ).

Lr_salv_sorts->add_sort( EXPORTING columnname = ‘AGE’

                                                          sequence       = if_salv_c_sort=>sort_up ).

The following sorting and grouping options are available.

If_salv_c_sort=>sort_none.

If_salv_c_sort=>sort_up.

If_salv_c_sort=>sort_down.

If_salv_c_sort=>group_with_underline.

If_salv_c_sort=>group_with_newpage.

If_salv_c_sort=>group_none.

How to sort columns by default in SAP ALV List.

The colums can be sorted by default in the ALV table. So that it is sorted initially when it is first displayed.

              The internal table of type LVC_T_SORT can be used for this purpose.

              The following key fields of LVC_T_SORT to be filled are:

Fieldname: The column to be sorted must be mentioned in this field.

UP: If the column must be sorted in increasing or ascending order,then the value ‘X’ must be set to the field ‘UP’.

DOWN: If the column must be sorted in descending or decreasing order, then the value ‘X’must be set to the field ‘DOWN’.

SPOS: If two or more columns must be sorted. Then we can prioritize the sorting sequence. For example, second column must be sorted before the first column.

Let us look at the ALV table sorting with the following example.

DATA lt_sort TYPE lvc_t_sort.

DATA ls_sort TYPE lvc_s_sort.

              ls_sort-spos = 1.

              ls_sort-fieldname = ‘CONTACT_NAME’.

              ls_sort-up = ‘X’.

              APPEND ls_sort TO lt_sort.

              ls_sort-spos = 2.

              ls_sort-fieldname = ‘CONTACT_ID’.

              ls_sort-down =’X’.

              APPEND ls_sort TO lt_sort.

              CALL METHOD lr_gui_alv_grid -> set_table_for_first_display

                            EXPORTING

                                          is_layout = ls_layout

                            CHANGING

                                          it_outtab = lt_contact

                                          it_fieldcatalog = lt_field_cat

                                          it_sort = lt_sort.