Application Development and Automation Blog Posts
Learn and share on deeper, cross technology development topics such as integration and connectivity, automation, cloud extensibility, developing at scale, and security.
cancel
Showing results for 
Search instead for 
Did you mean: 
Bikash_11
Explorer
636

Virtual Element in RAP (Restful ABAP Programming Model):

A virtual element in SAP RAP is a field that exists in the the RAP behavior layer but does not have a direct mapping to a database field. It is calculated dynamically at runtime and is used to enhance the data provided by an entity with additional information, such as derived values or computed fields, without altering the underlying database structure.

Key Features of Virtual Elements :

  • Non-Persistent: Virtual elements are not stored in the database.   
  • Runtime Calculation: Their values are computed dynamically in the behavior implementation or SADL (Service Adaptation Definition Language) exits.   
  • UI and Reporting Enhancements: Used to display dynamic information without affecting the core data model.

Use Cases: 

  • Display derived or computed fields. 
  • Provide additional data like URLs, status messages, or formatted output. 
  • Enhance the user interface with runtime information.

How Virtual Elements Work :

  • Define Virtual Element in CDS View: Add the virtual field in the CDS view with the annotation @ObjectModel.virtualElement. 
  • Implement Calculation Logic: Use the behavior implementation or an exit handler to calculate the value of the virtual element at runtime.

Scenario :

I have a scenario where a video management application needs to display a thumbnail URL dynamically generated from a video URL stored in the database.

Step 1: Define the Database Table :

The table stores video details, including the video URL.

Bikash_11_0-1737100732469.png

Step 2: Create an interface View.

Bikash_11_0-1737096719998.png

Step 3: Create a consumption View with a Virtual Element :

Define a virtual field Thumbnail that generates the thumbnail URL dynamically. 

This CDS view defines a projection view on the database entity ZR_BRT_T_VIDEO to expose fields and add a virtual element called Thumbnail. The virtual element dynamically provides an image URL derived from the Url field. 

Syntax : 

Bikash_11_2-1736574464426.png

Bikash_11_1-1737096773927.png

Annotations for the Thumbnail Field : 

   @ObjectModel.virtualElementCalculatedBy: 'ABAP:ZCL_BRT_VIRTUAL_ELEMENT' 

  •  Indicates that the value for this field will be dynamically calculated by the ABAP class ZCL_BRT_VIRTUAL_ELEMENT. This class implements the logic to compute the thumbnail URL at runtime.  

   @EndUserText.label: 'Thumbnail 

  •  Provides a descriptive label for the field.

    @Semantics.imageUrl: true 

  •   Indicates that the field represents an image URL, enabling frontend applications like SAP Fiori to   treat it as such.   

    virtual Thumbnail : abap.char( 256 ) :

  •  In this case, virtual Thumbnail is a field designed to hold the dynamically generated thumbnail URL  of a video which defines the data type of the virtual element as a character string with a maximum length of 256 characters.

Behavior :

  • The Thumbnail field is not persisted in the database. 
  • It is computed dynamically by the logic implemented in the ABAP class ZCL_BRT_VIRTUAL_ELEMENT. 

Step 4 : Define the Behavior definition for the CDS View :

It defines a managed implementation for handling the operations of a business object (BO) ZBP_R_BRT_T_VIDEO that is based on the persistent database table zbrt_t_video.

 

managed implementation in class ZBP_R_BRT_T_VIDEO unique;
strict ( 2 );

define behavior for ZR_BRT_T_VIDEO alias ZrBrtTVideo
persistent table zbrt_t_video
lock master
authorization master ( global )
{
  field ( readonly )
  VideoUuid,
  LocalCreatedBy,
  LocalCreatedAt,
  LocalLastChangedBy,
  LocalLastChangedAt,
  LastChangedAt;

  field ( numbering : managed )
  VideoUuid;

  create;
  update;
  delete;

  mapping for zbrt_t_video
    {
      VideoUuid          = video_uuid;
      Title              = title;
      Url                = url;
      Description        = description;
      LocalCreatedBy     = local_created_by;
      LocalCreatedAt     = local_created_at;
      LocalLastChangedBy = local_last_changed_by;
      LocalLastChangedAt = local_last_changed_at;
      LastChangedAt      = last_changed_at;
    }
}

 

Step 5: Implement the Logic to Calculate the Virtual Element :

The virtual element’s value is computed at runtime in the behavior implementation class. 

This ABAP class implementation showcases the usage of virtual elements in SAP RAP (RESTful Application Programming) to calculate additional, non-persistent fields at runtime. It is based on the SADL (Service Adaptation Definition Language) exit interfaces.

 

CLASS zcl_brt_virtual_element DEFINITION
  PUBLIC
  FINAL
  CREATE PUBLIC .

  PUBLIC SECTION.
    INTERFACES if_sadl_exit .
    INTERFACES if_sadl_exit_calc_element_read .
  PROTECTED SECTION.
  PRIVATE SECTION.
ENDCLASS.

