2024 Mar 21 4:47 AM
Hi Experts,
I read the below thread but that goes with a structure and fieldcat methodology that will not suit my requirement.
So, please consider this request and let us know your valuable solutions/comments.
My requirement is to use the variable names as a field name.
For ex: lv_zbatch , lv_zmatnr, lv_zauto_date are the variables which I want to use these as field names (like zbatch, zmatnr, zauto_date) instead of hard coded value or using text element values.
Currently, I declared using text-001 as field name but due to code review process, I have to avoid this and go with other way solution.
Please note, I don't have any structure and these are local variables.
Thanks in advance.
Kind regards.
2024 Mar 21 7:57 AM - edited 2024 Mar 21 8:01 AM
The following code is wrong because text-001 is for translatable texts but a field name should not be translated:
* anti-pattern
DATA(field_name_1) = text-001.
DATA(field_name_zmatnr) = 'ZMATNR'(001).
The following code is correct if the field name is used only once in the code (despite the "historic tendency in ABAP to wrap every literal in constants" (styleguides/clean-abap/CleanABAP.md at main · SAP/styleguides (github.com))):
DATA(field_name) = `ZMATNR`.
The following code is correct according to "There is a historic tendency in ABAP to wrap every literal in constants" (styleguides/clean-abap/CleanABAP.md at main · SAP/styleguides (github.com)) or if the field name is used more than once in the program:
CONSTANTS:
BEGIN OF alv_field_names,
zbatch TYPE string VALUE `ZBATCH`,
zmatnr TYPE string VALUE `ZMATNR`,
END OF alv_field_names.
There is a last solution where you get the name by combining RTTS and DESCRIBE DISTANCE, which you have to code yourself as I don't have the code available right now:
CONSTANTS alv_fields TYPE ... " any structure
DATA(alv_field_names) = zcl_abap_get_comp_names=>create( alv_fields ).
DATA(alv_field_name_zmatnr) = alv_field_names->get( alv_fields-zmatnr ).
2024 Mar 21 6:15 PM
As I said, "you have to code yourself as I don't have the code available right now".
2024 Mar 21 5:03 PM
Hi Sandra_Rossim
Thank you for your response.
Instead of declaring the constants or hard coded values like 'ZMATNR' , is there a way using offset or getting it from the variable lv_zmatnr. After lv_[name] , the name will be fetched as fieldname.
I also understand to achieve it by declaring a structure or the fields in the class method. I have a similar one, defined it as a structure and derive it from the field cat.
DATA(alv_field_names) = zcl_abap_get_comp_names=>create( alv_fields ).
2024 Mar 21 6:14 PM
Please do not post a solution. Instead, click on the "Reply" of the answer.
2024 Mar 22 8:46 AM
As Sandra referenced the style guide, I'd also add that prefixes such as lv_ are discouraged. Just use meaningful names as in all strongly typed programming languages.