Behavior AL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

ABAP Entity Manipulation Language (or EML for short) is a subset of ABAP that allows you to access the

data of RAP business objects in an ABAP program. The following points cover RAP-related terms such
as RAP business objects and others for setting the context:

 RAP business objects (RAP BO)


o A RAP BO is based on a special, tree-like hierarchical structure of CDS entities of a data
model
o Such a structure of entities consists of parent entities and child entities that are themselves
defined using CDS compositions and to-parent associations.
o The top parent entity of a CDS composition tree is the root entity that represents the
business object. With a large composition tree, RAP BOs can be fairly complex. Or they can
be very simple by just consisting of one root entity alone.
o Note: There is a special syntax for the CDS root entity of a RAP BO: define root view entity
 RAP behavior definition (BDEF)
o RAP BOs are described by the definitions specified in a special DDIC artifact: RAP behavior
definition (BDEF)
o A BDEF defines the RAP business object behavior (i. e. the transactional behavior of a RAP
BO)
o Transactional behavior means a BDEF defines behavior characteristics and RAP BO
operations i. e. RAP BO standard operations (CRUD operations), non-standard
operations like specific RAP actions and functions, and more.
o There are many other things that can be included impacting the RAP BO behavior like RAP
feature control, for example, defining which data is mandatory and which is read-only,
or determinations and validations.
o BDEFs use Behavior Definition Language (BDL) for the definitions. Find more information on
the topic and various options to define the transactional behavior in section BDL for
Behavior Definitions in the ABAP Keyword Documentation.
 Transactional buffer and implementation types
o A BDEF defines the behavior of a RAP BO and, thus, how to handle its data. This data is
available in the RAP transactional buffer.
o It is a storage for a RAP BO's data that is used and worked on during an SAP LUW.
o This data includes RAP BO instances (i. e. concrete data sets of an entity). This is where EML
enters the picture: EML is used, among others, to access this data in the transactional buffer.
o Currently, there are two kinds of RAP BOs: managed and unmanaged RAP BOs.
o Managed and unmanaged are implementation types that are also specified in the BDEF.
o The implementation type determines the RAP BO provider, i. e. how the transactional buffer
is provided and how the behavior of a RAP BO is implemented.
 Managed RAP BOs:
o The managed RAP BO provider fully or partly provides the transactional buffer and RAP BO
behavior (for standard operations only). In this case, the developers need not cater for the
transactional buffer and implement the standard operations. This implementation is mostly
relevant for greenfield scenarios when starting from scratch.
o Example: Regarding CRUD operations in managed RAP BOs, developers need not cater for
an implementation at all. The standard operations work out of the box. For example, in case
of an update operation, RAP BO instance data that is to be updated is automatically read
into the transactional buffer, and then updated accordingly there. Finally, when triggering
the saving, the updated instance in the transactional buffer is automatically saved to the
database without any custom development needed.
o The transactional buffer is provided, too. You do not need to create the buffer yourself.
o Note: Usually, the behavior of a RAP BO requires some additional implementations also in
the context of managed RAP BOs. For example, non-standard operations or feature controls
must be self-implemented in ABAP behavior pools (see the details further down).
 Unmanaged RAP BOs:
o Everything must be provided by the unmanaged RAP BO provider, i. e. the transactional
buffer and all RAP BO operations must be provided or self-implemented by developers in
an ABAP behavior implementation
o Unmanaged RAP BOs are, for example, relevant for brownfield scenarios, i. e. in scenarios in
which transactional buffers and application logic is already available and should be
embedded in the RAP world. Note that it is possible to have a managed RAP BO with
unamanged parts, e.g. unamanged save or additional save. Find more information here.
 ABAP behavior implementation in an ABAP behavior pool (ABP)
o An ABAP behavior pool is a special class pool for an ABAP behavior implementation that
implements the unmanaged RAP BO provider based on definitions in a BDEF. The class
pool's name is specified in the BDEF.
o The global class of a behavior pool does not implement the behavior itself. It is (initially)
empty apart from the declaration and implementation part skeletons. The behavior
implementation is coded in local RAP handler classes and a RAP saver class in the CCIMP
include of the behavior pool. These classes are called by the RAP runtime engine when the
RAP BO is accessed. This is covered in more detail further down.
o Usually, saver classes are not needed in managed RAP BOs (except for special variants of
managed RAP BOs which are not covered here). Local handler classes are, as mentioned
above, usually needed in managed RAP BOs if implementations are required that go
beyond standard operations.
o Note: In more complex scenarios, with RAP BOs that consist of many entities, you can define
behavior pools for individual entities by adding the syntax to the define behavior
for notation. There is not a saver class for each entity but only one saver class for the BO as
a whole. Any number of behavior pools can be assigned to a BDEF allowing applications a
structuring into multiple units.

Find more terms in the RAP Glossary of the ABAP Keyword Documentation. There are more artifacts and
concepts related to RAP that go way beyond the scope of this cheat sheet. For example, a RAP BO can be
exposed as a business service to be accessed from outside AS ABAP and consumed. A RAP BO
consumer is either the RAP transactional engine that handles requests from outside the AS ABAP or, from
inside AS ABAP, an ABAP program using ABAP EML (which this cheat sheet and the examples focus on).

⬆ back to top

Excursion: RAP Behavior Definition (BDEF)


 As mentioned in the RAP terms and as the name implies, a RAP behavior definition describes a
RAP business object (RAP BO) by defining its behavior for all of its RAP BO entities.
 BDL source code is used in a BDEF.
 Once you have created ...
o the CDS root entity of a RAP BO, ADT helps you create the skeleton of a BDEF (e.g., right-
click on the CDS root entity and choose New Behavior Definition from the pop-up).
o the BDEF, ADT helps you create the skeleton of an ABAP behavior pool, as well as RAP
handler and saver method declarations and the skeleton of implementations via ADT quick
fixes.
 More information (see also the subtopics there):
o Structure of a RAP behavior definition
o Infos about BDL syntax
o Infos about behavior definitions

