Requirement
Recently we had a requirement to create a dynamic ALV. The number of columns in the output would vary depending upon the number of unique records in another table say ZRECORD. If ZRECORD had 7 unique records, our ALV should have 7 columns with column name represented by the key field of ZRECORD.
Solution
1. Define three field symbols.
<fs_dyntable> TYPE standard table
<fs_dyn_wa> TYPE any
<fs_dyn_field> TYPE any.
2. Create a table similar to fieldcatalogue of type lvc_t_fcat (t_fieldcat) by looping through ZRECORD and appending column names depending upon the key field of ZRECORD to t_fieldcat.
3. T_fieldcat is passed too cl_alv_table_create=>create_dynamic_table and the new imported table is assigned to <fs_dyntable>
4. <fs_dyn_wa> is created as line of <fs_dyntable> as shown below.
CREATE DATA wa_new_line LIKE LINE OF <fs_dyntable>.
ASSIGN wa_new_line->* TO <fs_dyn_wa> (wa_new_line is reference type of DATA)
5. Each row of this dynamic table now can be filled using
ASSIGN COMPONENT (n) (column number)
OF STRUCTURE <fs_dyn_wa> TO <fs_dyn_field>.
<fs_dyn_field> = (data need to input).
6. After filling each row append <fs_dyn_wa> to <fs_dyntable>
7. Pass <fs_dyntable> to REUSE_ALV_GRID_DISPLAY as t_outtab, along with the new fieldcatalogue and other desired parameters.