================
CODE SNIPPETS
================
TITLE: abapGit Repository URL for ABAP Cheat Sheets
DESCRIPTION: This snippet provides the Git repository URL for the SAP ABAP Cheat Sheets. This URL is essential when configuring a new online repository in `abapGit` to import the demo examples into an ABAP system.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/README.md#_snippet_2
LANGUAGE: Plaintext
CODE:
```
https://github.com/SAP-samples/abap-cheat-sheets.git
```
--------------------------------
TITLE: abapGit Repository URL for ABAP Cheat Sheets
DESCRIPTION: The GitHub repository URL to be used when linking a new abapGit repository in the SAP BTP ABAP environment via the ABAP Development Tools (ADT) plug-in.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/README.md#_snippet_0
LANGUAGE: Shell
CODE:
```
https://github.com/SAP-samples/abap-cheat-sheets.git
```
--------------------------------
TITLE: Check ABAP System Release (sy-saprl)
DESCRIPTION: This ABAP code snippet demonstrates how to retrieve and display the current ABAP system release using the `sy-saprl` system field. It's used as a prerequisite check to ensure compatibility with available ABAP examples.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/README.md#_snippet_1
LANGUAGE: ABAP
CODE:
```
DATA rel LIKE sy-saprl.
rel = sy-saprl.
BREAK-POINT.
```
--------------------------------
TITLE: ABAP RTTI Example: Initial Data Declaration and Class Setup
DESCRIPTION: This ABAP code defines the `zcl_demo_abap` class, implementing `if_oo_adt_classrun`, which serves as the foundation for an RTTI exploration example. It declares various data objects of different types (elementary, enumerated, structured, internal tables, and reference variables) that will be used as input for RTTI methods to retrieve their type information. This snippet sets up the environment and initial data for the RTTI demonstration.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_130
LANGUAGE: abap
CODE:
```
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_demo_abap IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
"Data objects to work with in the example
DATA itab_refs TYPE TABLE OF REF TO data.
DATA str_tab TYPE string_table.
DATA dyn_dobj TYPE REF TO data.
DATA dyn_obj TYPE REF TO object.
DATA tdo TYPE REF TO cl_abap_typedescr.
"Data objects of different kinds based on which type information shall be retrieved
"Elementary type
DATA elem_dobj TYPE c LENGTH 4 VALUE 'ABAP'.
"Enumerated type
TYPES: BEGIN OF ENUM enum_t,
enum1,
enum2,
enum3,
END OF ENUM enum_t.
DATA(dobj_enum) = enum2.
"Structured types
DATA(struct) = VALUE zdemo_abap_carr( carrid = 'XY' carrname = 'XY Airlines' ).
"BDEF derived type (structure)
DATA struct_rap TYPE STRUCTURE FOR CREATE zdemo_abap_rap_ro_m.
"Internal table types
"Standard table with standard table key
DATA(string_table) = VALUE string_table( ( `AB` ) ( `AP` ) ).
"Local structured type as basis for a sorted internal table that
"includes primary and secondary table key specifiactions (including
"an alias name)
TYPES: BEGIN OF struc_type,
a TYPE c LENGTH 3,
b TYPE i,
c TYPE decfloat34,
END OF struc_type.
TYPES tab_type TYPE SORTED TABLE OF struc_type
WITH UNIQUE KEY a
WITH NON-UNIQUE SORTED KEY sec_key ALIAS sk COMPONENTS b c .
DATA(sorted_tab) = VALUE tab_type( ( a = 'aaa' ) ).
"Reference variables
"Data reference variable
DATA(dref) = NEW i( 123 ).
"Object reference variable
DATA(oref) = NEW zcl_demo_abap_objects( ).
"Interface reference variable
```
--------------------------------
TITLE: ABAP Internal Table Construction with CORRESPONDING and Lookup Table Example
DESCRIPTION: This example demonstrates the setup for constructing internal tables by joining a source internal table with a lookup table using the `CORRESPONDING` operator. It defines the necessary structured types and initializes a source internal table `it1` for subsequent operations.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/05_Constructor_Expressions.md#_snippet_37
LANGUAGE: ABAP
CODE:
```
"The following examples construct an internal tables by joining an internal table
"and a lookup table and comparing their components.
TYPES:
BEGIN OF s1,
character TYPE c LENGTH 1,
text TYPE string,
END OF s1,
it_type TYPE STANDARD TABLE OF s1 WITH EMPTY KEY,
lookup_tab_type TYPE HASHED TABLE OF s1 WITH UNIQUE KEY character.
DATA(it1) = VALUE it_type( ( character = 'a' ) ( character = 'b' ) ( character = 'c' ) ( character = 'd' )
```
--------------------------------
TITLE: ABAP Unit Test Class with Fixture Methods Example
DESCRIPTION: This ABAP code demonstrates the structure of a local test class, including the declaration and implementation of special fixture methods (setup, teardown) and test methods. It shows how to initialize objects and prepare/clean up test data within the fixture methods, ensuring a clean state for each test.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/14_ABAP_Unit_Tests.md#_snippet_8
LANGUAGE: ABAP
CODE:
```
"Test class, declaration part
CLASS ltc_test_class DEFINITION
FOR TESTING
RISK LEVEL HARMLESS
DURATION SHORT.
PRIVATE SECTION.
DATA ref_cut TYPE REF TO cl_class_under_test.
METHODS:
"special methods
setup,
teardown,
"test methods
some_test_method FOR TESTING,
another_test_method FOR TESTING.
ENDCLASS.
"Test class, implementation part
CLASS ltc_test_class IMPLEMENTATION.
METHOD setup.
"Creating an object of the class under test
ref_cut = NEW #( ).
"Here goes, for example, code for preparing the test data,
"e.g. filling a database table used for test methods.
...
ENDMETHOD.
METHOD some_test_method.
"Method call
DATA(result) = ref_cut->multiply_by_two( 5 ).
"Assertion
cl_abap_unit_assert=>...
ENDMETHOD.
METHOD another_test_method.
"Another method to be tested, it can also use the centrally created instance.
"Calling method
DATA(result) = ref_cut->multiply_by_three( 6 ).
"Assertion
cl_abap_unit_assert=>...
ENDMETHOD.
METHOD teardown.
"Here goes, for example, code to undo the test data preparation
"during the setup method (e.g. deleting the inserted database table entries).
...
ENDMETHOD.
ENDCLASS.
```
--------------------------------
TITLE: ABAP: Create or Reuse Reference Types with cl_abap_refdescr=>get
DESCRIPTION: This example shows how to use the `cl_abap_refdescr=>get` method to create or reuse reference types. It demonstrates obtaining a reference type description object from an elementary type description and from an object type description, then using it to create a dynamic data reference. The `get` method is recommended over `create`.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_209
LANGUAGE: ABAP
CODE:
```
DATA(tdo_ref_int) = cl_abap_elemdescr=>get_i( ).
DATA(tdo_ref_get_a) = cl_abap_refdescr=>get( tdo_ref_int ).
CREATE DATA dref_ref TYPE HANDLE tdo_ref_get_a.
```
LANGUAGE: ABAP
CODE:
```
DATA(tdo_cl_abap_typedescr) = cl_abap_typedescr=>describe_by_name( 'CL_ABAP_TYPEDESCR' ).
DATA(tdo_ref_get_b) = cl_abap_refdescr=>get( tdo_cl_abap_typedescr ).
CREATE DATA dref_ref TYPE HANDLE tdo_ref_get_b.
```
--------------------------------
TITLE: ABAP Executable Example Programs for UI Elements
DESCRIPTION: A list of ABAP demonstration programs available in the repository, serving as entry points and specific examples for various UI functionalities like selection screens, classic lists, and ALV. These programs illustrate the usage of different ABAP statements and concepts.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/20_Selection_Screens_Lists.md#_snippet_117
LANGUAGE: APIDOC
CODE:
```
Program Names and Descriptions:
ZDEMO_ABAP_SELSCR_LISTS_INTRO: Entry point for all selection screen and list examples.
ZDEMO_ABAP_SELSCR_PARAMETERS: Demonstrates PARAMETERS statements.
ZDEMO_ABAP_SELSCR_SELECT_OPT: Demonstrates SELECT-OPTIONS statements.
ZDEMO_ABAP_SELSCR_STANDALONE: Demonstrates the creation and calling of standalone selection screens.
ZDEMO_ABAP_SELSCR_STMTS_VAR: Demonstrates variants of SELECTION-SCREEN statements that do not create selection screens.
ZDEMO_ABAP_LISTS: Demonstrates various ABAP statements to create and handle classic lists.
ZDEMO_ABAP_EVENT_BLOCKS: Demonstrates event blocks.
ZDEMO_ABAP_ALV: Demonstrates the SAP List Viewer (ALV).
```
--------------------------------
TITLE: ABAP: Get Element Type Description by Data Reference with cl_abap_elemdescr
DESCRIPTION: This example illustrates the use of `describe_by_data_ref` to get a type description object from a data reference. It shows how to initialize a data reference and then use its type for dynamic data creation.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_183
LANGUAGE: ABAP
CODE:
```
DATA data_ref TYPE REF TO data.
data_ref = NEW i( 123 ).
DATA(tdo_elem_descr_by_data_ref) = cl_abap_elemdescr=>describe_by_data_ref( data_ref ).
DATA(cast_tdo_elem_desc_by_data_ref) = CAST cl_abap_datadescr( tdo_elem_descr_by_data_ref ).
CREATE DATA dref_elem TYPE HANDLE cast_tdo_elem_desc_by_data_ref.
```
--------------------------------
TITLE: ABAP Class Method Implementations for Dynamic Call Examples
DESCRIPTION: Provides the basic implementations for the `inst_meth1`, `inst_meth2`, `stat_meth1`, and `stat_meth2` methods. These methods are referenced as targets in the various dynamic method call examples throughout the document, demonstrating their simple functionality.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_100
LANGUAGE: ABAP
CODE:
```
METHOD inst_meth1.
...
ENDMETHOD.
METHOD inst_meth2.
result = to_upper( text ).
ENDMETHOD.
METHOD stat_meth1.
...
ENDMETHOD.
METHOD stat_meth2.
result = to_upper( text ).
ENDMETHOD.
ENDCLASS.
```
--------------------------------
TITLE: Demonstrate ABAP sy System Fields Usage
DESCRIPTION: This ABAP code example illustrates the use of various `sy` system fields, including `sy-subrc`, `sy-tabix`, and `sy-index`. It highlights which fields are suitable for ABAP for Cloud Development and which may generate syntax warnings due to their context. The example requires creating a class `zcl_demo_abap` and can be executed in ADT to display output in the console.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/02_Structures.md#_snippet_39
LANGUAGE: ABAP
CODE:
```
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_demo_abap IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
"In ABAP for Cloud Development, the following statement will show a syntax warning saying that
"sy should not be used. Here, it is used for demonstration purposes.
"In the example, RTTI is used to get all component names of the built-in data object sy. In the loop,
"ABAP statements are created (they represent simple assignments using the various sy components) and
"output to the console. You can copy all the output DATA(...) = ... statements from the console and
"paste them in the demo class's main method implementation. The purpose is to demonstrate that most of
"the sy components should not be used in ABAP for Cloud Development. Most of the statements will show
"a syntax warning in ABAP for Cloud Development. Check the ABAP Keyword Documentation (for Standard ABAP)
"and the F2 information for the purpose of the individual sy components.
LOOP AT CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_data( sy ) )->components INTO DATA(co).
DATA(sycomp) = to_lower( co-name ).
DATA(code) = |DATA(sy{ sycomp }) = sy-{ sycomp }.|.
out->write( code ).
ENDLOOP.
out->write( |\n| ).
out->write( |\n| ).
"Demonstrating prominent sy components that can be used in ABAP for Cloud Development
*&---------------------------------------------------------------------*
*& sy-subrc: Return code of ABAP statements
*&---------------------------------------------------------------------*
"Many ABAP statements set a sy-subrc value. Check the ABAP Keyword Documentation
"for individual statements. Usually, the value 0 indicates a successful execution.
DATA(some_string) = `ABAP`.
"FIND statements
"Found
FIND `P` IN some_string.
ASSERT sy-subrc = 0.
"Not found
FIND `p` IN some_string RESPECTING CASE.
ASSERT sy-subrc = 4.
DATA(some_itab) = VALUE string_table( ( `a` ) ( `b` ) ( `c` ) ( `d` ) ).
"READ TABLE statements
"Entry available
READ TABLE some_itab INTO DATA(wa1) INDEX 3.
ASSERT sy-subrc = 0.
"Entry not available
READ TABLE some_itab INTO DATA(wa2) INDEX 7.
ASSERT sy-subrc = 4.
"ABAP SQL statements
DELETE FROM zdemo_abap_tab1.
IF sy-subrc = 0.
out->write( `DELETE: All rows were deleted.` ).
ELSE.
out->write( `DELETE: No row was deleted because it was already empty.` ).
ENDIF.
INSERT zdemo_abap_tab1 FROM TABLE @( VALUE #( ( key_field = 1 ) ( key_field = 2 ) ) ).
IF sy-subrc = 0.
out->write( `INSERT: All rows of the internal table were inserted.` ).
ENDIF.
```
--------------------------------
TITLE: Insert Demo Data for Dynamic ABAP SQL Examples
DESCRIPTION: This snippet provides an example of inserting demo data into a custom database table. This data can then be used for subsequent dynamic SQL operations like UPDATE or DELETE statements.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_85
LANGUAGE: ABAP
CODE:
```
TYPES carr_tab TYPE TABLE OF zdemo_abap_carr WITH EMPTY KEY.
INSERT ('ZDEMO_ABAP_CARR') FROM TABLE @( VALUE carr_tab( ( carrid = 'WX' carrname = 'WX Airways' )
( carrid = 'XY' carrname = 'Air XY' )
( carrid = 'YZ' carrname = 'YZ Airlines' ) ) ).
```
--------------------------------
TITLE: ABAP Examples for Regular Expression Quantifiers and Alternatives
DESCRIPTION: Practical demonstrations of regular expression quantifiers, repetitions, and alternatives in ABAP using the `replace` function. Each example illustrates a specific regex pattern and its effect on a given string.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/28_Regular_Expressions.md#_snippet_11
LANGUAGE: ABAP
CODE:
```
DATA string_quan_rep_alt TYPE string.
"Zero or more repetitions
"#c #c #c # #c
string_quan_rep_alt = replace( val = `abc abbc abbbc a ac` pcre = `ab*` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"One or more repetitions
"#c #c #c a ac
string_quan_rep_alt = replace( val = `abc abbc abbbc a ac` pcre = `ab+` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"Between x and y repetitions
"abc #c #c a ac
string_quan_rep_alt = replace( val = `abc abbc abbbc a ac` pcre = `ab{2,3}` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"Exactly n repetitions
"abc abbc #c a ac
string_quan_rep_alt = replace( val = `abc abbc abbbc a ac` pcre = `ab{3}` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"Exactly n or more repetitions
"abc #c #c a ac
string_quan_rep_alt = replace( val = `abc abbc abbbc a ac` pcre = `ab{2,}` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"Optional matches
"#c #bc #bbc # #c
string_quan_rep_alt = replace( val = `abc abbc abbbc a ac` pcre = `ab?` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"Alternative matches
"#z#y#xdwevfu
string_quan_rep_alt = replace( val = `azbycxdwevfu` pcre = `a|b|c` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"Capturing non-greedily (zero or more repetitions)
"a#cd a#ccccd a#
string_quan_rep_alt = replace( val = `abcd abccccd ab` pcre = `bc*?` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"_defghxi
string_quan_rep_alt = replace( val = `abcxdefghxi` pcre = `\A.*?x` with = `_` ).
```
LANGUAGE: ABAP
CODE:
```
"Example to compare with greedy capturing
"_i
string_quan_rep_alt = replace( val = `abcxdefghxi` pcre = `\A.*x` with = `_` ).
```
LANGUAGE: ABAP
CODE:
```
"Capturing non-greedily (one or more repetitions)
"a#d a#cccd ab
string_quan_rep_alt = replace( val = `abcd abccccd ab` pcre = `bc+?` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"Example to compare with greedy capturing
"a#d a#d ab
string_quan_rep_alt = replace( val = `abcd abccccd ab` pcre = `bc+` with = `#` occ = 0 ).
```
LANGUAGE: ABAP
CODE:
```
"#Hallo#
string_quan_rep_alt = replace( val = `Hallo` pcre = `<.+?>` with = `#` occ = 0 ).
```
--------------------------------
TITLE: ABAP SELECT FROM Clause Examples with Various Data Sources
DESCRIPTION: Provides concrete ABAP examples demonstrating the `SELECT` statement's `FROM` clause usage with different data sources: a database table, a CDS view entity, a CDS table function, and an internal table. It also shows the declaration and initialization of an internal table for use as a data source.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/03_ABAP_SQL.md#_snippet_5
LANGUAGE: ABAP
CODE:
```
"Database table
SELECT FROM zdemo_abap_fli
FIELDS *
INTO TABLE @DATA(itab_db).
"CDS entities
"CDS view entity
SELECT *
FROM zdemo_abap_fli_ve
INTO TABLE @DATA(itab_ve).
"CDS table function
SELECT FROM zdemo_abap_table_function
FIELDS *
INTO TABLE @DATA(itab_tf).
"Internal table
TYPES: BEGIN OF s,
num TYPE i,
chars TYPE c LENGTH 3,
END OF s,
t_type TYPE TABLE OF s WITH EMPTY KEY.
DATA(itab) = VALUE t_type( ( num = 1 chars = 'aaa' )
( num = 2 chars = 'bbb' )
( num = 3 chars = 'ccc' ) ).
SELECT FROM @itab AS it
FIELDS *
INTO TABLE @DATA(itab_it).
```
--------------------------------
TITLE: ABAP CORRESPONDING Operator Syntax Patterns and Data Structure Definitions
DESCRIPTION: This ABAP code snippet illustrates common syntax patterns for the `CORRESPONDING` operator, including examples for `BASE`, `MAPPING`, `EXCEPT`, and `DISCARDING DUPLICATES`. It also defines two example ABAP structures, `s1` and `s2`, which are used as data objects for demonstrating the operator's functionality in subsequent examples.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/05_Constructor_Expressions.md#_snippet_17
LANGUAGE: ABAP
CODE:
```
*&---------------------------------------------------------------------*
*& Patterns
*&---------------------------------------------------------------------*
"The following examples demonstrate simple assignments
"with the CORRESPONDING operator using these syntax patterns.
"Note:
"- The examples show only a selection of possible additions.
"- There are various combinations of additions possible.
"- The effect of the statements is shown in lines commented out.
"... CORRESPONDING #( z ) ...
"... CORRESPONDING #( BASE ( x ) z ) ...
"... CORRESPONDING #( z MAPPING a = b ) ...
"... CORRESPONDING #( z EXCEPT b ) ...
"... CORRESPONDING #( it DISCARDING DUPLICATES ) ...
*&---------------------------------------------------------------------*
*& Structures
*&---------------------------------------------------------------------*
"Data objects to work with in the examples
"Two different structures; one component differs.
DATA: BEGIN OF s1,
a TYPE i,
b TYPE c LENGTH 3,
c TYPE c LENGTH 5,
END OF s1.
DATA: BEGIN OF s2,
a TYPE i,
```
--------------------------------
TITLE: ABAP Dynamic ASSIGN Statements Comprehensive Example
DESCRIPTION: This comprehensive ABAP code snippet demonstrates various forms of dynamic ASSIGN statements. It illustrates how to dynamically assign memory areas using string literals or data references, assign components of structures or internal tables, and assign attributes of classes or interfaces. The example also includes setup for data objects and field symbols, and provides important notes regarding best practices and warnings for ABAP for Cloud Development, particularly concerning the use of named data objects and fully dynamic specifications.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_41
LANGUAGE: ABAP
CODE:
```
"Creating and populating various types/data objects to work with
TYPES: BEGIN OF st_type,
col1 TYPE i,
col2 TYPE string,
col3 TYPE string,
END OF st_type.
DATA st TYPE st_type.
DATA it TYPE TABLE OF st_type WITH EMPTY KEY.
st = VALUE #( col1 = 1 col2 = `aaa` col3 = `Z` ).
APPEND st TO it.
DATA(dref) = NEW st_type( col1 = 2 col2 = `b` col3 = `Y` ).
DATA dobj TYPE string VALUE `hallo`.
"The following examples use a field symbol with generic type
FIELD-SYMBOLS TYPE data.
*&---------------------------------------------------------------------*
*& Specifying the memory area dynamically
*&---------------------------------------------------------------------*
"I.e. the memory area is not specified directly, but as content of a
"character-like data object in parentheses.
"Note:
"- When specified as unnamed data object, the compiler treats the
" specifications like static assignments. Do not use named data objects
" for ASSIGN statements in ABAP for Cloud Development. It is recommended
" that existing named data objects are put in a structure. Then, the syntax
" for assigning components dynamically can be used so as to avoid a syntax
" warning.
"- Most of the following examples use an unnamed data object.
"- The specification of the name is not case-sensitive.
ASSIGN ('IT') TO .
ASSIGN ('ST') TO .
"Field symbol declared inline
"Note: The typing is performed with the generic type data.
ASSIGN ('DOBJ') TO FIELD-SYMBOL().
"The statements set the sy-subrc value.
ASSIGN ('DOES_NOT_EXIST') TO .
IF sy-subrc <> 0.
...
ENDIF.
"The memory area can also be a dereferenced data reference
ASSIGN dref->* TO .
"Do not use named data objects in ABAP for Cloud Development because
"you cannot know what data object you get (e.g. a class attribute or a
"local variable). If you want to assign a data object from your local
"scope, it is recommended that you specify the data objects to
"be assigned as components of a structure. Then you can ensure that
"you assign the correct data object dynamically, using the dynamic
"component assignments as shown below.
DATA some_string TYPE string VALUE `hi`.
DATA(some_named_dobj) = 'SOME_STRING'.
"A warning is displayed for the following statement in ABAP for Cloud
"Development.
"ASSIGN (some_named_dobj) TO FIELD-SYMBOL().
*&---------------------------------------------------------------------*
*& Assigning components dynamically
*&---------------------------------------------------------------------*
"You can chain the names with the component selector (-), or, in
"case of reference variables, the object component selector (->).
ASSIGN st-('COL1') TO .
ASSIGN it[ 1 ]-('COL1') TO .
ASSIGN dref->('COL1') TO .
"The following example uses the dereferencing operator explicitly
"followed by the component selector.
ASSIGN dref->*-('COL1') TO .
"Using a named data object for the component specification
DATA columnname TYPE string VALUE `COL1`.
ASSIGN st-(columnname) TO .
"Fully dynamic specification
"If the compiler can fully determine the data object in ASSIGN
"statements in ABAP for Cloud Development, a warning is not issued.
ASSIGN ('ST-COL1') TO .
"Numeric expressions are possible. Its value is interpreted
"as the position of the component in the structure.
ASSIGN st-(3) TO .
"If the value is 0, the memory area of the entire structure is
"assigned to the field symbol.
ASSIGN st-(0) TO .
"The statements above replace the following, older statements.
ASSIGN COMPONENT 'COL1' OF STRUCTURE st TO .
ASSIGN COMPONENT 3 OF STRUCTURE st TO .
*&---------------------------------------------------------------------*
*& Assigning attributes of classes or interfaces dynamically
*&---------------------------------------------------------------------*
"The following syntax pattern shows the possible specifications.
"... cref->(attr_name) ... "object reference variable
"... iref->(attr_name) ... "interface reference variable
"... (clif_name)=>(attr_name) ... "class/interface name
"... (clif_name)=>attr ...
"... clif=>(attr_name) ...
"Creating an instance of a class
DATA(oref) = NEW zcl_demo_abap_objects( ).
"Assigning instance attributes using an object reference variable
"All visible attributes of objects can be assigned.
oref->string = `ABAP`. "Assigning a value to the attribute for demo purposes
ASSIGN oref->('STRING') TO .
"Assigning instance attributes using an interface reference variable
DATA iref TYPE REF TO zdemo_abap_objects_interface.
iref = oref.
ASSIGN iref->('STRING') TO .
iref->in_str = `hallo`.
ASSIGN iref->('IN_STR') TO .
"Assigning static attributes
"All visible static attributes in classes and interfaces can be assigned
```
--------------------------------
TITLE: ABAP Example: Dynamic Method Calls with Simple Methods (Class 1)
DESCRIPTION: A comprehensive ABAP example class (`zcl_demo_abap`) demonstrating dynamic method calls for both static and instance methods. It covers various scenarios including dynamic class and method names, parameter handling, and error handling for incorrect calls like missing parameters or type mismatches.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_94
LANGUAGE: ABAP
CODE:
```
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
METHODS inst_meth1.
METHODS inst_meth2 IMPORTING text TYPE string
RETURNING VALUE(result) TYPE string.
CLASS-METHODS stat_meth1.
CLASS-METHODS stat_meth2 IMPORTING text TYPE string
EXPORTING result TYPE string.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_demo_abap IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
"The following examples use both named and unnamed data objects randomly,
"i.e. ...=>(meth_name) or ...=>(`SOME_METH`), for example.
DATA(cl_name) = `ZCL_DEMO_ABAP`.
DATA(meth_name1) = `STAT_METH1`.
*&---------------------------------------------------------------------*
*& Calling static methods dynamically
*&---------------------------------------------------------------------*
"-------- Method without mandatory parameters defined --------
"The syntax is possible for methods of the same class.
CALL METHOD (meth_name1).
"The previous example method call works like me->(meth).
CALL METHOD me->(meth_name1).
"-------- Class specified statically, method specified dynamically --------
CALL METHOD zcl_demo_abap=>(meth_name1).
"-------- Class specified dynamically, method specified statically --------
CALL METHOD (`ZCL_DEMO_ABAP`)=>stat_meth1.
"-------- Class and method specified dynamically --------
CALL METHOD (`ZCL_DEMO_ABAP`)=>(`STAT_METH1`).
"-------- Specifying non-optional parameters --------
CALL METHOD (`ZCL_DEMO_ABAP`)=>stat_meth2 EXPORTING text = `hallo`.
"Specifying the output parameter is optional
DATA res TYPE string.
CALL METHOD (`ZCL_DEMO_ABAP`)=>stat_meth2 EXPORTING text = `hallo` IMPORTING result = res.
ASSERT res = `HALLO`.
"-------- Some examples for handling errors when calling methods wrongly --------
"Instance method called using =>
TRY.
CALL METHOD zcl_demo_abap=>(`INST_METH1`).
CATCH cx_sy_dyn_call_illegal_method.
ENDTRY.
"The example method declares a non-optional parameter.
TRY.
CALL METHOD (`ZCL_DEMO_ABAP`)=>stat_meth2.
CATCH cx_sy_dyn_call_param_missing.
ENDTRY.
"Specifying a wrong parameter name
TRY.
CALL METHOD (`ZCL_DEMO_ABAP`)=>stat_meth2 EXPORTING hallo = `hallo`.
CATCH cx_sy_dyn_call_param_missing.
ENDTRY.
"Assigning wrong, incompatible type
TRY.
CALL METHOD (`ZCL_DEMO_ABAP`)=>stat_meth2 EXPORTING text = VALUE string_table( ( `hi` ) ).
CATCH cx_sy_dyn_call_illegal_type.
ENDTRY.
```
--------------------------------
TITLE: Create Dynamic Deep ABAP Structures
DESCRIPTION: This ABAP example illustrates the dynamic creation of a deep structured type, which includes nested structures and table types. It demonstrates how to define components that reference other global types (like `ZDEMO_ABAP_FLI`, `STRING_TABLE`) and even locally defined types (`flat_struc_type`) within the dynamic structure definition using `cl_abap_structdescr=>get` and `cl_abap_tabledescr=>get`.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_186
LANGUAGE: abap
CODE:
```
*&---------------------------------------------------------------------*
*& Creating a structured type and data object dynamically
*& Deep structure
*&---------------------------------------------------------------------*
"A structured type and data object such as the following shall be created
"dynamically using a type description object.
TYPES: BEGIN OF deep_struc_type,
num TYPE i, "Built-in ABAP types
str TYPE string,
flight_struc TYPE zdemo_abap_fli, "Structure based on the line type of a database table
string_tab TYPE string_table, "Global table type
local_tab TYPE TABLE OF flat_struc_type WITH EMPTY KEY, "Table type based on local structured type
END OF deep_struc_type.
DATA struc_2 TYPE deep_struc_type.
"Creating a reference type dynamically using a type description object
DATA(tdo_struc_2) = cl_abap_structdescr=>get(
VALUE #(
( name = 'NUM' type = cl_abap_elemdescr=>get_i( ) )
( name = 'STR' type = cl_abap_elemdescr=>get_string( ) )
( name = 'FLIGHT_STRUC' type = CAST cl_abap_datadescr( cl_abap_typedescr=>describe_by_name( 'ZDEMO_ABAP_FLI' ) ) )
( name = 'STRING_TAB' type = CAST cl_abap_datadescr( cl_abap_typedescr=>describe_by_name( 'STRING_TABLE' ) ) )
( name = 'LOCAL_TAB' type = CAST cl_abap_datadescr( cl_abap_tabledescr=>get(
p_line_type = CAST cl_abap_structdescr( cl_abap_tabledescr=>describe_by_name( 'FLAT_STRUC_TYPE' ) )
p_table_kind = cl_abap_tabledescr=>tablekind_std
p_unique = cl_abap_typedescr=>false
p_key_kind = cl_abap_tabledescr=>keydefkind_empty ) ) ) ) ).
"Creating a data reference variable dynamically using a type description object
CREATE DATA dref_struc TYPE HANDLE tdo_struc_2.
"Getting type information and checking type compatibility
DATA(tdo_for_dref_struc_2) = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_data( dref_struc->* ) ).
DATA(applies_to_struc_2) = tdo_for_dref_struc_2->applies_to_data( struc_2 ).
ASSERT applies_to_struc_2 = abap_true.
```
--------------------------------
TITLE: ABAP: Get Type Description Object for REF TO DATA with cl_abap_refdescr=>get_ref_to_data
DESCRIPTION: This example demonstrates the `cl_abap_refdescr=>get_ref_to_data` method, which directly returns the type description object for the generic `REF TO DATA` type.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_215
LANGUAGE: ABAP
CODE:
```
DATA(tdo_ref_get_ref_to_data) = cl_abap_refdescr=>get_ref_to_data( ).
```
--------------------------------
TITLE: ABAP: Constructing Strings with REDUCE and Iteration Control
DESCRIPTION: Demonstrates how to use the REDUCE expression for constructing text strings. The first example uses the THEN addition to decrement an iteration variable and a LET expression for a helper variable. The second example uses the UNTIL addition to enlarge a string until it reaches a specific size.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/05_Constructor_Expressions.md#_snippet_102
LANGUAGE: ABAP
CODE:
```
DATA(count) = REDUCE string( LET start = 10 IN
INIT text = |Counting downwards starting with { start }:|
FOR n = start THEN n - 1 WHILE n > 0
NEXT text &&= | { n }| ).
```
LANGUAGE: ABAP
CODE:
```
DATA(abap_str) = REDUCE string( INIT text = ``
FOR t = `ab` THEN t && `ap` UNTIL strlen( t ) > 15
NEXT text &&= |{ t } | ).
```
--------------------------------
TITLE: ABAP Class Definition and Demo Data Initialization
DESCRIPTION: This snippet defines the basic structure of the `zcl_demo_abap` class, implementing the `if_oo_adt_classrun` interface to enable console execution. It includes the initial call to `zcl_demo_abap_aux=>fill_dbtabs()` to populate necessary demo database tables, setting up the environment for the subsequent security examples.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_108
LANGUAGE: ABAP
CODE:
```
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_demo_abap IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
"Filling demo database tables of the ABAP cheat sheet repository
zcl_demo_abap_aux=>fill_dbtabs( ).
```
--------------------------------
TITLE: Define ABAP Class for /ui2/cl_json Examples
DESCRIPTION: This snippet provides a template for an ABAP demo class (`zcl_demo_abap`) that implements `if_oo_adt_classrun`. This class can be used as a container to execute and test the JSON handling examples, particularly those involving the `/ui2/cl_json` class, directly within ADT.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/21_XML_JSON.md#_snippet_33
LANGUAGE: ABAP
CODE:
```
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
```
--------------------------------
TITLE: Example Output of Parsed and Rendered XML
DESCRIPTION: This snippet provides examples of the structured output generated after parsing and iterating through the XML nodes (stored in 'xml_nodes'), and the final rendered XML string after modifications (e.g., text conversion to uppercase, stored in 'conv_string').
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/21_XML_JSON.md#_snippet_6
LANGUAGE: Text
CODE:
```
*--- xml_nodes ---
*Element: "node"
*Attribute: "attr_a = 123"
*Element: "subnode1"
*Element: "hallo"
*Text: "hi"
*Element: "subnode2"
*Element: "letter"
*Text: "a"
*Element: "date"
*Attribute: "format = mm-dd-yyyy"
*Text: "01-01-2025"
*Element: "subnode3"
*Element: "text"
*Attribute: "attr_b = 1"
*Attribute: "attr_c = a"
*Text: "ABC"
*Element: "text"
*Attribute: "attr_b = 2"
*Attribute: "attr_c = b"
*Text: "DEF"
*Element: "text"
*Attribute: "attr_b = 3"
*Attribute: "attr_c = c"
*Text: "GHI"
*Element: "text"
*Attribute: "attr_b = 4"
*Attribute: "attr_c = d"
*Text: "JKL"
*--- conv_string ---
*HIA
*01-01-2025ABC
*DEFGHIJKL
```
--------------------------------
TITLE: Alternative Syntax for ABAP EXPORT/IMPORT Statements
DESCRIPTION: This example illustrates the alternative syntax for `EXPORT` and `IMPORT` statements, using `FROM ...` instead of `= ...` for `EXPORT` and `TO ...` instead of `= ...` for `IMPORT`. This provides flexibility in how parameters are specified.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/21_XML_JSON.md#_snippet_50
LANGUAGE: ABAP
CODE:
```
"--------- Alternative syntax for specifying the parameters ---------
"EXPORT: Using ... FROM ... instead of ... = ...
"IMPORT: Using ... TO ... instead of ... = ...
EXPORT flights FROM itab1 TO DATA BUFFER buffer.
IMPORT flights TO itab2 FROM DATA BUFFER buffer.
EXPORT int1 = 100 int2 = 200 TO DATA BUFFER buffer.
IMPORT int1 TO num1 int2 TO num2 FROM DATA BUFFER buffer.
```
--------------------------------
TITLE: ABAP Event Block: INITIALIZATION for Program Setup
DESCRIPTION: The `INITIALIZATION` event block is executed before the selection screen is displayed. This snippet logs the event using `sel_screen_evt` and initializes various text variables (`intro`, `note`, `text`) that might be used later in the report, preparing the program's initial state.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/20_Selection_Screens_Lists.md#_snippet_87
LANGUAGE: ABAP
CODE:
```
INITIALIZATION.
demo=>sel_screen_evt( `INITIALIZATION` ).
intro = 'Exploring list events'.
note = 'The Back/Exit/Cancel buttons raise the ON EXIT-COMMAND event.'.
text = 'Hello'.
```
--------------------------------
TITLE: Populate ABAP Structures with Initial Values
DESCRIPTION: Initializes structures `s1` and `s2` with example data using the `VALUE` operator, preparing them for `CORRESPONDING` operations.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/05_Constructor_Expressions.md#_snippet_19
LANGUAGE: ABAP
CODE:
```
s1 = VALUE #( a = 1 b = 'aaa' c = 'bbbbb' ).
s2 = VALUE #( a = 2 b = 'ccc' d = `dddd` ).
```
--------------------------------
TITLE: ABAP Class Definition and Data Initialization for Transformation Examples
DESCRIPTION: Defines the `zcl_demo_abap` class implementing `if_oo_adt_classrun` for execution in ADT. It initializes a sample internal table `tab` with structured data, which serves as the source for subsequent `CALL TRANSFORMATION` demonstrations.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/21_XML_JSON.md#_snippet_16
LANGUAGE: ABAP
CODE:
```
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_demo_abap IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
TYPES: BEGIN OF line,
char TYPE c LENGTH 3,
int TYPE i,
END OF line,
t_type TYPE TABLE OF line WITH EMPTY KEY.
DATA(tab) = VALUE t_type( ( char = 'aaa' int = 1 )
( char = 'bbb' int = 2 )
( char = 'ccc' int = 3 ) ).
out->write( `ABAP <-> XML using XSLT (Using the Predefined Identity Transformation ID)` ).
```
--------------------------------
TITLE: ABAP Executable Example for Internal Table LOOP AT Statements
DESCRIPTION: This ABAP class `zcl_demo_abap` provides a comprehensive executable example for working with internal tables, specifically demonstrating various `LOOP AT` statements with different `WHERE` clause conditions. It includes examples for numeric and character-like comparison operators, complex logical expressions (AND, OR, NOT, EQUIV), pattern matching, and range-based filtering using `BETWEEN` and `IN` clauses. The example is designed for interactive debugging to observe the effects of each statement on internal table data.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/31_WHERE_Conditions.md#_snippet_42
LANGUAGE: ABAP
CODE:
```
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_demo_abap IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
*&---------------------------------------------------------------------*
*& Demo data types/objects
*&---------------------------------------------------------------------*
TYPES: BEGIN OF demo_struc,
id TYPE i,
text TYPE string,
num TYPE i,
ref TYPE REF TO string,
oref TYPE REF TO object,
END OF demo_struc,
tab_type TYPE TABLE OF demo_struc WITH EMPTY KEY.
DATA(itab) = VALUE tab_type(
( id = 1 text = `abc` num = 0 ref = REF #( `hello` ) oref = NEW cl_system_uuid( ) )
( id = 2 text = `abc` num = 20 )
( id = 3 text = `def` num = 0 ref = REF #( `world` ) oref = NEW cl_system_uuid( ) )
( id = 4 text = `efg` num = 40 )
( id = 5 text = `ghi` num = 50 ref = REF #( `ABAP` ) ) ).
DATA str TYPE string.
*&---------------------------------------------------------------------*
*& LOOP AT statements
*&---------------------------------------------------------------------*
"Comparison operators
LOOP AT itab INTO DATA(wa) WHERE num = 0.
str &&= wa-id.
ENDLOOP.
CLEAR str.
LOOP AT itab INTO wa WHERE num > 20.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"Combination of one or more logical expressions with the Boolean operators
"NOT, AND, OR, EQUIV where parentheses are possible
LOOP AT itab INTO wa WHERE id >= 3 and num > 5.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"Two logical expressions can be combined with EQUIV, which creates a new
"logical expression. This expression is true if both expressions are true
"or both expressions are false. If an expression returns a different
"result than the other, the combined expression is false.
"Example pattern: ... a = b EQUIV c = d ...
"The combined expression is true if a/b and c/d are either both equal
"or not.
"The following loop yields 23 for str.
"For the entry with id = 2, both expressions are false.
"For the entry with id = 3, both expressions are true.
LOOP AT itab INTO wa WHERE id > 2 EQUIV num < 10.
str &&= wa-id.
ENDLOOP.
CLEAR str.
LOOP AT itab INTO wa WHERE num >= 40 OR num = 0.
str &&= wa-id.
ENDLOOP.
CLEAR str.
LOOP AT itab INTO wa WHERE NOT num = 0.
str &&= wa-id.
ENDLOOP.
CLEAR str.
LOOP AT itab INTO wa WHERE ( id < 5 AND num > 10 ) AND text = `abc`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"Comparison operators for character-like data types
"contains only
LOOP AT itab INTO wa WHERE text CO `abc`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"contains not only
LOOP AT itab INTO wa WHERE text CN `abc`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"contains string
LOOP AT itab INTO wa WHERE text CS `ef`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"contains no string
LOOP AT itab INTO wa WHERE text NS `ef`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"contains any
LOOP AT itab INTO wa WHERE text CA `xyzi`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"contains not any
LOOP AT itab INTO wa WHERE text NA `a`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"conforms to pattern
LOOP AT itab INTO wa WHERE text CP `*c`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"does not conform to pattern
LOOP AT itab INTO wa WHERE text NA `*c`.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"[NOT] BETWEEN ... AND ...
LOOP AT itab INTO wa WHERE num BETWEEN 5 AND 45.
str &&= wa-id.
ENDLOOP.
CLEAR str.
LOOP AT itab INTO wa WHERE num NOT BETWEEN 5 AND 45.
str &&= wa-id.
ENDLOOP.
CLEAR str.
"[NOT] IN ranges_table
DATA rangestab TYPE RANGE OF i.
rangestab = VALUE #( ( sign = `I` option = `BT` low = 5 high = 45 ) ).
```
--------------------------------
TITLE: Define ABAP Structures for CORRESPONDING Examples
DESCRIPTION: Defines two ABAP structures, `s1` and `s2`, with partially identical and non-identical components, used as a basis for demonstrating the `CORRESPONDING` statement.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/05_Constructor_Expressions.md#_snippet_18
LANGUAGE: ABAP
CODE:
```
DATA: BEGIN OF s1,
a TYPE i,
b TYPE c LENGTH 3,
c TYPE string,
END OF s1.
DATA: BEGIN OF s2,
a TYPE i,
b TYPE c LENGTH 3,
d TYPE string,
END OF s2.
```
--------------------------------
TITLE: ABAP: Get Element Type Description by Data with cl_abap_elemdescr
DESCRIPTION: This example shows how to use the `describe_by_data` method of `cl_abap_elemdescr` to get a type description object for an existing data variable. It also illustrates how to cast the result to `cl_abap_datadescr` for use in dynamic data creation.
SOURCE: https://github.com/sap-samples/abap-cheat-sheets/blob/main/06_Dynamic_Programming.md#_snippet_181
LANGUAGE: ABAP
CODE:
```
DATA a_number TYPE i.
DATA(tdo_elem_descr_by_data) = cl_abap_elemdescr=>describe_by_data( a_number ).
"Note: To use it with the CREATE DATA ... TYPE HANDLE ... statement, a cast is
"required.
DATA(cast_tdo_elem_descr_by_data) = CAST cl_abap_datadescr( tdo_elem_descr_by_data ).
CREATE DATA dref_elem TYPE HANDLE cast_tdo_elem_descr_by_data.
```