The following example shows a commented BDEF. Note that there is a wide variety of possible
specifications and options. The example shows only a selection. For full details, refer to the ABAP Keyword
Documentation. Some of the syntax examples are commented out, just for the sake of showing more
syntax options.

//Possible implementation types: managed, unmanaged, abstract, projection, interface


//(which restrict/enable further specifications)
//You can specifiy one or more implementation classes (behavior pools/ABPs -> bp...)
//for the RAP BO (in some contexts, specifying no ABP is possible).
//Specifying unique is mandatory (each operation can only be implemented once).
managed implementation in class bp_some_demo unique;
//For managed RAP BOs, you can enable user-defined saving options (optional additions
//are available).
//Purpose: Enhancing or replacing the default save sequence (Note: Only in this case,
//the ABP has a local saver class/save_modified saver method)
//managed with additional save with full data implementation in class bp_some_demo unique;
//full data: Full instance data is passed for saving
//managed with unmanaged save implementation in class bp_some_demo unique;

//Enabling the strict mode (and version) to apply additional syntax checks; handled by
//the RAP framework; it is recommended that you use the most recent version
strict ( 2 );

//Enabling RAP draft handling


//with draft;

//It is mandatory to specify an entity behavior definition for the RAP BO root entity.
//Here, some_demo represents a CDS view entity.
define behavior for some_demo
//Specifying an alias name (e.g. to have a more telling name than the technical name of
//the entity). When specifying an alias name, you should address the entity with the alias
//name instead of the full name (e.g. in the signature of handler methods).
//define behavior for some_demo alias root

//Specifying the database table a RAP BO is based on (only available/mandatory in managed


//BOs); note further requirements for diverse scenarios in the documentation
persistent table some_dbtab

//Mandatory specification of a draft table when a RAP BO is draft-enabled


//draft table drafttab

//Specifying the locking mechanism for entities, e.g. to prevent a simultaneous


//modification. In unmanaged RAP BOs, this must be self-implemented in a dedicated handler
//method
lock master

//Controlling authorization that is to be implemented in an ABP (also for managed)


//You can specify variants: global (e.g. for restricting certain operations) and/or
//instance (restrictions based on entity instances) or both of them (dedicated handler
//methods must be implemented)
//More variants are available that can be specified in the { ... } block below for
//excluding and delegating authorization checks (e.g. authorization:update)
authorization master ( instance )
//authorization master ( global )
//authorization master ( instance, global )

//Defining late numbering for primary key fields (see the adjust_numbers handler method)
//More numbering options are available such as early numbering, or, in the { ... } block below,
//the 'numbering : managed' specification for particular fields.
//late numbering

//Defining a field as entity tag (ETag) field for optimistic concurrency control (i.e.
//enabling transactional access to data by multiple users to avoid inconsistencies when
//unintentionally changing already modified data). More options available, e.g. for
//draft-enabled RAP BOs (total etag).
//etag master some_field

