Behavior Definitions and Implementations

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A data model only describes what the data looks like. To let people create, change and delete expense claims, a program also has to decide what is allowed and what must happen automatically: a claim with an amount of zero is rejected, a new claim starts in the status "new", and a "submit" button moves it forward. In the RESTful Application Programming Model (RAP) these rules are written in two places. A short text file, the behavior definition, says what a business object can do and under which conditions. A special ABAP class, the behavior pool, holds the code for everything the framework cannot do on its own. This page explains both, using the expense claim of the running example. It is written against ABAP for Cloud Development release 9.20 (2608), where RAP is the standard way to build transactional applications. Every listing needs a RAP framework, a database and ABAP development tools, so each one is labelled as requiring an SAP system and was not run here.

Before you read

Key terms

  • Behavior definition: a repository object, written in the RAP Behavior Definition Language, that defines the operations and characteristics of a business object.

  • Behavior pool: the ABAP class that holds the code of a business object, kept in its local types.

  • Handler class: a local class that inherits from CL_ABAP_BEHAVIOR_HANDLER and implements operations, determinations, validations and checks during the interaction phase and the save sequence.

  • Saver class: a local class that inherits from CL_ABAP_BEHAVIOR_SAVER and takes part in saving, for example to give final keys or to add extra writes.

  • Determination: logic that changes instances automatically when a trigger such as a create or a field change happens.

  • Validation: a consistency check that runs when data is saved and rejects the save when the data is wrong.

  • Action: a custom operation on a business object, such as "submit", that is more than create, update or delete.

  • ETag: a field whose value changes whenever an instance changes, used so that a client cannot overwrite a change it has not seen.

What a behavior definition is

A business object (BO) in RAP is a tree of entities: a root entity such as the claim and, below it, child entities such as the claim items. Each entity is a CDS view entity. The behavior definition (BDEF) is a separate repository object that carries the same name as the root view entity and describes how that tree behaves. The ABAP cheat sheet on the BDL puts it as follows: the behavior definition defines the behavior of the BO and all its entities, covering operations such as create, update and delete and characteristics such as read-only or mandatory fields.

It is written in the RAP Behavior Definition Language (BDL), a small declarative language with its own syntax, not ABAP. It does not contain business logic. It lists what exists: "this entity can be created and updated", "this field is read-only", "this check runs on save". For everything that needs code, the BDEF only names the thing, and the code goes into the behavior pool. The framework reads the BDEF and, from it, knows which methods the behavior pool must contain. That is why an activation error of the pool tells you which method is missing.

In ADT the object is created with the wizard that offers a behavior definition for a CDS root view entity, and it is edited as text with code completion. The text uses these building blocks, which the rest of the page explains one after another.

Building block What it does

Header (managed, unmanaged, strict)

Chooses the implementation type, the pool class and how strict the syntax checks are.

Entity block (define behavior for ... alias ...)

Starts the behavior of one entity of the BO, with its table, ETag, lock and authorization settings.

Standard operations (create, update, delete)

Declare that the entity can be created, changed and deleted.

Field characteristics (field ( readonly ))

Say which fields a consumer may not write, or must fill.

Determinations, validations, actions

Name the logic that the behavior pool implements.

mapping for

Connects the column names of the table to the element names of the view entity.

The header: implementation type and strict mode

The first lines of a BDEF are its header. Two choices matter for a newcomer.

The implementation type says who provides the transactional buffer, the place in memory where changes are collected before they are saved. With managed, the framework provides the buffer and standard create, update and delete work without custom code, so the type suits new development. With unmanaged, the provider has to supply the buffer and implement every operation; it suits existing code that is wrapped by RAP. The cheat sheet adds that the addition unique is mandatory and means each operation can be implemented only once. The managed and unmanaged types have a page of their own later in this section, so here the examples are managed.

Strict mode is written strict ( 2 ); on a line of its own. The cheat sheet says it activates additional syntax checks done by the framework, that version 2 is the most recent and that it is recommended. Older tutorials and older examples may leave strict mode out or use an older version; write strict ( 2 ) in new objects.

The header also names the behavior pool class, for example managed implementation in class zbp_i_expclaim unique;. Its name is up to you; the prefix zbp_ followed by the name of the BDEF is only a convention that the SAP samples follow.