CLASS zcl_brt_virtual_element IMPLEMENTATION.

  METHOD if_sadl_exit_calc_element_read~calculate.

    TYPES : BEGIN OF ls_str,
              thumbnail TYPE c LENGTH 256,
              url       TYPE c LENGTH 256,
            END OF ls_str.

    DATA : lt_tab       TYPE TABLE OF ls_str,
           lt_video_id  TYPE TABLE OF string,
           lt_video_id1 TYPE TABLE OF string.

    lt_tab = CORRESPONDING #( it_original_data ).

    LOOP AT lt_tab ASSIGNING FIELD-SYMBOL(<fs_tab>).
      SPLIT <fs_tab>-url AT '/'  INTO TABLE lt_video_id.
      DATA(lv_id) = VALUE #( lt_video_id[ 4 ] OPTIONAL ).

      IF  lv_id CS 'watch?v='.
        SPLIT lv_id AT '='  INTO TABLE lt_video_id1.
        lv_id = VALUE #( lt_video_id1[ 2 ] OPTIONAL ).
      ELSEIF lv_id CS '?si='.
        SPLIT lv_id AT '?'  INTO TABLE lt_video_id1.
        lv_id = VALUE #( lt_video_id1[ 1 ] OPTIONAL ).
      ENDIF.

      <fs_tab>-thumbnail = |https://img.youtube.com/vi/{ lv_id }/hqdefault.jpg|.

    ENDLOOP.

    ct_calculated_data = CORRESPONDING #(  lt_tab ).

  ENDMETHOD.

  METHOD if_sadl_exit_calc_element_read~get_calculation_info.
  ENDMETHOD.
ENDCLASS.

 

INTERFACES if_sadl_exit_calc_element_read :

  This interface is specifically used to implement runtime calculations for virtual elements.

if_sadl_exit_calc_element_read~calculate : 

This method is responsible for calculating the values of virtual elements.

 

TYPES : BEGIN OF ls_str,
           thumbnail TYPE c LENGTH 256,
           url       TYPE c LENGTH 256,
        END OF ls_str.

 

Defines a structure ls_str with two fields : 

  • thumbnail: Holds the generated thumbnail URL. 
  • url: Holds the original video URL.

 

DATA : lt_tab       TYPE TABLE OF ls_str,
       lt_video_id  TYPE TABLE OF string,
       lt_video_id1 TYPE TABLE OF string.

 

  • lt_tab: Temporary table holding the input data (it_original_data) with fields thumbnail and url.
  • lt_video_id / lt_video_id1: Temporary tables used for splitting and processing URL components.

 

lt_tab = CORRESPONDING #( it_original_data ).

 

The CORRESPONDING operator maps the fields of the it_original_data (provided by RAP) into lt_tab.

 

LOOP AT lt_tab ASSIGNING FIELD-SYMBOL(<fs_tab>).

 

  • Iterates over the lt_tab table.
  • Processes the url field to extract the video ID and generate a YouTube thumbnail URL.

 

SPLIT <fs_tab>-url AT '/'  INTO TABLE lt_video_id.
DATA(lv_id) = VALUE #( lt_video_id[ 4 ] OPTIONAL ).

 

  • Splits the url at / and stores the components in lt_video_id. 
  • Extracts the 4th component as the initial video ID (lv_id).

 

IF  lv_id CS 'watch?v='.
    SPLIT lv_id AT '='  INTO TABLE lt_video_id1.
    lv_id = VALUE #( lt_video_id1[ 2 ] OPTIONAL ).
ELSEIF lv_id CS '?si='.
    SPLIT lv_id AT '?'  INTO TABLE lt_video_id1.
    lv_id = VALUE #( lt_video_id1[ 1 ] OPTIONAL ).
ENDIF.

 

Handles two URL variants : 

  • URLs containing watch?v= extract the part after = as the video ID. 
  • URLs containing ?si= extract the part before ?.

 

<fs_tab>-thumbnail = |https://img.youtube.com/vi/{ lv_id }/hqdefault.jpg|.

 

 Constructs a YouTube thumbnail URL using the extracted lv_id.

 

ct_calculated_data = CORRESPONDING #(  lt_tab ).

 

  • The modified data in lt_tab (including the newly added thumbnail field) is returned as ct_calculated_data.
  • ct_calculated_data is used to update the virtual element values dynamically.

Update Metadata Extension File : 

After providing the implementation for virtual element Since we are using Metadata Extension file to display Columns on Fiori Application. We need to add a new Virtual Element column Thumbnail.

 

.lineItem: [ {
    position: 5 ,
    importance: #MEDIUM, 
    label: 'Thumbnail',
    cssDefault.width: '5em'
  } ]
@UI.identification: [ {
    position: 5 , 
    label: 'Thumbnail'
  } ]
  Thumbnail;

 

Then we have to create service definition and service binding. 

Then preview it. Then in the ui we can see it.

Bikash_11_0-1737100285318.png

If we preview the database table, we can see there is no field called Thumbnail.

Bikash_11_1-1737100367322.png

Conclusion :

The primary functionality of this class is to calculate a virtual field thumbnail at runtime based on the url provided in the input data. This allows:

  • Dynamically generating YouTube thumbnail URLs from video URLs.
  • Adding these values as virtual elements without storing them in the database.

Thank you--

1 Comment
Ismail_05
Explorer
0 Kudos

very usefull.

 

Labels in this area