{
//RAP BO operations
//Standard operations (Note: Read is implicitly enabled, no specification available)
create;
update;
//More additions are available dealing with authorization, feature control, precheck etc.
//The example shows precheck. In doing so, you can implement a precheck (e.g. to prevent
//unwanted changes) before instances are deleted in a dedicated handler method. A precheck
//implementation is also available for other operations (e.g. actions).
//As is true for various specifications, a comma-separated list of specifications is possible.
delete( precheck );

//Note: It is not possible to specify operations multiple times. The following specifications
//just demonstrate syntax options. Anyway, the compiler helps you not to specify wrong notations.
//Applying feature control
//delete( features: global );

//Applying authorization control


//delete( authorization : update );

//Operations for associations (many specification options are possible)


//The following example means enabling create-by-association operations for associations
//Assumption: _child is specified in the the underlying CDS data model.
association _child { create; }

//Non-standard operations (check the specification options in the documentation, e.g. feature
//control and others are possible) such as actions (modify RAP BO instance) and functions (return
//information). There are different flavors of actions such as non-factory and factory actions,
//which themselves have different variations. Other flavors of actions are save actions (only to
//be executed during save sequence), determine actions (allow RAP BO consumers to execute
//determinations and validations on request), and draft actions.

//Non-factory actions (modify existing instances)


//Instance action, relates to instances, modify instances
action act1;

//Static action, not bound to instances, relates to the entrie entity


static action act2;

//Internal action, accessible only from within the ABP (internal can also be specified in other
//contexts, e.g. operations)
internal action act3;

//You can optionally specify input or output parameters or both (not always possible for all
//action types). The following example shows an output parameter, defined with the result
//addition. It stores the result of an action in an internal table. Variants are possible for
//the return type. Here, it is $self (result type is the same type as entity) It can, for
//example, also be an abstract BDEF or a different entity.
action act4 result [1] $self;

//Input parameter specified following 'parameter' (in this case, a CDS abstract entity)
action act5 parameter some_cds_abstract;
//Factory action (to create instances, can be instance-bound or static)
//Specifying the cardinality is mandatory
factory action act6 [1];

//Draft actions
//Available for draft-enabled RAP BOs, allow data modification on the draft table; are
//implicitly available; it is recommended for the draft actions to be specified explicitly;
//for some of the methods, the 'with additional implementation' addition is available

//Copies active instances to the draft table


//draft action Edit;

//Sets a lock for entity instances on the persistent database table


//draft action Resume;

//Copies draft table content to the persitent database table; recommendation: use the
//optimized addition
//draft action Activate optimized;

//Clears entries from the draft database table


//draft action Discard;

//Corresponds to the determine actions for active instances;


//used to validate draft data before transitioning to active data
//draft determine action Prepare
// {
//You can assign validations and determinations defined with 'on save'
// validation val;
// }

//Functions (similar to actions, there are optional additions, such as static)


//Since they return information, specifying an output parameter is required.
//Instance function
function func1 result [0..*] $self;

//Static function
static function func2 result [1] some_cds_abstract;

//Instance function with optional input parameter


function func3 parameter some_cds_abstract result [1] $self;

//Field characteristics
//Field values cannot be created/updated
field ( readonly ) field1;

//Read-only during update (especially key fields created during create operations)
field ( readonly : update ) key_field;

//The mandatory specification denotes that values must be provided for the fields before persisting
//them to the database.
//Comma-separated list possible for the field characteristics in general;
//mutliple characteristics can also be specified in a comma-separated list in the parentheses
field ( mandatory ) field2, field3;

//Defining access restrictions for fields


field ( features : instance ) field4;

//Validations
//Checking the consitency of instances; validations are triggered based on conditions
//Conditions (one or more are possible) can be specified for create, update, delete operations
//and modified fields; note: not available for unmanaged, non-draft RAP BOs.
validation val on save { create; field field1; }

//Determinations
//Modifying instances based on trigger conditions;
//As above, conditions (one or more are possible) can be specified for create, update, delete
//operations and modified fields. The triggering is possible for 'on modify' and 'on save'.
determination det1 on modify { update; delete; field field5, field6; }
determination det2 on save { create; field field7, field8; }

//RAP business event (derived events with the specification 'managed evt ...' are also possible)
event evt;

//RAP side effects, to trigger a reload of affected properties on the UI


//Trigger properties: Field changes, action executions
//Multiple side effects can be specified within a { ... } block, separated by a colon
//There are multiple options to specify the target following 'affect'; the example uses fields
//to be reloaded
side effects { field field1 affects field field4;
field field2 affects field field4;
field field3 affects field field4;
action act1 affects field field4; }

//It is optional to specify an entity behavior definition for child entities


define behavior for some_child_entity alias child

//Applying locks dependent on the specified association (locks are delegated to


//the specified association). In this case, it's the parent entity. Assumption:
//_parent is specified in the the underlying CDS data model.
lock dependent by _parent

//Applying authorization checks dependent on the specified association


//As above, the assumption is that _parent is specified in the underlying CDS
//data model.
authorization dependent by _parent

{
update;
delete;
field ( readonly ) key_field;
field ( readonly : update ) key_field_child;
association _parent;
}

⬆ back to top

ABAP Behavior Pools (ABP)


As mentioned above, you can access RAP BO data from inside AS ABAP using EML. Among other things,
EML allows you to read or modify RAP BOs by accessing the RAP BO data (the RAP BO instances) in the
transactional buffer and trigger the persistent storage or reset changes. More precisely, when EML
statements are executed, the calling of RAP handler methods is triggered to access the transactional
buffer of a RAP BO. As mentioned, for unmanaged RAP BOs or unmanaged parts of managed RAP BOs,
the handler methods that are called are part of an ABAP behavior pool.

The global class of an ABP has the addition FOR BEHAVIOR OF bdef to the definition while bdef stands for
the name of the BDEF. This class is (initially) empty apart from the declaration and implementation part
skeleton.
CLASS zbp_demo_abap_rap_draft_m DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF
zdemo_abap_rap_draft_m.
ENDCLASS.

CLASS zbp_demo_abap_rap_draft_m IMPLEMENTATION.


ENDCLASS.

The actual implementation is done in local classes in the CCIMP include (Local Types tab in ADT) of the
behavior pool. There, two kinds of local classes are to be defined and implemented that are related to the
RAP BO's runtime: one or more handler classes to implement the RAP BO behavior (in RAP handler
methods) during the RAP interaction phase (the data reading and modification phase) and a saver
class to implement the RAP save sequence (in saver methods to save data from the transactional buffer to
the database).

⬆ back to top

RAP Handler Classes and Methods

 One or more handler classes implement the RAP interaction phase. For modularization purposes,
one behavior pool can define multiple handler classes. For example, each entity can have its own
handler class, or individual handler classes can be defined to distinguish between reading and
changing RAP BO entities.
 A handler class inherits from class CL_ABAP_BEHAVIOR_HANDLER.
 These classes are implicitly ABSTRACT and FINAL since instantiating and calling only happens through
the RAP runtime engine.
 ADT helps you create the classes and methods (and basically the ABP as such) when creating the
BDEF. A quick fix is available that creates the method definitions and a skeleton of the
implementations automatically.

Example: Handler class definition

CLASS lhc_root DEFINITION INHERITING FROM cl_abap_behavior_handler.


...
ENDCLASS.

 Handler method definitions include the additions ... FOR ... FOR ... followed by the kinds of
operations. There are various options depending on the RAP BO operation.
 Depending on the definition in the BDEF, there might be more additions with dedicated method
parameters. For example, an action might be defined with a result parameter, hence, the method
must be defined with the addition RESULT and a parameter.
 The FOR MODIFY handler method can handle multiple entities and operations, i. e. not only create
but also update or delete might be integrated in the method definition. However, it might be
useful to split the handler method into separate methods for better readability.
 See more details on the handler method definitions in the topic METHODS, FOR.

Example: Handler method definitions

"Create
METHODS create FOR MODIFY
IMPORTING entities FOR CREATE bdef.

"Read: Specifying a read result is mandatory.


METHODS read FOR READ
IMPORTING keys FOR READ bdef RESULT result.

"Action: action name is preceded by the BDEF name and a tilde after FOR ACTION
METHODS some_action FOR MODIFY
IMPORTING keys FOR ACTION bdef~some_action.

Parameters of Handler Methods

 The handler method definitions contain RAP-specific additions like FOR MODIFY, FOR CREATE or FOR
READ as well as mandatory or optional additions like RESULT that are followed by parameters.
 Nearly all parameters are typed with BDEF derived types that have special RAP-related
components as covered further down.
 The parameters' names can be chosen freely. This is also true for the method names except for
some predefined names.
 Each handler method must have at least one importing parameter. The addition IMPORTING is
optional since it is used implicitly. In most cases, entire instances or just key values of instances are
imported.
 All handler methods have changing parameters that are usually not explicitly specified in the
definition but implicitly used. The explicit specification of the CHANGING addition is not needed. In
most cases, these are RAP response parameters. The following image shows the F2 information in
ADT for the create handler
method.

 The response parameters mapped, failed and reported (the names are predefined) can be