The running example: a first behavior definition

The expense claim of the running example is the root of a business object with items, as defined in CDS Associations, Compositions and Path Expressions: the root view entity ZI_ExpClaim with the composition _Items and the child ZI_ExpItem with the association _Claim. The behavior definition below makes it a managed business object. It is assembled from the statement shapes in SAP’s own sample definitions listed under the listing; the table names zexp_claim and zexp_item, the status codes and the rule "amount must be greater than zero" belong to this example and are invented for it.

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

define behavior for ZI_ExpClaim alias Claim
persistent table zexp_claim
lock master
authorization master ( global )
{
  create;
  update;
  delete;
  association _Items { create; }

  field ( readonly : update ) ClaimId;
  field ( mandatory ) EmployeeId, CurrencyCode, TotalAmount;
  field ( readonly ) Status;

  determination setStatusNew on modify { create; }
  validation validateAmount on save { create; update; field TotalAmount; }
  action submit result [1] $self;

  mapping for zexp_claim
    {
      ClaimId      = claim_id;
      EmployeeId   = employee_id;
      Status       = status;
      CurrencyCode = currency_code;
      TotalAmount  = total_amount;
    }
}

define behavior for ZI_ExpItem alias Item
persistent table zexp_item
lock dependent by _Claim
authorization dependent by _Claim
{
  update;
  delete;
  field ( readonly ) ClaimId;
  field ( readonly : update ) ItemNo;
  association _Claim;

  mapping for zexp_item
    {
      ClaimId       = claim_id;
      ItemNo        = item_no;
      Category      = category;
      Amount        = amount;
      CurrencyCode  = currency_code;
    }
}

Reading it from the top. The header makes the object managed with strict mode 2. define behavior for ZI_ExpClaim alias Claim starts the claim entity; the alias Claim is the short name that the behavior pool and later consumers use. persistent table zexp_claim tells a managed BO where to save. lock master and authorization master ( global ) are explained in their own sections below. Inside the braces, create, update and delete switch on the standard operations, and association _Items { create; } lets a consumer create items through the claim. The three field lines set characteristics; setStatusNew, validateAmount and submit only name logic that the pool implements. The item entity has no create of its own, because items are created through the claim, and it does not declare a lock master: it follows the claim with lock dependent by _Claim and authorization dependent by _Claim, and it declares the association back to its parent. The mapping for blocks pair each element of the view entity with its column. A mapping is needed wherever the names differ; the cheat sheet says that without it a syntax warning appears.

The example leaves out an ETag, draft handling and numbering on purpose; each of them has its own section below, and draft handling has its own page. The table of the claim also has client and audit columns that the view does not expose; this page does not rely on how the framework treats them, and a real definition has to follow the activation messages of the system.

Standard operations and field characteristics

The standard operations are create, update and delete. Each is written explicitly in the entity block. Reading is always possible and has no syntax. In a managed BO, the cheat sheet states, deleting a parent also deletes its composition children, which is why the item entity above needs no cleanup code. Additions can be attached to an operation in parentheses, for example update ( features : instance ); to make the operation depend on the state of the instance, internal to allow it only inside the business object, precheck for a check before the change is applied, and authorization : none to skip the authorization check of that operation.

Field characteristics describe what a consumer may do with a field.

Line Meaning

field ( readonly ) Status;

A consumer cannot create or change the value; only the business object itself can.

field ( readonly : update ) ClaimId;

The value can be given at creation and never changed afterwards. Key fields usually look like this.

field ( mandatory ) TotalAmount;

A value must be supplied before the instance is persisted.

field ( features : instance ) Status;

Whether the field is read-only or mandatory is decided at run time per instance, in a method of the pool (see Feature control).

field ( suppress ) Notes;

The field is removed from the derived types and the APIs of the BO.

The static characteristics are fixed for every instance. The cheat sheet notes that variants such as readonly : create apply to one operation only.

Determinations

A determination sets or corrects values automatically. In the example, a new claim should start in the status "new" without the user typing it, which is why the field Status is read-only for consumers. The BDEF names the determination and says when it runs.

  • on modify runs immediately after a change has entered the transactional buffer, so its result is available during the rest of the transaction.

  • on save runs during the save sequence, when the buffer is about to be written.

