We all know about ALV reports and the flexibility and user friendliness that ALV offers to users and ease of development for the technical consultants.
However, off late I have seen requirements where the users want dynamically add or remove columns depending on the data selected. For example, there is a report which compares the same set of fields for a given dimension. To be more precise if for a vendor / RFQ, you want to compare a list of fields and the user wants the comparison to be displayed vertically, that means more number of vendors / RFQs, more number of fields need to be added to the output.
Now to the field catalog you can add more fields at runtime depending on the data coming in. However, how to add more columns to the internal table that will be used to display the data on the ALV grid. One crude of way doing is declare an internal table big enough to handle maximum fields and depending on the actual fields coming in at runtime, build the field catalog only for those field required so that the extra fields will not be visible. However, this is not the efficient way doing the same and more over you have every chance that the code might short dump as the field catalog and the structure of the output internal table are in sync.
So the elegant solution for this is to create a table dynamically, with the list of the fields that we have determined at run time. The question is how do we do that. Here is a quick solution.
1. Create your field catalog either manually or automatically using the function module, LVC_FIELDCATALOG_MERGE. Add more rows to the field catalog table (T_FIELDCAT) at run time.
2. Use the field catalog to create a table dynamically using the method below.
DATA: T_OUTPUT TYPE REF TO DATA
FIELD-SYMBOLS: <T_OUTPUT> TYPE TABLE
Call Method CL_ALV_TABLE_CREATE->CREATE_DYNAMIC_TABLE
IT_FIELDCATALOG = T_FIELDCAT
EP_TABLE = T_OUTPUT
ASSIGN T_OUTPUT->* TO <T_OUTPUT>.
Now the field symbol <T_OUTPUT> is pointing to an output table of the structure that contains the fields which were determined at runtime. Now fill this table with the data and pass <T_OUTPUT> to the method SET_TABLE_FOR_FIRST_DISPLAY and the ALV grid should show the data properly.
However, if you want to access or modify or fill in the data for specific columns, you have to use the ASSIGN COMPONENT statement for the specific field name and do it.