considered as containers for information - information a RAP BO consumer is provided with by a
RAP BO provider, for example, an SAP Fiori app displays an error message if something went
wrong. The availability of the parameters depends on the handler method used (e. g. mapped is only
available for operations creating instances).
o mapped: Used to provide mapping information on RAP BO instances, for example, which key
values were created for given content IDs ( %cid).
o failed: Information for identifying the data set for which an error occurred in a RAP
operation
o reported: Used, for example, to exchange error messages for each entity defined in the BDEF
and not related to a specific entity.
o Example: Technically, the reported parameter is a deep structure containing, for example,
the messages of the root entity and child entities. For example, if a create operation fails for
a RAP BO instance of the root entity, a message, information about the instance key and
other things can be included in this parameter which is passed to a RAP BO consumer. You
could imagine that such an error message is displayed on an SAP Fiori UI if something goes
wrong to inform the user.

⬆ back to top

RAP Saver Class and Saver Methods

 A RAP saver class implements the RAP save sequence. A saver class is usually only available in
unmanaged RAP BOs (except for special variants of managed RAP BOs that are not outlined here).
 The saver class is implicitly ABSTRACT and FINAL since the instantiating and calling only happens
through the RAP runtime engine.
 A saver class can be defined in the CCIMP include of an ABAP behavior pool. It includes the
definitions and implementations of RAP saver methods.
 The saver methods consist of a set of predefined methods having predefined names. Some of
them are mandatory to implement, some are optional. The adjust_numbers method is only available
in late numbering scenarios.
 A saver class inherits from class CL_ABAP_BEHAVIOR_SAVER. The saver methods are declared by
redefining predefined methods of the superclass. They implicitly have response parameters.
 In contrast to RAP handler methods, saver methods do not have data of RAP BO instances as
import parameter. Therefore, instance data must be handled via the transactional buffer when self-
implementing the saver methods.
 Saver methods are called when the RAP save sequence has been triggered by a COMMIT
ENTITIES statement. Note that in natively supported RAP scenarios, for example, an SAP Fiori app
using OData, the COMMIT ENTITIES call is performed implicitly and automatically by the RAP runtime
engine.
 Find more information on RAP saver methods here.

Example: Definition of a RAP saver class and saver methods

CLASS lsc_bdef DEFINITION INHERITING FROM cl_abap_behavior_saver.


PROTECTED SECTION.

"For final calculations and data modifications involving all


"BOs in the current RAP transaction
METHODS finalize REDEFINITION.

"Checks the consistency of the transactional buffer before


"the save method saves data to the database
METHODS check_before_save REDEFINITION.

"Preliminary IDs are mapped to final keys. Only for late numbering.
METHODS adjust_numbers REDEFINITION.

"Saves the current state of the transactional buffer to the database


METHODS save REDEFINITION.

"Clear the transactional buffer


METHODS cleanup REDEFINITION.
METHODS cleanup_finalize REDEFINITION.

ENDCLASS.

⬆ back to top

BDEF Derived Types


The operands of EML statements and parameters of handler and saver methods are mainly special
messenger tables for passing data and receiving results or messages, i. e. the communication between a
RAP BO consumer and the RAP BO provider using EML consists (in most cases) of exchanging data stored
in internal tables that have special ABAP types - BDEF derived types. These types are tailor-made for RAP
purposes.

As the name implies, the types are derived by the ABAP runtime framework from CDS entities and their
behavior definition in the BDEF. With these special types, a type-safe access to RAP BOs is guaranteed.
You can create internal tables (using TYPE TABLE FOR), structures (using TYPE STRUCTURE FOR) and data types
with BDEF derived types. For all operations and behavior characteristics defined in the BDEF, types can be
derived.
The syntax uses - similar to the method definitions mentioned before - the addition FOR followed by the
operation and the name of an entity (and, if need be, the concrete name, e. g. in case of an action defined
in the BDEF).
Each BDEF derived type can be categorized as input or output derived type according to its use as
importing or exporting parameters in methods of RAP BO providers. In most cases, structures of type TYPE
STRUCTURE FOR can be considered as serving as work area and line type of the internal tables. However,
there are also structured derived types that do serve as types for handler method parameters.
The response parameters mapped, failed and reported have dedicated derived types: TYPE RESPONSE FOR.
They are deep structures containing the information for the individual entities of the RAP BO. The
components of these structures are internal tables of appropriate types with TYPE TABLE FOR.
Examples for BDEF derived types:

"Data objects with input derived types (entity = name of a root entity)

"For an EML create operation


DATA create_tab TYPE TABLE FOR CREATE entity.

"For an update operation


DATA update_tab TYPE TABLE FOR UPDATE entity.

"Type for create-by-association operations specifying the name of the entity


"and the association
DATA cba_tab TYPE TABLE FOR CREATE entity\_child.

"For an action execution; the name of the action is preceded by a tilde


DATA action_imp TYPE TABLE FOR ACTION IMPORT entity~action1.

"Data objects with output derived types

"For a read operation


DATA read_tab TYPE TABLE FOR READ RESULT entity.

"For an action defined with a result


DATA action_res TYPE TABLE FOR ACTION RESULT entity~action2.

"Examples for structures and types


DATA create_wa TYPE STRUCTURE FOR CREATE entity.

"For permission retrieval


DATA perm_req TYPE STRUCTURE FOR PERMISSIONS REQUEST entity.

"For retrieving global features


DATA feat_req TYPE STRUCTURE FOR GLOBAL FEATURES RESULT entity.

"Type declaration using a BDEF derived type


TYPES der_typ TYPE TABLE FOR DELETE entity.

"Response parameters
DATA map TYPE RESPONSE FOR MAPPED entity.
DATA fail TYPE RESPONSE FOR FAILED entity.
DATA rep TYPE RESPONSE FOR REPORTED entity.

� Note
Some of the derived types can only be created and accessed in implementation classes.

⬆ back to top

Components of BDEF Derived Types