The braces list the triggers: operations such as create or delete, or field followed by names. A determination on modify with the trigger create runs after every create. The cheat sheet adds that for on save an update counts only together with a create, that several triggers need only one match, and that the order in which two determinations run is not defined; a determination must therefore not depend on another.

The code goes into a handler method of kind FOR DETERMINE. Handler methods are written in the next section; this listing is the implementation of setStatusNew.

METHOD setStatusNew.
  READ ENTITIES OF ZI_ExpClaim IN LOCAL MODE
    ENTITY Claim
      FIELDS ( Status )
      WITH CORRESPONDING #( keys )
    RESULT DATA(claims).

  DELETE claims WHERE Status IS NOT INITIAL.
  CHECK claims IS NOT INITIAL.

  MODIFY ENTITIES OF ZI_ExpClaim IN LOCAL MODE
    ENTITY Claim
      UPDATE FIELDS ( Status )
      WITH VALUE #( FOR claim IN claims
                    ( %tky = claim-%tky Status = 'N' ) )
    REPORTED DATA(update_reported).

  reported = CORRESPONDING #( DEEP update_reported ).
ENDMETHOD.

Source: abap-platform-rap100: method setStatusToOpen of the travel behavior pool. This listing requires an SAP system; not run here.

Reading it: the parameter keys holds the keys of the instances that triggered the determination. READ ENTITIES ... IN LOCAL MODE reads them from the transactional buffer; IN LOCAL MODE means the read does not go through authorization and feature checks, because this code is part of the business object itself. Instances that already have a status are removed, and the others are updated with MODIFY ENTITIES. %tky is the transactional key of an instance. The line reported = CORRESPONDING #( DEEP update_reported ) passes messages of the update on to the caller. The Entity Manipulation Language, in which READ ENTITIES and MODIFY ENTITIES are written, has a page of its own later in this section; this page uses it only as far as these listings need it.

Validations

A validation checks that the data is consistent. It always runs on save, and it has the same trigger list as a determination. If a validation fails, the save is rejected and the messages travel back to the consumer in the structures failed and reported. The cheat sheet stresses that the rejection is all or nothing: if one instance is wrong, the whole transactional buffer is rejected, including the instances that are fine.

Two output parameters of every handler method carry the outcome. failed lists the instances that failed, so the framework knows it must not save them. reported carries the messages for the user and, with %element, says which field a message belongs to. A validation therefore normally appends to both.

METHOD validateAmount.
  READ ENTITIES OF ZI_ExpClaim IN LOCAL MODE
    ENTITY Claim
      FIELDS ( TotalAmount )
      WITH CORRESPONDING #( keys )
    RESULT DATA(claims).

  LOOP AT claims INTO DATA(claim).
    IF claim-TotalAmount <= 0.
      APPEND VALUE #( %tky = claim-%tky ) TO failed-claim.

      APPEND VALUE #( %tky                 = claim-%tky
                      %msg                 = new_message_with_text(
                                               severity = if_abap_behv_message=>severity-error
                                               text     = 'The amount must be greater than zero.' )
                      %element-TotalAmount = if_abap_behv=>mk-on ) TO reported-claim.
    ENDIF.
  ENDLOOP.
ENDMETHOD.

Source: abap-cheat-sheets: validation val of the managed BO and abap-platform-rap100: validation validateCustomer. This listing requires an SAP system; not run here.

Reading it: the structures are named after the entity alias with a dash, so the claim’s tables are failed-claim and reported-claim. The first APPEND marks the instance as failed. The second sends a message; new_message_with_text builds a message from a severity and a text, as the cheat sheet’s sample does, and %element-TotalAmount = if_abap_behv=>mk-on says the message is about the field TotalAmount, so a user interface can mark it. The RAP100 sample uses a message class instead of a literal text, which is the way to go when the text must be translated; see Messages.

A difference worth knowing: a validation only reports, it never changes data. If code needs to change a value, it belongs in a determination.

Actions

An action is an operation that is neither create, update nor delete, such as "submit this claim". It is declared with the keyword action and a name; the code is a handler method of kind FOR MODIFY.

