Understanding Virtual Elements in CDS Views for Dynamic Data Processing

Virtual Elements in CDS Views

Understanding Virtual Elements

Virtual elements in CDS views are additional fields that do not exist in the database but are calculated dynamically at runtime. They are used for displaying data in the UI through calculations rather than retrieval from the database.

To implement virtual elements, the interface IF_SADL_EXIT_CALC_ELEMENT_READ must be integrated into an implementation class. This interface contains two key methods:

  • GET_CALCULATION_INFO
  • CALCULATE

Additionally, the following annotation should be included in the CDS view:

@ObjectModel.virtualElementCalculatedBy: 'ABAP:'

Since virtual elements are computed at runtime, they do not appear in the CDS itself but are visible when the application is executed.

Requirement: Adding an Item Count Column

To enhance the user experience, an "Item Count" column should be included to represent the number of items associated with a purchase order.

Steps to Add a Virtual Element in Projection View

  1. Define the Item Count element in the projection view as a virtual element.
  2. Implement an ABAP class to calculate its value dynamically.

Sample Code for Projection View Definition

@ObjectModel.virtualElementCalculatedBy: 'ABAP:ZCL_ITEM_COUNT_VE'

@ObjectModel.virtualElement: true

cast ('' as abap.char(4)) as ItemCount


Alternatively, another syntax may be used:

@ObjectModel.virtualElement: true virtual ItemCount : abap.char(4)


Implementation Class for Virtual Element

The CALCULATE method in the implementation class processes the item count dynamically:

CLASS zcl_item_count_ve DEFINITION

  PUBLIC FINAL CREATE PUBLIC .

  PUBLIC SECTION.

    INTERFACES if_sadl_exit_calc_element_read .

ENDCLASS .


CLASS zcl_item_count_ve IMPLEMENTATION.

  METHOD if_sadl_exit_calc_element_read~calculate.

    DATA: it_po_details TYPE TABLE OF zc_po_head,

          it_count TYPE TABLE OF ztb_po_items.


    CHECK NOT it_original_data IS INITIAL.

    MOVE-CORRESPONDING it_original_data TO it_po_details.


    SELECT * FROM ztb_po_items 

      FOR ALL ENTRIES IN @it_po_details 

      WHERE po_num EQ @it_po_details-PoNum 

      INTO TABLE @DATA(it_po_items).


    IF sy-subrc EQ 0.

      LOOP AT it_po_details ASSIGNING FIELD-SYMBOL(<lfs_po>).

        it_count[] = it_po_items[].

        DELETE it_count WHERE po_num NE <lfs_po>-PoNum.

        DATA(lv_count) = LINES(it_count).

        <lfs_po>-ItemCount = lv_count.

        CLEAR lv_count.

      ENDLOOP.

      MOVE-CORRESPONDING it_po_details TO ct_calculated_data.

    ENDIF.

  ENDMETHOD.

ENDCLASS.


Adding the Element in Metadata Extension

To make the virtual element available for UI display, add the following metadata annotation:

@UI.lineItem: [{ position: 100, label: 'No of Items' }]

@UI.identification: [{ position: 100, label: 'No of Items' }]

ItemCount;

Preview the application to verify the data of the newly added element