Many of the BDEF derived types contain components of CDS entities like key and data fields that retain
their original data type, for example, a messenger table typed with TYPE TABLE FOR CREATE. Certainly, if an
instance is to be created, key and field values of a RAP BO instance are of relevance.
Yet, all BDEF derived types contain special RAP components serving a dedicated purpose. The names of
these RAP components begin with % to avoid naming conflicts with components of the CDS entities. The
following image shows the F2 information of a BDEF derived type containing the % components and fields
from the CDS entity.

Some of the % components are component groups summarizing groups of table columns under a single
name. In doing so, they simplify the handling of derived types for developers. For example, the
component group %data contains all primary key and data fields of a RAP BO entity (actually, by
containing the keys, it also contains the component group %key in the case above). The F2 information in
ADT helps you find out about the available components in a variable. The image below shows the details
of %data when clicking the derived type link in the first ADT F2 information screen.
The availability of % components depends on definitions in the BDEF. Their availability also depends on
more criteria, for example, the scenario. For example, the component %pid that represents a preliminary ID
for a RAP BO instance is only available in late numbering scenarios. The draft indicator %is_draft is only
relevant in the context of draft.
Find more details on the available components in section Components of BDEF Derived Types.

Bullet points on selected % components:

 %cid
o A string to define a content ID.
o Content IDs are used as a unique and preliminary identifier for RAP BO operations in which
instances are created and especially in cases where the key values of RAP BO instances are
not yet determined
o Assume that you create a RAP BO instance with an EML create request and the key value
has not yet been determined. In the same request - a save has not yet been triggered - an
update is requested for this RAP BO instance. Using the content ID, it is guaranteed that the
update operation happens for the desired instance. For this purpose, derived types for
operations like update or delete include the component %cid_ref to refer to the content
ID %cid as the name implies.
o Note: You should always fill %cid even if not needed. The specified content ID is only valid
within one ABAP EML request. You can use the optional addition AUTO FILL CID in EML
modify operations to create %cid automatically. However, if you use this addition, you
cannot refer to %cid in subsequent operations.
 %key/%tky
o Both are component groups summarizing all primary keys of a RAP BO instance.
o Where possible, it is recommended that you use %tky instead of %key. %tky includes %key and
also the draft indicator %is_draft. When using %tky in non-draft scenarios, you are prepared
for a potential, later switch to a draft scenario. In doing so, you can avoid lots of adaptations
in your code by manually adding the indicator.
 %control
o Structured component that is a component of many BDEF derived types. It contains the
names of all key and data fields of a RAP BO instance, which indicate flags.
o For example, it is used to get information on which fields are provided or set a flag for
which fields are requested by RAP BO providers or RAP BO consumers respectively during
the current EML request.
o For this purpose, the value of each field in the %control structure is of type ABP_BEHV_FLAG.
For the value setting, you can use the structured constant mk of interface IF_ABAP_BEHV. Note
that the technical type is x length 1.
o Example: If you want to read data from a RAP BO instance and particular non-key fields
in %control are set to if_abap_behv=>mk-off, the values of these fields are not returned in the
result.

⬆ back to top

EML Syntax
The focus is here on selected EML statements. These statements can be fairly long and various additions
are possible. Find more information on the EML statements here.

EML Syntax for Modifying Operations


The modifying operations covered include the standard operations (using the additions CREATE, CREATE
BY, UPDATE, and DELETE) and non-standard operations (actions) using the addition EXECUTE. All EML
statements for the mentioned operations begin with MODIFY. The following commented code snippets
demonstrate the short and long form of EML MODIFY statements.
� Note
Unlike reading operations, modifying operations are not enabled by default. You must make the
respective notations in the BDEF:

Explain
...
create;
update;
delete;
action some_act;
...

Create operation for creating new instances of a RAP BO entity:

"Declaration of data objects using BDEF derived types

DATA: cr_tab TYPE TABLE FOR CREATE root_ent, "input derived type
mapped_resp TYPE RESPONSE FOR MAPPED root_ent, "response parameters
failed_resp TYPE RESPONSE FOR FAILED root_ent,
reported_resp TYPE RESPONSE FOR REPORTED root_ent.

"Input derived type for the EML statement is filled using the VALUE operator
"Assumption: key_field is the key field having type i,
"field1 and field2 are data fields with character-like data type.
"Specify %cid even if not used or of interest; it must be unique within a request

cr_tab = VALUE #(
( %cid = 'cid1' key_field = 1
field1 = 'A' field2 = 'B' )
( %cid = 'cid2'
"Just to demo %data/%key. You can specify fields with or without
"the derived type components
%data = VALUE #( %key-key_field = 2
field1 = 'C'
field2 = 'D' ) ) ).

"EML statement, short form


"root_ent must be the full name of the root entity, it is basically the name of the BDEF
MODIFY ENTITY root_ent
CREATE "determines the kind of operation
FIELDS ( key_field field1 field2 ) WITH cr_tab "Fields to be respected for the
"input derived type and the input
"derived type itself
MAPPED mapped_resp "mapping information
FAILED failed_resp "information on failures with instances
REPORTED reported_resp. "messages

� Note

 Addition FIELDS ( ... ) WITH: This field selection option specifies which fields are to be respected
for the operation. The derived type, i. e. an internal table containing the concrete RAP BO instance
values, follows WITH. If a field is specified in the field list within the pair of parentheses after FIELDS,
the %control flag for this field is automatically set to if_abap_behv=>mk-on. Likewise, if a field is not
contained in the list, the flag in %control is set to if_abap_behv=>mk-off. Assume field2 is not
specified in the list. The value for field2 will not be respected (even if a value is specified in the
internal table). The initial value will be used for the field.
 Retrieving the responses and specifying the parameters is optional. Assuming a data set with the
value 2 for key_field already exists on the database for this BO, you should expect an entry for this
particular instance in the failed_resp operand and potentially an error message in reported_resp,
too. Nevertheless, especially in ABP implementations and depending on the context, you should
implement and fill these parameters according to the RAP BO contract to meet the variety of
implementation rules.
 %cid should be provided even if you are not interested in it and subsequent operations do not