The cheat sheet lists the variants. Instance-bound is the default: the action works on one or more existing instances, which arrive in keys. A static action belongs to the entity and not to an instance. An internal action can only be called from inside the business object, which makes it a good place for reusable code that a determination calls. A factory action creates new instances, for example a copy of a claim, and cannot have an output parameter. An action can have an input parameter and a result; result [1] $self says that the action returns the changed instance itself. precheck adds a check before the action runs.

The action submit of the example moves a claim to the status "submitted".

METHOD submit.
  MODIFY ENTITIES OF ZI_ExpClaim IN LOCAL MODE
    ENTITY Claim
      UPDATE FIELDS ( Status )
      WITH VALUE #( FOR key IN keys ( %tky = key-%tky Status = 'S' ) )
    FAILED failed
    REPORTED reported.

  READ ENTITIES OF ZI_ExpClaim IN LOCAL MODE
    ENTITY Claim
      ALL FIELDS WITH CORRESPONDING #( keys )
    RESULT DATA(claims).

  result = VALUE #( FOR claim IN claims
                    ( %tky = claim-%tky %param = claim ) ).
ENDMETHOD.

Source: abap-platform-rap100: method rejectTravel, an instance-bound action with a result. This listing requires an SAP system; not run here.

Reading it: the first statement changes the status and passes failures and messages on directly to the method’s own failed and reported. The second reads the changed instances, and the last statement fills result, which has one line per instance, with the transactional key and the full instance in %param.

A related construct is the determine action, which lets a consumer ask for the on save determinations and validations to run before the final save. The cheat sheet states that determinations run before validations in it and that the addition always forces a determination to run. The draft action Prepare is built on this idea; drafts have their own page.

Numbering: where the key comes from

Every instance needs a key. Numbering describes who creates it. The cheat sheet distinguishes external numbering, where the consumer supplies the key and which is the default when nothing is written, from internal numbering, where the business object supplies it. Internal numbering can happen early or late.

Variant What it means

external (default)

The consumer sends the key with the create request. The expense claim above works this way: claim_id is a character field that someone fills.

field ( numbering : managed ) ClaimUuid;

Managed early numbering: the framework generates a UUID key. The cheat sheet says the key must be a 16-byte field.

early numbering with a method FOR NUMBERING

You write the code that assigns the key during the create, for example from a number range. The RAP100 sample defines a method earlynumbering_create FOR NUMBERING IMPORTING entities FOR CREATE Travel.

late numbering

The key is assigned shortly before the data is written, in the method adjust_numbers of the saver class. Until then the business logic works with a temporary key.

The claim table of the running example has a character key, so external numbering is the simplest choice; if the example should hand out claim numbers itself, the definition adds early numbering or late numbering and the matching method. Number ranges themselves are outside this page.

ETag, locking and authorization

Three header lines decide how concurrent users and different roles are handled. Each of them is a declaration; the framework does the work in a managed BO.

Optimistic concurrency with an ETag. etag master LocalLastChangedAt names a field of the root that changes whenever the instance changes. An OData client sends the value it last saw with every change request, and the request succeeds only if it still matches the stored value, so two people cannot silently overwrite each other. The cheat sheet says the field should be read-only and of a timestamp type, and that a managed BO can maintain it automatically with a timestamp annotation in the view. Child entities use etag dependent by _Assoc. A draft-enabled BO also needs a total etag field, a different one, which compares the draft with its active instance. The expense claim of this page has no timestamp field in its view, so its definition shows no ETag; adding one means adding such a field to the view and the table first.

Pessimistic concurrency with a lock. lock master on the root and lock dependent by _Claim on a child reuse the SAP lock concept that is described in Lock Objects and the SAP Lock Concept. In a managed BO the cheat sheet states that locking is automatic for updates, deletes, create by association and actions, and that action ( lock : none ) switches it off for one action. In an unmanaged BO the provider writes the lock code.

Authorization. A root entity declares authorization master with a scope in parentheses: global for checks that do not depend on one instance (may this user create claims at all), instance for checks that do (may this user change this claim), both separated by a comma, or none. The cheat sheet states that FOR GLOBAL AUTHORIZATION and FOR INSTANCE AUTHORIZATION handler methods implement these. Children declare authorization dependent by their parent. Read access is a different thing: it is governed by access control of the CDS data model, described on CDS Access Control. The example uses authorization master ( global ), so the pool needs the method shown in the next section.

