[[{“value”:”
Hi everyone,
I’m sharing a SAP RAP topic: Actions , Factory Function and Functions.
I kept this explanation small and simple on purpose. If we put all RAP topics into one app, it becomes hard to understand. Learning one topic at a time gives better clarity on how it works.Every business app needs more than create, update and delete. Users want to click Start, Approve or Close. They also want to ask questions like “how many days are left?”
In SAP RAP (ABAP RESTful Application Programming Model), you build both with actions and functions.
-
The memory trick
- Changes data → Action
- Only reads → Function
Makes a new copy: factory action
If it saves something, it’s an action. If it only answers a question, it’s a function.
Our example: a Task app
The app has tasks with a status: New → In Progress → Completed. We build one action (Start) and one function (Days Left).
Step 1: Create the database table
@EndUserText.label : ‘Task’
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table ztask {
key client : abap.clnt not null;
key task_id : sysuuid_x16 not null;
title : abap.char(60);
description : abap.char(255);
status : abap.char(1);
priority : abap.char(1);
due_date : abap.dats;
created_by : abp_creation_user;
created_at : abp_creation_tstmpl;
last_changed_by : abp_lastchange_user;
last_changed_at : abp_lastchange_tstmpl;
local_last_changed_at : abp_locinst_lastchange_tstmpl;
}
Step 2: Create the Root Interface View
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: ‘. Interface view (Root View)’
@Metadata.ignorePropagatedAnnotations: true
define root view entity ZI_Task
as select from ztask
{
key task_id as TaskId,
title as Title,
description as Description,
status as Status,
cast( case status
when ‘N’ then ‘New’
when ‘P’ then ‘In Progress’
when ‘C’ then ‘Completed’
when ‘X’ then ‘Cancelled’
else ‘Unknown’
end as abap.char(12) ) as StatusText,
case status
when ‘C’ then 3
when ‘P’ then 2
when ‘X’ then 1
else 0
end as StatusCriticality,
priority as Priority,
due_date as DueDate,
@Semantics.user.createdBy: true
created_by as CreatedBy,
@Semantics.systemDateTime.createdAt: true
created_at as CreatedAt,
@Semantics.user.lastChangedBy: true
last_changed_by as LastChangedBy,
@Semantics.systemDateTime.lastChangedAt: true
last_changed_at as LastChangedAt,
@Semantics.systemDateTime.localInstanceLastChangedAt: true
local_last_changed_at as LocalLastChangedAt
}
Step 3: Create the two abstract entities
@EndUserText.label: ‘Priority Input’
define abstract entity ZA_TaskPriority
{
@EndUserText.label: ‘Priority (L, M or H)’
Priority : abap.char(1);
}
@EndUserText.label: ‘Days Left Result’
define abstract entity ZA_TaskDays
{
DaysLeft : abap.int4;
}
Step 4: Create the Behavior Definition
managed implementation in class zbp_i_task unique;
strict ( 2 );
with draft;
define behavior for ZI_Task alias Task
persistent table ztask
draft table ztask_d
lock master total etag LastChangedAt
authorization master ( global )
etag master LocalLastChangedAt
{
create;
update;
delete;
draft action Edit;
draft action Activate;
draft action Discard;
draft action Resume;
draft determine action Prepare
{
validation validateTitle;
}
validation validateTitle on save { create; update; field Title; }
field ( numbering : managed, readonly ) TaskId;
field ( readonly ) Status, StatusText, StatusCriticality,
CreatedBy, CreatedAt, LastChangedBy,
LastChangedAt, LocalLastChangedAt;
field ( mandatory ) Title;
determination setInitialStatus on modify { create; }
// ACTION: changes data. Shows as a button.
// Example: user selects a New task and clicks Start -> status becomes In Progress.
// features : instance = button is enabled or disabled per task.
// result [1] $self = returns the updated task so the screen refreshes.
action ( features : instance ) startTask result [1] $self;
// ACTION: changes data.
// Example: click Complete on an In Progress task -> status becomes Completed.
action ( features : instance ) completeTask result [1] $self;
// ACTION: changes data.
// Example: click Cancel on a New or In Progress task -> status becomes Cancelled.
action ( features : instance ) cancelTask result [1] $self;
// ACTION WITH PARAMETER: opens a popup to ask the user for input.
// Example: click Set Priority, popup asks for L, M or H, then the priority is saved.
// parameter ZA_TaskPriority = the input structure shown in the popup.
action ( features : instance ) setPriority parameter ZA_TaskPriority result [1] $self;
// FACTORY ACTION: creates a NEW record from an existing one.
// Example: select “Fix login bug”, click Copy -> new task “Fix login bug (Copy)” is created.
factory action ( features : instance ) copyTask [1];
// FUNCTION: only reads and returns a value. Changes nothing. No button.
// Example: call getDaysLeft on a task due in 2 days -> returns { “DaysLeft”: 2 }.
// result [1] ZA_TaskDays = the structure that holds the answer.
function getDaysLeft result [1] ZA_TaskDays;
mapping for ztask
{
TaskId = task_id;
Title = title;
Description = description;
Status = status;
Priority = priority;
DueDate = due_date;
CreatedBy = created_by;
CreatedAt = created_at;
LastChangedBy = last_changed_by;
LastChangedAt = last_changed_at;
LocalLastChangedAt = local_last_changed_at;
}
}
Step 5: Create the draft table :
@EndUserText.label : ‘Draft table for entity ZI_TASK’
@AbapCatalog.enhancement.category : #EXTENSIBLE_ANY
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table ztask_d {
key mandt : mandt not null;
key taskid : sysuuid_x16 not null;
title : abap.char(60);
description : abap.char(255);
status : abap.char(1);
statustext : abap.char(12);
statuscriticality : abap.int1;
priority : abap.char(1);
duedate : abap.dats;
createdby : abp_creation_user;
createdat : abp_creation_tstmpl;
lastchangedby : abp_lastchange_user;
lastchangedat : abp_lastchange_tstmpl;
locallastchangedat : abp_locinst_lastchange_tstmpl;
“%admin” : include sych_bdl_draft_admin_inc;
}
Step 6: Create the behavior class
CLASS lhc_task DEFINITION INHERITING FROM cl_abap_behavior_handler.
PRIVATE SECTION.
METHODS startTask FOR MODIFY IMPORTING keys FOR ACTION Task~startTask RESULT result.
METHODS completeTask FOR MODIFY IMPORTING keys FOR ACTION Task~completeTask RESULT result.
METHODS cancelTask FOR MODIFY IMPORTING keys FOR ACTION Task~cancelTask RESULT result.
METHODS setPriority FOR MODIFY IMPORTING keys FOR ACTION Task~setPriority RESULT result.
METHODS copyTask FOR MODIFY IMPORTING keys FOR ACTION Task~copyTask.
METHODS getDaysLeft FOR READ IMPORTING keys FOR FUNCTION Task~getDaysLeft RESULT result.
ENDCLASS.
CLASS lhc_task IMPLEMENTATION.
” ACTION: Start (status = In Progress)
METHOD startTask.
MODIFY ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task UPDATE FIELDS ( Status )
WITH VALUE #( FOR key IN keys ( %tky = key-%tky Status = ‘P’ ) )
FAILED failed
REPORTED reported.
READ ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task ALL FIELDS
WITH CORRESPONDING #( keys )
RESULT DATA(lt_tasks).
result = VALUE #( FOR ls_task IN lt_tasks
( %tky = ls_task-%tky %param = ls_task ) ).
ENDMETHOD.
” ACTION: Complete (status = Completed)
METHOD completeTask.
MODIFY ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task UPDATE FIELDS ( Status )
WITH VALUE #( FOR key IN keys ( %tky = key-%tky Status = ‘C’ ) )
FAILED failed
REPORTED reported.
READ ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task ALL FIELDS
WITH CORRESPONDING #( keys )
RESULT DATA(lt_tasks).
result = VALUE #( FOR ls_task IN lt_tasks
( %tky = ls_task-%tky %param = ls_task ) ).
ENDMETHOD.
” ACTION: Cancel (status = Cancelled)
METHOD cancelTask.
MODIFY ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task UPDATE FIELDS ( Status )
WITH VALUE #( FOR key IN keys ( %tky = key-%tky Status = ‘X’ ) )
FAILED failed
REPORTED reported.
READ ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task ALL FIELDS
WITH CORRESPONDING #( keys )
RESULT DATA(lt_tasks).
result = VALUE #( FOR ls_task IN lt_tasks
( %tky = ls_task-%tky %param = ls_task ) ).
ENDMETHOD.
” ACTION WITH PARAMETER: Set Priority (popup input L, M or H)
METHOD setPriority.
DATA lt_valid TYPE TABLE FOR UPDATE zi_task\Task.
LOOP AT keys INTO DATA(key).
IF key-%param-Priority = ‘L’ OR key-%param-Priority = ‘M’ OR key-%param-Priority = ‘H’.
APPEND VALUE #( %tky = key-%tky Priority = key-%param-Priority ) TO lt_valid.
ELSE.
APPEND VALUE #( %tky = key-%tky ) TO failed-task.
APPEND VALUE #( %tky = key-%tky
%msg = new_message_with_text(
severity = if_abap_behv_message=>severity-error
text = ‘Priority must be L, M or H’ )
%action-setPriority = if_abap_behv=>mk-on ) TO reported-task.
ENDIF.
ENDLOOP.
IF lt_valid IS NOT INITIAL.
MODIFY ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task UPDATE FIELDS ( Priority )
WITH lt_valid.
ENDIF.
READ ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task ALL FIELDS
WITH CORRESPONDING #( keys )
RESULT DATA(lt_tasks).
result = VALUE #( FOR ls_task IN lt_tasks
( %tky = ls_task-%tky %param = ls_task ) ).
ENDMETHOD.
” FACTORY ACTION: Copy Task (creates a new task)
METHOD copyTask.
DATA lt_create TYPE TABLE FOR CREATE zi_task\Task.
READ ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task
FIELDS ( Title Description Priority DueDate )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_tasks).
LOOP AT lt_tasks INTO DATA(ls_task).
APPEND VALUE #( %cid = keys[ KEY entity %key = ls_task-%key ]-%cid
Title = |{ ls_task-Title } (Copy)|
Description = ls_task-Description
Priority = ls_task-Priority
DueDate = ls_task-DueDate ) TO lt_create.
ENDLOOP.
MODIFY ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task
CREATE FIELDS ( Title Description Priority DueDate )
WITH lt_create
MAPPED DATA(lt_mapped).
mapped-task = lt_mapped-task.
ENDMETHOD.
” FUNCTION: Days Left (only reads, changes nothing)
METHOD getDaysLeft.
READ ENTITIES OF zi_task IN LOCAL MODE
ENTITY Task FIELDS ( DueDate )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_tasks).
DATA(lv_today) = cl_abap_context_info=>get_system_date( ).
result = VALUE #( FOR ls_task IN lt_tasks
( %tky = ls_task-%tky
%param-DaysLeft = COND #( WHEN ls_task-DueDate IS INITIAL
THEN 0
ELSE ls_task-DueDate – lv_today ) ) ).
ENDMETHOD.
ENDCLASS.
Step 7: Create the Projection View
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: ‘Task Projection’
@Metadata.allowExtensions: true
define root view entity ZC_Task
provider contract transactional_query
as projection on ZI_Task
{
key TaskId,
Title,
Description,
Status,
StatusText,
StatusCriticality,
Priority,
DueDate,
CreatedBy,
CreatedAt,
LastChangedBy,
LastChangedAt,
LocalLastChangedAt
}
Step 8: Create the Projection Behavior Definition
projection;
strict ( 2 );
use draft; // NEW
define behavior for ZC_Task alias Task
{
use create;
use update;
use delete;
use action Edit; // NEW
use action Activate; // NEW
use action Discard; // NEW
use action Resume; // NEW
use action Prepare; // NEW
use action startTask;
use action completeTask;
use action cancelTask;
use action setPriority;
use action copyTask;
use function getDaysLeft;
}
Step 9: Create the Metadata Extension (UI annotations)
@Metadata.layer: #CUSTOMER
annotate entity ZC_Task with
{
@UI.facet: [
{ id: ‘General’, purpose: #STANDARD, type: #IDENTIFICATION_REFERENCE,
label: ‘Task Details’, position: 10 } ]
@UI.hidden: true
TaskId;
// ============ ACTIONS START HERE (on the Title field) ============
// Buttons in the LIST screen (above the table)
@UI.lineItem: [
{ position: 10, label: ‘Title’ },
// ACTION: user selects a row and clicks Start -> status becomes In Progress
{ type: #FOR_ACTION, dataAction: ‘startTask’, label: ‘Start’, position: 10 }, // ◄◄ ACTIONS
// ACTION: click Complete -> status becomes Completed
{ type: #FOR_ACTION, dataAction: ‘completeTask’, label: ‘Complete’, position: 20 }, // ◄◄ ACTIONS
// ACTION: click Cancel -> status becomes Cancelled
{ type: #FOR_ACTION, dataAction: ‘cancelTask’, label: ‘Cancel’, position: 30 }, // ◄◄ ACTIONS
// ACTION WITH PARAMETER: click Set Priority -> popup asks for L, M or H
{ type: #FOR_ACTION, dataAction: ‘setPriority’, label: ‘Set Priority’, position: 40 }, // ◄◄ ACTIONS
// FACTORY ACTION: click Copy -> a new task “… (Copy)” is created
{ type: #FOR_ACTION, dataAction: ‘copyTask’, label: ‘Copy’, position: 50 } ] // ◄◄ ACTIONS
// Same buttons in the DETAIL screen (object page, top right)
@UI.identification: [
{ position: 10, label: ‘Title’ },
{ type: #FOR_ACTION, dataAction: ‘startTask’, label: ‘Start’, position: 10 }, // ◄◄ ACTIONS
{ type: #FOR_ACTION, dataAction: ‘completeTask’, label: ‘Complete’, position: 20 }, // ◄◄ ACTIONS
{ type: #FOR_ACTION, dataAction: ‘cancelTask’, label: ‘Cancel’, position: 30 }, // ◄◄ ACTIONS
{ type: #FOR_ACTION, dataAction: ‘setPriority’, label: ‘Set Priority’, position: 40 }, // ◄◄ ACTIONS
{ type: #FOR_ACTION, dataAction: ‘copyTask’, label: ‘Copy’, position: 50 } ] // ◄◄ ACTIONS
// ============ ACTIONS END HERE ============
@UI.selectionField: [{ position: 10 }]
Title;
@UI.identification: [{ position: 20 }]
Description;
@UI.hidden: true
Status;
@UI.hidden: true
StatusCriticality;
@UI.lineItem: [{ position: 20, label: ‘Status’, criticality: ‘StatusCriticality’ }]
@UI.identification: [{ position: 30, label: ‘Status’, criticality: ‘StatusCriticality’ }]
@UI.selectionField: [{ position: 20 }]
StatusText;
@UI.lineItem: [{ position: 30, label: ‘Priority’ }]
@UI.identification: [{ position: 40, label: ‘Priority’ }]
@UI.selectionField: [{ position: 30 }]
Priority;
@UI.lineItem: [{ position: 40, label: ‘Due Date’ }]
@UI.identification: [{ position: 50, label: ‘Due Date’ }]
DueDate;
@UI.hidden: true
CreatedBy;
@UI.hidden: true
CreatedAt;
@UI.hidden: true
LastChangedBy;
@UI.hidden: true
LastChangedAt;
@UI.hidden: true
LocalLastChangedAt;
}
Step 10: Create the Service Definition
@EndUserText.label: ‘Task Service’
define service ZUI_TASK {
expose ZC_Task as Task;
}
Step 11: Create and publish the Service Binding
WHY THIS BLOG
Business apps need more than create, update and delete. Users click Start, Complete or Copy. They also ask simple questions like “how many days are left?”
In SAP RAP (ABAP RESTful Application Programming Model), actions and functions handle all of this. To learn each one clearly, I built a small Task app and kept every topic separate.
WHAT WE COVERED
- Action
Why: to change data with a business step.
Example: Start, Complete and Cancel change the task status. - Action with parameter
Why: to ask the user for input first.
Example: Set Priority opens a popup where the user enters L, M or H. - Factory action
Why: to create a new record from an existing one.
Example: Copy creates a new task named “… (Copy)”. - Function
Why: to read and return a value without changing anything.
Example: getDaysLeft returns DaysLeft = 2.
MEMORY TRICK
Changes data: action
Only reads: function
Makes a new copy: factory action
Needs input: parameter
HOW IT WORKS, IN THREE STEPS
Step 1: Declare it in the behavior definition.
action startTask result [1] $self;
Step 2: Write the logic in the behavior class.
Actions use MODIFY ENTITIES because they change data. Functions use only READ ENTITIES because they change nothing.
Step 3: Show the button with a UI annotation.
@UI.lineItem: [{ type: #FOR_ACTION, dataAction: ‘startTask’, label: ‘Start’ }]
Do not forget to add “use action” and “use function” in the projection behavior definition. Without them, the button does not appear.
HOW WE TESTED
Actions: we clicked the buttons in the Fiori app and checked the status change.
Function: it has no button, so we called it with a URL in the browser.
URI: /sap/opu/odata4/sap/zui_task_o4/srvd/sap/zui_task/0001/Task(TaskId=3b6c8568-d8cf-1fe1-b8ff-8c3f34a619fa,IsActiveEntity=true)/com.sap.gateway.srvd.zui_task.v0001.getDaysLeft()
PROBLEMS WE HIT AND FIXED
- No Create or Edit button: adding draft fixed it.
- Empty title could be saved: a validation on save fixed it.
- INT1 cast error: removing the extra cast fixed it.
- Function URL error: the placeholder <your-guid> must be replaced with a real task ID.
KEY TAKEAWAY
Actions do the work and functions answer questions. Keeping each topic in its own small example makes RAP much easier to understand.
NEXT BLOG
Validations, Determinations and Feature Control: the rules that keep the data correct.
“}]]
Read More Technology Blog Posts by Members articles
#abap