require the reference.

Long form of an EML MODIFY statement:


MODIFY ENTITIES OF root_ent "full name of root entity
ENTITY root "root or child entity (alias name if available)
CREATE FROM "FROM as further field selection variant
VALUE #( ( %cid = 'cid' "Input derived type created inline
key_field = 3
field1 = 'E'
field2 = 'F'
%control = VALUE #( "Must be filled when using FROM
key_field = if_abap_behv=>mk-on
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on ) ) )
MAPPED DATA(m) "Target variables declared inline
FAILED DATA(f)
REPORTED DATA(r).

� Note

 The entity specified after ENTITY can be either the root entity itself or a child entity. If an alias is
defined, the alias should be used.
 The addition FIELDS ( ... ) WITH from the previous snippet is basically a shortcut for the
addition FROM that is used here. When using FROM, the values of the %control structure must be
specified explicitly.
 The BDEF derived types can also be created inline as shown in the example using a constructor
expression for the input derived type and with DATA or FINAL for the responses.
 The long form allows you to bundle several operations in one statement, either different
operations on the same entity (for example, deleting some instances and updating some others) or
operations on different entities of the same RAP BO (for example, creating a root entity instance
and related instances of a child entity in one EML request). Long and short forms are also available
for other EML statements.
 The SET FIELDS WITH addition is available as another field specification option. However, it has
limitations that you should be aware of. It can cause syntax warnings. Check the documentation. It
is recommended that you use FIELDS ... WITH and FROM.

Excursion: Specifying %control component values in the short form of VALUE constructor expressions
"The following EML statement creates RAP BO instances. The BDEF derived
"type is created inline. With the FROM addition, the %control values
"must be specified explicitly. You can provide the corresponding values
"for all table lines using the short form, i.e. outiside of the inner
"parentheses, instead of individually specifying the values for each
"instance within the parentheses. In this case, the corresponding %control
"component value is assigned for all of the following table lines.
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FROM VALUE #(
%control-key_field = if_abap_behv=>mk-on
%control-field1 = if_abap_behv=>mk-on
%control-field2 = if_abap_behv=>mk-on
%control-field3 = if_abap_behv=>mk-on
%control-field4 = if_abap_behv=>mk-off
( %cid = 'cid1'
key_field = 1
field1 = 'aaa'
field2 = 'bbb'
field3 = 10
field4 = 100 )
( %cid = 'cid2'
key_field = 2
field1 = 'ccc'
field2 = 'ddd'
field3 = 20
field4 = 200 ) )
MAPPED DATA(m)
FAILED DATA(f)
REPORTED DATA(r).

The following EML statement combines multiple operations in one EML request. It demonstrates the use
of %cid and %cid_ref. First, two instances are created by specifying %cid. An update operation in the same
request only specifies a certain field within the parentheses of the FIELDS ( ... ) WITH addition which
denotes that only this particular field should be updated. The other field values remain unchanged. The
reference to the instance is made via %cid_ref. Consider an EML request in which no instance to refer to
using %cid_ref exists, e. g. for an update operation. You can also make the reference using the unique
key. A delete operation is available in the same request, too. DELETE can only be followed by the
addition FROM. In contrast to other derived types, the derived type that is expected here (TYPE TABLE FOR
DELETE) only has %cid_ref and the key as components.
MODIFY ENTITIES OF root_ent
ENTITY root
CREATE FIELDS ( key_field field1 field2 ) WITH
VALUE #( ( %cid = 'cid4' key_field = 4
field1 = 'G' field2 = 'H' )
( %cid = 'cid5' key_field = 5
field1 = 'I' field2 = 'J' ) )

UPDATE FIELDS ( field2 ) WITH


VALUE #( ( %cid_ref = 'cid4' field2 = 'Z' ) )

DELETE FROM
VALUE #( ( %cid_ref = 'cid5' ) "Instance referenced via %cid_ref
( key_field = 9 ) ) "Instance referenced via the key
...

EML statement including the execution of an action:


MODIFY ENTITIES OF root_ent
ENTITY root
EXECUTE some_action
FROM action_tab
RESULT DATA(action_result) "Assumption: The action is defined with a result parameter.
...

The following code snippet shows a deep create. First, an instance is created for the root entity. Then, in
the same request, instances are created for the child entity based on the root instance. In the example
below, the assumption is that a composition is specified in the root view entity like composition [1..*] of
root_ent as _child and key_field and key_field_child are the keys of the child view entity. The structured
component %target enters the picture here which contains the target's primary key and data fields.
MODIFY ENTITIES OF root_ent
ENTITY root_ent
CREATE FIELDS ( key_field field1 field2 ) WITH
VALUE #( ( %cid = 'cid6' key_field = 6
field1 = 'I' field2 = 'J' ) )
CREATE BY \_child
FIELDS ( key_field_child field1_child field2_child ) WITH
VALUE #( ( %cid_ref = 'cid6'
%target = VALUE #( ( %cid = 'cid_child_1'
key_field_child = 1
field1_child = 'aa'
field2_child = 'bb' )
( %cid = 'cid_child_2'
key_field_child = 2
field1_child = 'cc'
field2_child = 'dd' ) ) ) )
...

⬆ back to top

EML Syntax for Reading Operations

 Read-only operations always return a result, i.e. the syntax of the EML statement requires the
addition RESULT and an operand.
 When RAP BO instances are read, the returned data include the current status of instances in the
transactional buffer which includes unsaved modifications on instances. If an instance is not yet
available in the transactional buffer, the currently persisted data set is automatically read into the
transactional buffer.
 Note that read operations are always implicitly enabled for each entity listed in a BDEF, i. e. there is
no extra definition in the BDEF in contrast to, for example, create or update.