Feature control

Feature control decides what the user may do with an entity, a field or an action right now. There are two kinds. Static control is written in the BDEF and is the same for every instance: readonly, mandatory and suppress above. Dynamic control depends on the state of an instance, and the cheat sheet describes it with features : instance on a field, an operation or an action, and a handler method of kind FOR INSTANCE FEATURES. features : global does not depend on the state of an instance; the cheat sheet does not show the method for it.

For the example, a claim that is already submitted must not be submitted again. The BDEF line becomes action ( features : instance ) submit result [1] $self;, and the pool gets this method.

METHOD get_instance_features.
  READ ENTITIES OF ZI_ExpClaim IN LOCAL MODE
    ENTITY Claim
      FIELDS ( Status )
      WITH CORRESPONDING #( keys )
    RESULT DATA(claims)
    FAILED failed.

  result = VALUE #( FOR claim IN claims
                    ( %tky           = claim-%tky
                      %action-submit = COND #( WHEN claim-Status = 'S'
                                               THEN if_abap_behv=>fc-o-disabled
                                               ELSE if_abap_behv=>fc-o-enabled ) ) ).
ENDMETHOD.

Source: abap-platform-rap100: method get_instance_features. This listing requires an SAP system; not run here.

A Fiori elements application reads the result and disables the "Submit" button for those claims. The sample uses %features-%update and %features-%delete in the same way for the standard operations.

The behavior pool and its handler class

The behavior pool is a global ABAP class that the BDEF names in its header. The cheat sheet describes it as a class pool, typically with the prefix BP, whose implementation lives in the local types include, shown as the Local Types tab in ADT. The global class itself is nearly empty. SAP’s samples declare it like this, with the addition FOR BEHAVIOR OF followed by the name of the root entity.

CLASS zbp_i_expclaim DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF ZI_ExpClaim.
ENDCLASS.

CLASS zbp_i_expclaim IMPLEMENTATION.
ENDCLASS.

Source: abap-cheat-sheets: behavior pool global class. This listing requires an SAP system; not run here.

The code is in local classes in the Local Types tab. A handler class is a local class that inherits from CL_ABAP_BEHAVIOR_HANDLER. By convention one handler class exists per entity of the BDEF, named lhc_ followed by the entity. Its method definitions have a fixed shape: a name, the kind in capital letters (FOR VALIDATE ON SAVE, FOR DETERMINE ON MODIFY, FOR MODIFY, FOR INSTANCE FEATURES, FOR GLOBAL AUTHORIZATION, FOR NUMBERING) and the importing parameter that says for which part of the BDEF the method is written. The importing parameter refers to the alias of the entity and the name in the BDEF, joined by a tilde.

CLASS lhc_claim DEFINITION INHERITING FROM cl_abap_behavior_handler.
  PRIVATE SECTION.
    METHODS get_global_authorizations FOR GLOBAL AUTHORIZATION
      IMPORTING REQUEST requested_authorizations FOR Claim RESULT result.

    METHODS setStatusNew FOR DETERMINE ON MODIFY
      IMPORTING keys FOR Claim~setStatusNew.

    METHODS validateAmount FOR VALIDATE ON SAVE
      IMPORTING keys FOR Claim~validateAmount.

    METHODS submit FOR MODIFY
      IMPORTING keys FOR ACTION Claim~submit RESULT result.

    METHODS get_instance_features FOR INSTANCE FEATURES
      IMPORTING keys REQUEST requested_features FOR Claim RESULT result.
ENDCLASS.

CLASS lhc_claim IMPLEMENTATION.
  METHOD get_global_authorizations.
  ENDMETHOD.

  " setStatusNew, validateAmount, submit and get_instance_features
  " are the methods of the previous sections.
ENDCLASS.

Source: abap-platform-rap100: local handler class lhc_travel and abap-cheat-sheets: local handler class lhc_calc. This listing requires an SAP system; not run here.