The following code snippet shows the long form of the EML READ statement for reading instances from
the root entity. In READ statements, the additions FIELDS ( ... ) WITH and FROM can also be used to specify
the fields that you intend to read. Here, the addition ALL FIELDS WITH is available for reading all field
values.
READ ENTITIES OF root_ent
ENTITY root_ent
ALL FIELDS WITH
VALUE #( ( key_field = 1 ) "Derived type TYPE TABLE FOR READ IMPORT only includes the keys
( key_field = 2 ) )
RESULT DATA(result)
FAILED DATA(f)
REPORTED DATA(r).

Read-by-association operations include the optional addition LINK with which you can retrieve the keys of
the source and target (i. e. the associated entity). The by-association operations work reciprocally, i. e. you
can, for example, read a child instance via the parent and a parent instance via the child, too.
"Read-by association operation: parent to child
READ ENTITIES OF root_ent
ENTITY root_ent
BY \_child
ALL FIELDS WITH VALUE #( ( key_field = 1 ) )
RESULT DATA(rba_res1)
LINK DATA(links1).
...

"Read-by association operation: child to parent


READ ENTITIES OF root_ent
ENTITY child_ent
BY \_parent
ALL FIELDS WITH VALUE #( ( key_field = 1 key_field_child = 1 ) )
RESULT DATA(rba_res2)
LINK DATA(links2).
...

⬆ back to top

Dynamic Forms of EML Statements


In addition to the short and long forms described above, various ABAP EML statements also have
dynamic forms. Taking EML read operations as an example, the following code snippet shows a dynamic
EML READ ENTITIES statement. The relevant syntax element is the OPERATIONS addition. The dynamic form
allows the collection of read operations for multiple RAP BOs in one EML statement. For more
information, see the ABAP keyword documentation and the comments in the snippet.
"The statement is taken from the executable example. The example has a
"root entity and a child entity. For both entities, RAP BO instances
"are to be read (read and read-by-association operation).

DATA:
"The following data object is the operand of the dynamic EML statement
"It is an internal table and has a special, RAP-specific type.
op_tab TYPE abp_behv_retrievals_tab,

"More data object declarations (internal tables typed with BDEF


"derived types) that are relevant for the EML statement.
"For both entities (root and child), RAP BO instances are to be
"read. The internal tables are used for components of the internal
"table op_tab further down.
read_dyn TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m,
read_dyn_result TYPE TABLE FOR READ RESULT zdemo_abap_rap_ro_m,
rba_dyn TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m\_child,
rba_dyn_result TYPE TABLE FOR READ RESULT zdemo_abap_rap_ro_m\_child,
rba_dyn_link TYPE TABLE FOR READ LINK zdemo_abap_rap_ro_m\_child.

"Filling the internal tables, i.e. which instances are to be read


"Root entity
"Example:
"- The key is comprised of the field 'key_field'. It is of type i.
"- The %control structure is filled, flagging those fields that
" are to be read. Flagging the key field is not required.
read_dyn = VALUE #(
( %key-key_field = 1
%control = VALUE #(
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on
field3 = if_abap_behv=>mk-on
field4 = if_abap_behv=>mk-on ) )
( %key-key_field = 2
%control = VALUE #(
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on
field3 = if_abap_behv=>mk-on
field4 = if_abap_behv=>mk-on ) ) ).

"Child entity
"Instances to be read for a read-by-association operation
"The shared key is 'key_field'.
rba_dyn = VALUE #(
( %key-key_field = 1
%control = VALUE #(
key_ch = if_abap_behv=>mk-on
field_ch1 = if_abap_behv=>mk-on
field_ch2 = if_abap_behv=>mk-on ) )
( %key-key_field = 2
%control = VALUE #(
key_ch = if_abap_behv=>mk-on
field_ch1 = if_abap_behv=>mk-on
field_ch2 = if_abap_behv=>mk-on ) ) ).

"Filling the internal table that is the operand of the


"dynamic EML statement
"This table has optional and mandatory components.
op_tab = VALUE #(
( "op: Specifies the operation to be executed; is mandatory;
" can be set with the predefined constants, e.g. OP-R-READ
" etc., of interface IF_ABAP_BEHV
op = if_abap_behv=>op-r-read
"entity_name: Specifies the name of the RAP BO entity for which
" the operation is executed; is mandatory
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
"instances: Specifies a reference to an internal table holding
" the input keys; must be appropriately typed; is mandatory
instances = REF #( read_dyn )
"results: Specifies a reference to an internal table with the required
" BDEF derived type for the read results; is mandatory
results = REF #( read_dyn_result ) )
( op = if_abap_behv=>op-r-read_ba
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
"sub_name: Only relevant for specifying association names in
" read-by-association operations; in that context, it is mandatory
sub_name = '_CHILD'
"full: Optional flag; specifies if all target instances are to be retrieved
full = abap_true
instances = REF #( rba_dyn )
results = REF #( rba_dyn_result )
"links: Reference to internal table holding the key pairs of the source and
" target
links = REF #( rba_dyn_link ) ) ).

READ ENTITIES OPERATIONS op_tab.

⬆ back to top

Persisting to the Database

 A COMMIT ENTITIES statement triggers the RAP save sequence. Without such a statement, the
modified RAP BO instances that are available in the transactional buffer are not persisted to the
database. As mentioned above, in case of a natively supported RAP scenario (for example, when
using OData), the COMMIT ENTITIES request is executed automatically.
 COMMIT ENTITIES implicitly includes COMMIT WORK.
 Note: COMMIT ENTITIES statements cannot be used in behavior implementations.
 There are multiple variants available for the statement as described in the ABAP Keyword
Documentation here. For example, RAP responses can be retrieved, key conversion in late
numbering scenarios, checking a RAP transaction in a simulation mode.
 COMMIT ENTITIES statements set the system field sy-subrc. When using COMMIT ENTITIES, it is not
guaranteed that COMMIT WORK is carried out successfully. Hence, you should include a check for sy-
subrc after COMMIT ENTITIES so that you can react to failures accordingly.

The following snippet shows a create operation. This operation has only an impact on the database with
the COMMIT ENTITIES statement. Triggering the save sequence means that the execution of the statement
triggers the calling of the saver methods available in the saver class of a behavior implementation. In
managed scenarios (except for some special variants), the saving is done automatically without
implementing a dedicated saver method.
MODIFY ENTITIES OF root_ent
ENTITY root_ent
CREATE FIELDS ( key_field field1 field2 ) WITH
VALUE #( ( %cid = 'cid' key_field = 7
field1 = 'K' field2 = 'L' ) )
MAPPED DATA(mapped)
FAILED DATA(failed)
REPORTED DATA(resp).