Reading it: the method get_global_authorizations is empty here, as it is in the RAP100 sample, which means the code grants everything; a real definition would check an authorization object there. The names Claim~setStatusNew match the alias and the names in the BDEF, so a typing mistake in either place is found when the class is activated. All methods get their data through keys and write their outcome into the implicit parameters failed, reported, mapped and result, never through global variables.

How the pieces fit in time is easier to see in a picture. The RAP framework calls the handler methods in two stages. While a user edits, the interaction phase collects changes in the transactional buffer, running determinations on modify, actions and feature checks. When the user saves, the save sequence runs the checks and then the saver.

flowchart TD C["Consumer: Fiori app or EML"] --> I["Interaction phase"] I --> H1["Handler: create, update, delete, action"] I --> H2["Handler: determination on modify, feature control, authorization"] H1 --> B[("Transactional buffer")] H2 --> B B --> S["Save sequence"] S --> V["Handler: determination on save, validation on save"] V --> OK{"Any instance failed?"} OK -- yes --> R["Save rejected: failed and reported go back to the consumer"] OK -- no --> SV["Saver class: adjust_numbers, save, cleanup"] SV --> D[("Database")]

Source: ABAP Cheat Sheet: RAP Behavior Definition Language. The diagram simplifies the framework’s order; the exact sequence of the save phases is described in the RAP development guide.

The saver class

A managed business object saves by itself, so most behavior pools have no saver. A saver class is needed when the save is changed. It is a local class that inherits from CL_ABAP_BEHAVIOR_SAVER and redefines methods. The cheat sheet names three situations.

  • with additional save in the header of a managed BDEF keeps the automatic save and adds code, for example for change documents, business events or logging. The saver redefines save_modified. The addition with full data makes the framework pass the full instance data to the method; without it only the keys arrive.

  • with unmanaged save replaces the automatic save; no persistent table may then be given. It also uses save_modified.

  • Late numbering needs the method adjust_numbers, which gives the instances their final key shortly before they are written.

In an unmanaged BO the saver redefines the methods finalize, check_before_save, save and cleanup instead; the sample class of the cheat sheet shows all of them. The method cleanup_finalize appears in several samples as an empty redefinition. A saver is a local class too, in the same Local Types tab.

CLASS lsc_zi_expclaim DEFINITION INHERITING FROM cl_abap_behavior_saver.
  PROTECTED SECTION.
    METHODS save_modified REDEFINITION.
    METHODS cleanup_finalize REDEFINITION.
ENDCLASS.

CLASS lsc_zi_expclaim IMPLEMENTATION.
  METHOD save_modified.
    " create-claim, update-claim and delete-claim hold the changes.
  ENDMETHOD.

  METHOD cleanup_finalize.
  ENDMETHOD.
ENDCLASS.

Source: abap-cheat-sheets: saver class lsc_zdemo_abap_rap_ro_m_as with save_modified and RAP: Unmanaged Save. This listing requires an SAP system; not run here and, because the example claim BDEF has no additional save, it would not compile against it as it stands.

The unmanaged and unmanaged-save implementation types, and how to wrap an existing function module or BAPI in them, are the subject of the next page of this section.

What older books show, and what has changed

  • Books and articles written before RAP describe the transactional model of the ABAP Programming Model for SAP Fiori with CDS views, BOPF and annotations; the behavior definition replaces that model, and handler methods replace BOPF determinations, validations and actions.

  • Older RAP tutorials may omit strict or use a lower version; the cheat sheet recommends strict ( 2 ).

  • Behavior definitions exist in Standard ABAP releases that contain RAP and in ABAP for Cloud Development. In ABAP Cloud only released APIs may be used inside handler methods; see ABAP Language Versions and Released APIs.

Summary

  • A behavior definition is a short text in the RAP Behavior Definition Language that lists what a business object can do; it contains no logic.

  • The header chooses managed or unmanaged, names the behavior pool and should switch on strict ( 2 ).

  • Determinations change data automatically, validations only check it and report through failed and reported, and actions are custom operations such as "submit".

  • Numbering, ETag, lock master and authorization master are declarations; in a managed BO the framework carries most of the work.

  • Static field characteristics are fixed, dynamic feature control needs a handler method that decides per instance.

  • The code is in the behavior pool: handler classes for operations and checks, saver classes only when saving is changed or keys are assigned late.