COMMIT ENTITIES.

IF sy-subrc <> 0.
...
ENDIF.

⬆ back to top

Raising RAP Business Events

 RAP business events can be raised in ABAP behavior pools with RAISE ENTITY EVENT statements.
 The focus of the snippets is on the local consumption of RAP business events. Prerequisites:
o event specifications are available in the BDEF (e.g. ... event some_evt; ...). For more
details, refer to the BDL documentation
o A RAP event handler class is available that is used to implement RAP event handler
methods.
 Note that these methods are called asynchronously.
 Similar to RAP handler and saver methods, RAP event handler methods are
implemented in the CCIMP include of the RAP event handler class.
 To locally consume RAP business events, a local class that inherits
from CL_ABAP_BEHAVIOR_EVENT_HANDLER can be implemented in the CCIMP include of a
RAP event handler class.
 More information:
o ABAP for RAP Business Events in the ABAP Keyword Documentation
o Business Events in the SAP Help Portal

"---- Syntax for the declaration part of a global RAP event handler class ----
CLASS cl_event_handler DEFINITION PUBLIC FOR EVENTS OF some_bdef.
...
ENDCLASS.

"---- Syntax for the declaration part of a local event handler class ----
"---- in the CCIMP include of a RAP event handler class ----
CLASS lhe_event DEFINITION INHERITING FROM cl_abap_behavior_event_handler.
...
ENDCLASS.

"---- RAP event handler method definition ----


"Notes:
"- Must be defined as instance methods in the private visibility section.
"- The input parameter par is an internal table of type TYPE TABLE FOR EVENT.
"- This type includes the keys of RAP BO instances (and %param, if the event
" is specified with a parameter in the BDEF)
"- The methods do not contain RAP response parameters.
METHODS meth FOR ENTITY EVENT par FOR some_bdef~some_evt.

"---- RAISE ENTITY EVENT statement in an ABP, e.g. the save_modified method ----
"---- in managed scenarios with additional save ----
...
CLASS lsc IMPLEMENTATION.
METHOD save_modified.
"Assumption: An event is specified for create operations in the BDEF as follows
"event created;
IF create-some_bdef IS NOT INITIAL.
RAISE ENTITY EVENT some_bdef~created
FROM VALUE #( FOR <cr> IN create-root ( %key = VALUE #( some_key = <cr>-some_key ) ) ).
ENDIF.

"Assumption: An event is specified for delete operations in the BDEF as follows


"event deleted parameter some_abstract_entity;
"The abstract entity has two parameters, for example, with which additional
"information can be passed.
IF delete-some_bdef IS NOT INITIAL.
RAISE ENTITY EVENT some_bdef~deleted
FROM VALUE #( FOR <del> IN delete-some_bdef (
%key = VALUE #( some_key = <del>-some_key )
%param = VALUE #( par_a = '01'
par_b = 'Item deleted' ) ) ).
ENDIF.
ENDMETHOD.
ENDCLASS.

⬆ back to top

Additions to EML Statements in ABAP Behavior Pools

 There are a special additions when using EML in behavior pools. One of them is IN LOCAL MODE.
 This addition can be used to exclude feature controls and authorization checks.
 Consider the following use case: There is a field to display the booking status of a trip on a UI. In
the BDEF, this field is specified as read-only. Hence, it cannot be modified by a user on the UI.
However, there is a button on the UI to book the trip. This button might trigger an action to book
the trip so that the value of the field changes from open to booked. To enable this, the underlying
handler method for the modify operation with the action to be executed has the addition IN LOCAL
MODE that ignores the feature control.

Syntax:

MODIFY ENTITIES OF root_ent IN LOCAL MODE


ENTITY root
EXECUTE book
FROM action_tab
...

⬆ back to top

RAP Excursions

Using Keys and Identifying RAP BO Instances in a Nutshell


Expand to view the details

RAP Concepts
Expand to view the details

Ensuring Data Consistency in a RAP Transaction


Expand to view the details
⬆ back to top

More Information
 Section ABAP for RAP Business Objects in the ABAP Keyword Documentation including EML
 RAP Glossary
 Development guide for the ABAP RESTful Application Programming Model
 RAP Contract: Rules for the RAP BO provider and consumer implementation to ensure consistency
and reliability

⬆ back to top

Executable Examples
This cheat sheet is supported by different executable examples demonstrating various scenarios:

 Demo RAP scenario with a managed RAP BO, external numbering: zcl_demo_abap_rap_ext_num_m
 Demo RAP scenario with an unmanaged RAP BO, external
numbering: zcl_demo_abap_rap_ext_num_u
 Demo RAP scenario ("RAP calculator") with a managed, draft-enabled RAP BO, late
numbering zcl_demo_abap_rap_draft_ln_m
 Demonstrating the local consumption of RAP business events in the context of a RAP demo
scenario (managed RAP BO with managed internal numbering and additional
save): zcl_demo_abap_rap_m_as

� Note

 To reduce the complexity, the executable examples only focus on the technical side. ABAP classes
play the role of a RAP BO consumer here.
 The examples do not represent real life scenarios and are not suitable as role models for proper
RAP scenarios. They rather focus on the technical side by giving an idea how the communication
and data exchange between a RAP BO consumer and RAP BO provider can work. Additionally, the
examples show how the methods for non-standard RAP BO operations might be self-implemented
in an ABAP behavior pool.
 Due to the simplification, the examples do not entirely meet all requirements of the RAP BO
contract and do not represent semantic or best practice examples.
 You can check out the "RAP calculator" example using the preview version of an SAP Fiori
Elements UI. See the comments in the class for more information.
 The steps to import and run the code are outlined here.

You might also like