AC400 - Programming in Financials
December 27, 2016 | Author: sathishsapfi85 | Category: N/A
Short Description
AC400 - Programming in Financials...
Description
AC400 Programming in Financials
AC400
Programming in Financials
THE BEST-RUN BUSINESSES RUN SAP SAP AG 2006 © SAP AG©2006
mySAP ERP 2005 Financial Analytics 2006/Q2 Material number: 5008 0584
Copyright
Copyright 2006 SAP AG. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice.
© SAP AG 2006
Die von SAP AG oder deren Vertriebsfirmen angebotenen Softwareprodukte können Softwarekomponenten auch anderer Softwarehersteller enthalten. Microsoft, Windows, Outlook, und PowerPoint sind eingetragene Marken der Microsoft Corporation. IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, und Informix sind Marken oder eingetragene Marken der IBM Corporation in den USA und/oder anderen Ländern. Oracle ist eine eingetragene Marke der Oracle Corporation. UNIX, X/Open, OSF/1, und Motif sind eingetragene Marken der Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, und MultiWin sind Marken oder eingetragene Marken von Citrix Systems, Inc. HTML, XML, XHTML und W3C sind Marken oder eingetragene Marken des W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Java ist eine eingetragene Marke von Sun Microsystems, Inc. JavaScript ist eine eingetragene Marke der Sun Microsystems, Inc., verwendet unter der Lizenz der von Netscape entwickelten und implementierten Technologie. MaxDB ist eine Marke von MySQL AB, Schweden.
SAP, R/3, mySAP, mySAP.com, xApps, xApp und weitere im Text erwähnte SAP-Produkte und -Dienstleistungen sowie die entsprechenden Logos sind Marken oder eingetragene Marken der SAP AG in Deutschland und anderen Ländern weltweit. Alle anderen Namen von Produkten und Dienstleistungen sind Marken der jeweiligen Firmen. Die Angaben im Text sind unverbindlich und dienen lediglich zu Informationszwecken. Produkte können länderspezifische Unterschiede aufweisen. In dieser Publikation enthaltene Informationen können ohne vorherige Ankündigung geändert werden. Die vorliegenden Angaben werden von SAP AG und ihren Konzernunternehmen („SAP-Konzern“) bereitgestellt und dienen ausschließlich Informationszwecken. Der SAPKonzern übernimmt keinerlei Haftung oder Garantie für Fehler oder Unvollständigkeiten in dieser Publikation. Der SAP-Konzern steht lediglich für Produkte und Dienstleistungen nach der Maßgabe ein, die in der Vereinbarung über die jeweiligen Produkte und Dienstleistungen ausdrücklich geregelt ist. Aus den in dieser Publikation enthaltenen Informationen ergibt sich keine weiterführende Haftung.
Course Prerequisites
Required: z Basic knowledge of programming
Recommended z AC010 – Business Processes in Financial Accounting z
AC040 – Business Processes in Management Accounting (Controlling)
z BC400 – ABAP Workbench Basics
© SAP AG 2006
Note to participants y The course materials are not suitable for self-study. The explanations provided by your course instructor are essential to understanding the materials. The participants' handbook contains space for you to write down notes about this additional material.
Target Group
Participant z Members of financial accounting departments or system administrators who deal with tasks that cover a range of subjects z Consultants
Duration z Three days
© SAP AG 2006
Course Overview
Contents: z Course Goals z Course Objectives z Course Contents z Overview Diagram z Overview of the Exercises
© SAP AG 2006
© SAP AG
AC400
1-7
Course Goals
This course will prepare you to: z Perform technical programming-related tasks
for the Accounting departments, above all to z
analyze existing programs
z create your own programs and reports
© SAP AG 2006
© SAP AG
AC400
1-8
Course Objectives
At the end of this course, you will be able to: z Use the development tools of the ABAP Workbench z Analyze and debug Accounting programs z Create function modules z Enable database access z Implement your own ALV reports z Define authorization checks z Develop and incorporate extractors
© SAP AG 2006
© SAP AG
AC400
1-9
Course Content
Preface Unit 1
Overview
Unit 5
Customer Enhancements
Unit 2
The ABAP Workbench
Unit 6
Extraction
Unit 3
First Attempts at Programming
Unit 7
Template Allocation
Unit 4
Dialogs and ALV Reports
Appendix Self-Study Exercises
© SAP AG 2006
© SAP AG
AC400
1-10
Overview of the Exercises • Exercises for the Units • Unit 3: First Attempts at Programming • Unit 4: Dialogs • Unit 5: Customer Enhancements • Unit 6: Extractors • Unit 7: Template Allocation
• Optional self-study exercises • Optional exercise F1: Customer address data • Optional exercise F2: Open and close FI periods • Optional exercise F3: Master data group report
© SAP AG 2006
© SAP AG
AC400
1-11
Overview Diagram: The ABAP Workbench
The TheABAP ABAPWorkbench Workbench
Customer CustomerEnhancements Enhancements
First FirstAttempts Attemptsat atProgramming Programming
Extraction Extraction
Dialogs Dialogsand andALV ALVReports Reports
Template TemplateAllocation Allocation
© SAP AG 2006
© SAP AG
AC400
1-12
Overview Diagram: The ABAP Workbench
The TheABAP ABAPWorkbench Workbench
Customer CustomerEnhancements Enhancements
First FirstAttempts Attemptsat atProgramming Programming
Extraction Extraction
Dialogs Dialogsand andALV ALVReports Reports
Template TemplateAllocation Allocation
© SAP AG 2006
© SAP AG
AC400
2-13
The ABAP Workbench – Overview
Contents: z The unit provides an overview of the structure of the ABAP Workbench and the objects in the repository. It presents the most important commands in the ABAP programming language.
© SAP AG 2006
© SAP AG
AC400
2-14
The ABAP Workbench: Objectives
At the conclusion of this unit, you will be able to: z Describe the structure of the repository z Name and use the search tools in the repository z Use the Object Navigator for your development
work
© SAP AG 2006
© SAP AG
AC400
2-15
The Repository – Embedding
Presentation server layer
Application server layer
ABAP Program
Client-independent Database
Repository
Client-dependent Application tables Customizing tables
© SAP AG 2006
The database contains application and Customizing tables that are usually client-dependent. The database also contains the R/3 Repository. Part of the R/3 Repository is made up of the ABAP Dictionary. The R/3 Repository thus contains all the development objects, such as programs, database table definitions or central data type definitions. Development objects are therefore also known as repository objects. Repository objects are always client-independent. They can therefore be used and changed in all clients.
© SAP AG
AC400
2-16
Structure of the Repository
Repository objects Programs Table definitions
Repository FI
Function modules
. . .
CO Package MM_C
MM MM SD
Package MM_B Package MM_A
HR
MM Customer FI
Customer MM
Customer CO
© SAP AG 2006
The R/3 Repository is subdivided into application components. Within an application component there are several packages to enable more accurate, logical subdivision.. Repository objects are often comprised of subobjects that are themselves repository objects. When you create a repository object, it must be assigned to a package.
© SAP AG
AC400
2-17
SAP Application Hierarchy SAP + + +
CA AC FI
Cross-Application Components Accounting - General Financial Accounting ...
FBAS
Financial Accounting "Basis"
...
+ + + + +
TR CO ...
FI-GL General Ledger Accounting FI-LC Consolidation ... Treasury Controlling
+
Information System
Application component Package Selected subtree © SAP AG 2006
The structure of the application components is represented in the application hierarchy. You access the application hierarchy from the Easy Access menu by choosing Tools ABAP Workbench Overview Application Hierarchy. The application components are represented in a tree structure in the application hierarchy. When you open up the components you can see the packages assigned to them. You can select subtrees and navigate from the application hierarchy to the Repository Information System. The system then collects all the packages for the selected subtrees and transfers them to the Information System.
© SAP AG
AC400
2-18
The Repository Information System Repository Information System Business Engineering ABAP Dictionary Basic Objects Database Tables Views Data Elements Structures Table Types ...
Other Objects Fields Programming Function Library Program Library Programming Environment Program Subobjects ABAP Objects Class Library Class Subobjects Interface Subobjects Environment
Doubleclick
Selection Screen for Delimiting the Search
© SAP AG 2006
You can search specifically for repository objects using the Repository Information System. Suitable search criteria are available for the different repository objects. The objects you find with the Repository Information System depend on how you navigate there: y In the application hierarchy, if you click on the Information System pushbutton (double-click on the selected application component(s) or package), only those repository objects that are relevant are "filtered out". y If, from the Easy Access menu, you choose Tools ABAP Workbench Overview Information System, all the repository objects in the system can be searched from here.
© SAP AG
AC400
2-19
ABAP Workbench Tools
Debugger
Screen Painter Menu Painter FI
HR
MM
SD
WM
Object Navigator
MM Customer
ABAP Editor
ABAP Dictionary Function Builder Class Builder
© SAP AG 2006
The ABAP Workbench comprises different tools for processing repository objects. The tools cover the whole software development cycle. The most important tools for creating and processing repository objects are: the ABAP Editor for editing source texts, the ABAP Dictionary for editing database table definitions, central datatypes and more, the Screen Painter for creating screens (screen layouts including user dialog functions), the Menu Painter for creating user interfaces (menu bar, toolbar, application toolbar, function key setting), the Function Builder for processing function modules, the Class Builder for processing central classes. There are three possible ways of calling the respective tool: y Call the object directly from the Easy Access menu. y Work with the Object Navigator: This provides you with all the objects in a package or program in the form of a tree structure. By double-clicking on the object you open the respective tool. y Double-click to navigate from one tool to another and back again.
© SAP AG
AC400
2-20
Screen Layout in the Object Navigator Full screen on/off
Tool area Navigation area
Right mouse button Right mouse button
Context menu ...
Context menu ...
Adjustable border
© SAP AG 2006
The Object Navigator screen is divided into two areas: y The navigation area to display an object list as a hierarchy tree, y The tool area, in which a package can be displayed or processed using the appropriate tool. You can hide or display the hierarchy area. You can choose functions from the context menu in both windows. In each case, you can only choose those functions intended for displaying or processing the object on which the cursor is positioned. You open the context menu with the right mouse button (if you have set the mouse for left-handed users, this would then be the left mouse button).
© SAP AG
AC400
2-21
The Navigation Area
Package BC400 Previous/next object list
Higher-level object list
Application hierarchy Package Program Function group Class/Interface ... Inactive objects Local objects
Update object list BC400 Organize Favorites DDIC objects Programs SAPBC400WBD_GETTING_STA SAPBC400WBT_GETTING_STA Function groups BC400 Navigation by Classes double-click CL_BC400 © SAP AG 2006
Repository objects are organized hierarchically: y An application component can contain various development classes. y A development class in turn can contain different repository objects: Programs, function groups, ABAP Dictionary objects and so on. y A repository object can comprise various subobjects: - For a program: Global data, types, events, subroutines and so on - For a function group: Global data, function modules and so on You can enter the type of object list and the object names in the upper part of the navigation area. The object list is then displayed in the navigation area. Double-click on an object in an object list to display the subobjects. Double-click on an object that does not belong to an object list to display the object using the appropriate tool in the tool area. You can navigate historically or hierarchically between the object lists. You can add the object lists that you process frequently to your Favorites.
© SAP AG
AC400
2-22
Navigation in the Tool Area Previous/next object
Functions of the current tool
Show navigation window
Navigation history
Navigation stack
© SAP AG 2006
You can show a window for historical navigation in the tool area. A list is displayed there with the objects that you have displayed in the tool area since you started the Object Navigator. The object that is currently displayed in the tool area is highlighted in color in the list.
© SAP AG
AC400
2-23
Modifying the Tool Area Display object list
Double-click or context menu function
© SAP AG 2006
Navigation in the navigation and tool area is decoupled. This allows the navigation area to be used very flexibly. Both areas can be made to match one another if required: y You can access the object display in the tool area by double-clicking the object or from the navigation area. The system then automatically chooses the relevant tool for editing the object you have selected. y You can call the object list display that belongs to an object that you are currently processing in the tool area by choosing Display Object List. You can use the context menu for an object type to create objects for an object list. If no entry for the required object type exists in the object list, you can create any objects you like using Edit Object or Other Object.
© SAP AG
AC400
2-24
Creating Packages
Comply with customer namespace !
Create package
Package
ZBC400_00
Short description
Exercises group 00
Application component
CA
Software component
HOME
Transport layer
ZDEV
Package type
No main package
To which application component does the package belong ? Where should the development objects be transported ?
© SAP AG 2006
You can create a package from the Object Navigator: y With Release 4.6 c you can select the Development Class object type and enter the name of the package in the input field. Make sure you comply with the customer namespace in the process. If the package does not exist, the dialog box branches to the screen where you can create a package. y With Release 4.6 a/b you have to select Edit Object or Other Object in the initial screen. Enter the name of the package on the More tab strip in the Development Class entry field. Check the presettings for the following attributes: y Transport layer: If you carry out your own development, a transport layer has to be set up for customer development. y Person responsible: The person responsible carries full responsibility for the objects in this package. Your user name is entered as the default value. y Software component: You usually enter customer developments under HOME. You will find more detailed information in the F1 help for the field. y Application component: Determine where the package should appear in the application hierarchy.
© SAP AG
AC400
2-25
Assignment to Change Requests Enter transportable Workbench request Package
ZBC400_00
Request
IT3K90051
Workbench request
Participants' exercises for course BC400
...
Own requests Enter transportable Workbench request Change requests involving BC400-00 Changeable Transportable
Double-click on order number
IT3K900051 CARSON IT3K900052 CARSON IT3K900053 BC400-00 IT3K900054 BC400-01 © SAP AG 2006
The creation and change of each repository object must be assigned to the change request for the respective project. For this course, the instructor has created a change request for the project Participants' exercises for course BC400. Each group has a task within this change request. You can display all the change requests in which you have tasks using the Own Requests pushbutton. Simply assign all repository objects (packages, programs and so on) to this change request. The system assigns your task more precisely.
© SAP AG
AC400
2-26
ABAP Syntax I General structure of an ABAP statement XXX ABAP keyword
YYY Additions and operands (keyword-specific)
Period to close the statement
Sample Program ... DATA wa_scarr TYPE scarr . SELECT * FROM scarr INTO wa_scarr . NEW-LINE. WRITE wa_scarr-carrid . WRITE wa_scarr-carrname . WRITE wa_scarr-url . ENDSELECT. © SAP AG 2006
An ABAP program comprises individual statements. Each statement must be concluded with a period. The first word in a statement is a keyword. Words are separated by at least one blank character. Statements can be indented. Statements can extend over several lines. One line can comprise several statements. The ABAP runtime system does not distinguish between upper and lower case keywords, additions and operands. To make things more transparent, all keywords and their additions are written in upper case and all operands in lower case in this course. You can use the Pretty Printer for indentations and converting upper and lower case: Utilities Settings ABAP Editor Pretty Printer.
© SAP AG
AC400
2-27
ABAP Syntax II
* comments ... * comments ... * comments ...
Comments (complete lines)
DATA wa_scarr TYPE scarr.
" comments ...
SELECT * FROM scarr INTO wa_scarr.
" comments ... " comments ...
Command-related comments
NEW-LINE. WRITE : wa_scarr-carrid , wa_scarr-carrname ,
Chained statement
wa_scarr-url . ENDSELECT.
© SAP AG 2006
You introduce comment lines with an asterisk *. The corresponding commented line is ignored by the ABAP runtime system. If you want to add a comment to the remainder of a line that has already been started, you have to use quotation marks ". You can group successive statements that begin in the same way in a chained statement: y Close the identical start of the statement with a colon. y Separate the chained parts of the statement that follow the colon with commas. y Spaces and line breaks can come before and after the separators (colon, comma, period). y Note that the individual components of a chained statement represent separate instructions for the ABAP runtime system, as before.
© SAP AG
AC400
2-28
SY-SUBRC as Return Code
REPORT ... PARAMETERS pa_carr TYPE scarr-carrid. DATA wa_scarr TYPE scarr.
SELECT SINGLE * FROM scarr INTO wa_scarr WHERE carrid = pa_carr. IF sy-subrc
EQ 0.
NEW-LINE. WRITE: wa_scarr-carrid, wa_scarr-carrname, wa_scarr-url. ELSE. WRITE 'Sorry, no data found!'. ENDIF.
© SAP AG 2006
For many ABAP statements, the ABAP runtime system writes a numeric value to the system field sy-subrc to indicate how successful the execution of this statement was. The value zero always indicates that the statement was executed successfully. You can find out whether and how this return value is set in each individual case in the documentation for the respective statement.
© SAP AG
AC400
2-29
Creating a Program Create program Program
ZBC400_00_GS Comply with customer namespace !
With TOP include
ABAP program properties ... Header
My 1st ABAP program
... Attributes Type
Executable program
Status
Test program
Application ...
© SAP AG 2006
Fixed point arithmetic
Save
The following options are available for creating a program from the Object Navigator: y In the navigation area, choose the Program object type and enter a name. Make sure you comply with the customer namespace in the process. If the program does not exist, the system takes you through a dialog sequence to create the program. (This procedure is only possible as of Release 4.6 c.) y Display the package for which the program is to be created. Use the context menu for the package or the Programs node to trigger the dialog sequence for creating a program. y Choose Other Object or Edit Object. Choose the Program Objects tab page and enter the name. Now choose Create. For this course, remove the With TOP Include indicator (otherwise, your source text would be distributed to several programs). Change the title to a self-explanatory short text. Select the appropriate program status: Test Program for all ABAP training courses.
© SAP AG
AC400
2-30
Documentation of ABAP Terms
i START-OF-SELECTION. SELECT SINGLE * FROM scarr INTO wa_scarr WHERE carrid = pa_car. ABAP overview IF sy-subrc = 0. WRITE ABAP term MOVE-CORRESPONDING wa_scarr What's new in ABAP TO sbc400_carrier. ABAP glossary CALL SCREEN 100. ABAP index MOVE-CORRESPONDING sbc400_carrier ... Help
TO wa_scarr.
F1 WRITE: WRITE
Keyword documentation
wa_scarr-carrid, wa_scarr-carrname, wa_scarr-currcode.
ENDIF. © SAP AG 2006
There are a number of navigation options for displaying keyword documentation for an ABAP statement: y The F1-button takes you directly to the documentation for the statement on which the cursor is currently positioned. y The Information button takes you to a display frame for different views of the keyword documentation. Under Help SAP Library Basis you will also find comprehensive documentation for all tools and topics relating to the ABAP Workbench.
© SAP AG
AC400
2-31
Inactive and Active Development Objects Saved programs
Activated programs
(for further development/testing)
(for using/transporting across all systems)
Activate Program A ( inactive version )
Program A ( active version )
Program B ( active version )
Program C ( active version )
Program C ( inactive version )
© SAP AG 2006
If you create or change a development object and then save it, an inactive version is always stored in the R/3-Repository first. A repository object has to exist as an active version before it becomes available across the system, however. This active version of your program is then drawn when a user wants to execute your program, for example. If your program exists in both versions, you can switch between the two versions in display mode. If you activate a program, a list of all the inactive objects that you have processed is displayed first in the worklist. When you activate a program, the following occurs: It is saved, which means that the inactive version is either stored or overwritten. The program syntax is checked. The active version is stored or overwritten.
© SAP AG
AC400
2-32
Generating Runtime Objects Saved programs
Activated programs
(for further development/testing)
(for using/transporting across all systems)
Program A ( active version )
Program B ( active version )
Program C ( active version )
Program C ( inactive version )
When executed, the runtime object generated during activation is used.
When executed (from the editor), the relevant runtime object is always generated again. © SAP AG 2006
When a development object is generated, a separate runtime object (LOAD) is created (compiled) and stored in the R/3 Repository too. This generated object is the one that is executed (interpreted). The object is generated automatically, but can also be generated explicitly. If, for example, a user wants to execute your program and no generated version exists at that time, the active version is taken to be generated. You yourself can choose which version you want to execute: If you start your program from the navigation area, the active version is taken for generation. If you test an executable program from the editor, however, the inactive version is taken. A temporary generated version is created. This makes it possible for you to further develop the program without changing the current system status. The changes to the development object can only be "seen" across the system when the object is reactivated. A local, separate view is created on the R/3 Repository with the inactive versions, which creates the basis for a "local runtime system".
© SAP AG
AC400
2-33
Creating a Transaction Code System
Help
Create report transaction ZBC400_00_GS
Transaction code Package
Z00GS ZBC400_00
Transaction text
...
Program
ZBC400_00_GS
... Classification Professional User Transaction Easy Web Transaction ... ...
© SAP AG 2006
If you want to add a program to the menu for a role or to the Favorites in your SAP Easy Access menu, you have to assign it to a transaction code. To do this, display the object list for your program in the Object Navigator. In the context menu for the program name, choose Create Transaction. Make sure you comply with the customer namespace in the process. Choose Program and Selection Screen (Report Transaction), if the program is an Executable Program. Enter the name of the program on the subsequent screen. Choose Professional User Transaction. Save your transaction code. Since a transaction code is a repository object, you have to assign it to a package and a change request in the subsequent screens.
© SAP AG
AC400
2-34
Inserting Transaction Codes in Favorites System
Help
SAP Easy Access Favorites Object Navigator SAP Menu
... Insert Transaction ...
Enter a transaction manually Transaction code
Z00GS
© SAP AG 2006
To enter a transaction code in the Favorites for your role menu, proceed as follows: y Navigate to the initial screen (SAP Easy Access menu). y In the Favorites context menu, choose Insert Transaction. y Enter the transaction code in the dialog box. The short text for the transaction then appears under the Favorites node. You can use the context menu for this new node to start the relevant program.
© SAP AG
AC400
2-35
Data Types
ABAP program . . . Definition of input/output fields
. . . Definition of data objects
. . . Typing Typing interface interface parameters
Subroutine Interface ...
le du o m n ce io fa ct er t n In Fu
Method Interface ...
© SAP AG 2006
The type of a data object determines its technical properties. The type of an interface parameter determines the type of values (actual parameters) that are transferred when a modularization unit is called. The type of an input/output field can also provide information in addition to the technical properties. For example, it can be used to control the input help.
© SAP AG
AC400
2-36
Local vs. Global Data Types Data types local to programs
Global data types
(technical properties only)
(technical and semantic properties)
ABAP program ABAP Dictionary
le du mo e n c io fa ct er t n n I Fu
Subroutine Interface ...
Method Interface ...
© SAP AG 2006
Data types can be defined both within an ABAP program (local, keyword TYPES) or in the ABAP Dictionary (global). There are many advantages in using global data types: Global types are managed centrally and can be used in all repository objects. This improves the consistency of the system and reduces the effort required for maintenance considerably. An environment analysis is available in the ABAP Dictionary (where-used-list). The content of global data types can be coupled to business variables, and can thus contain semantic as well as technical information. This can be used to create screens too. When searching for global types, you should therefore make sure that you take semantic properties into account as well as technical ones. Only this way can you fully exploit the advantages of ease of maintenance and robustness of your program.
© SAP AG
AC400
2-37
Elementary Data Types Global types
ABAP Dictionary
ABAP program Declaration of local types TYPES type_name TYPE ...
Implemented ABAP types (Standard types in ABAP)
DATA myvar TYPE type_name .
DATA myvar2 LIKE myvar.
D
P
T
N
I
C
F
X
STRING XSTRING © SAP AG 2006
You can use an implemented ABAP type, a local or a global type to type data objects. The following implemented ABAP types are complete: y d Date (Date, format: YYYYMMDD) y t
Time (Time, format: HHMMSS)
y i
Integer (Integer)
y f
Floating point number (Floating point)
y string
String (String, variable length)
y xstring Byte sequence (HeXadecimal string, variable length) The length must be specified for the following implemented types: y c Character (Character) y n
Numerical character (Numerical character)
y x
Byte (HeXadecimal)
y p Packed number (Packed number = binary coded decimal number). You have to specify the number of decimal places here too. You will find further information about installed ABAP types in the keyword documentation for TYPES or DATA.
© SAP AG
AC400
2-38
You can use LIKE to refer to the type of a data object that has already been defined.
© SAP AG
AC400
2-39
Declaration of Variables ... TYPES t_percentage(3) TYPE p DECIMALS 2. DATA: percentage1
TYPE t_percentage,
percentage2
TYPE t_percentage,
number1
TYPE i VALUE 17,
number2
LIKE number1,
city(15)
TYPE c,
carrid
TYPE s_carr_id,
connid
TYPE sbc400focc-connid.
S_CARR_ID (Data element)
SBC400FOCC (Structure)
percentage1
00000+
percentage2
00000+
number1
17
number2
0
city carrid connid
0000
© SAP AG 2006
The predefined ABAP types d, t, i, f, string and xstring are complete. This means that you can define an elementary data object for these types in the following way: DATA do_name TYPE predefined_ABAP_type. y With the predefined ABAP types c, n, p, and x you still have to determine the length. This means that you should first define an elementary type: - TYPES type_name(length) TYPE predifined_ABAP_type. - You then use this to define the data object: - DATA do_name TYPE type_name. - For type p, you can also determine the number of decimal places using the DECIMALS addition. With the VALUE addition you can preassign a value for an elementary data object. For compatibility reasons, it is still possible to construct data objects in the DATA statement without defining the type locally to a program using a TYPES statement. For ABAP types that have not been fully implemented, the missing type information is supplemented by standard values. If the type is not specified at all, an elementary type cdata object of length one is defined. You will find the standard lengths as well as further information in the keyword documentation for TYPES or DATA.
© SAP AG
AC400
2-40
When you use global types, the syntax is the same as for user-defined types: DATA do_name TYPE global_type_name.
© SAP AG
AC400
2-41
Fixed Data Objects Fixed data objects without identifier Literals: Numeric literals
Text literals
positive integer :
123
Character string :
negative integer :
-123
Decimal numbers :
'Hallo' '123.45'
Floating point numbers : '123.45E01'
Fixed data objects with identifier Constants : CONSTANTS myconst TYPE type_name VALUE { literal | IS INITIAL } .
© SAP AG 2006
You already assign a value to fixed data objects in the source text. This value can therefore no longer be changed at runtime. With literals you can transfer fixed values to ABAP statements. There are numeric literals and text literals. The latter are enclosed by quotation marks. y You can represent integers (with a minus sign for negative numbers) as numeric literals. They are then mapped to data type i if they lie within the value range of 4-byte integers. Larger numeric literals are mapped to data type p. y You must represent all other literals (character strings, floating point numbers, ...) as text literals. They are mapped to data type c and converted later, if necessary. If a text literal contains an inverted comma, you have to enter this twice. Constants are defined with the CONSTANTS statement. Typing takes place in the same way as the definition of elementary data objects with DATA. The VALUE addition is mandatory for constants. This determines the value for the constants. Recommendation: Avoid using literals for statements whenever you can. Create constants instead. This makes your program much easier to maintain.
© SAP AG
AC400
2-42
Value Assignments ABAP runtime system
ABAP program Data declarations
CONSTANTS c_qf TYPE s_carr_id VALUE 'QF'. DATA: carrid1 TYPE s_carr_id, carrid2 TYPE s_carr_id VALUE 'LH', counter TYPE i. Program start
c_qf
QF
carrid1
carrid2
counter
LH
0
MOVE c_qf TO carrid1.
QF
LH
0
carrid2 = carrid1.
QF
QF
0
ADD 1 TO counter.
QF
QF
1
CLEAR: carrid1, carrid2, counter.
0
© SAP AG 2006
If a program is started, the program context is loaded to a storage area on the application server and storage space is made available for all the data objects. Each elementary data object is given the initial value assigned to its type, unless it has been allocated a different value by means of the VALUE addition. You can use the MOVE statement to copy the contents of data objects. Two syntax variants are available for this: y MOVE source TO target. y target = source. If both data objects belong to different types, the type is converted automatically if a conversion rule exists. You will find detailed information about copying transactions and conversion rules in the keyword documentation for the MOVE statement. The CLEAR statement resets the content of a data object to the initial value for the type. You will find detailed information about initial values for types in the keyword documentation for the CLEAR statement.
© SAP AG
AC400
2-43
Calculations ABAP program Data declarations DATA: max
TYPE sbc400focc-seatsmax,
occ
TYPE sbc400focc-seatsocc,
percentage TYPE sbc400focc-percentage.
COMPUTE
percentage
=
occ *
100 / max .
Keyword COMPUTE is optional : percentage
=
occ * 100 / max .
© SAP AG 2006
In ABAP you can program nested arithmetic expressions as "deep" as you wish. Note that brackets and operators are keywords and must therefore be enclosed by at least one blank character. Valid operators are: y + Addition y - Subtraction y * Multiplication y / Division y **Power y DIV
Integral division without remainder
y MOD Remainder with integral division There are numerous functions for the different data types in the ABAP runtime environment. For example, the following statement provides the current length of the content of a character string: length = STRLEN( cityfrom ). With functions, the opening bracket belongs to the identifier. The remainder must once again be separated by at least one blank character.
© SAP AG
AC400
2-44
The usual algebraic rules normally apply for the evaluation sequence, in other words, first the bracketed expressions, then functions, followed by powers, multiplication/division, and finally addition/subtraction. You will find detailed information about possible operations and functions in the keyword documentation for COMPUTE.
© SAP AG
AC400
2-45
Conditional Branches
IF var > 0 . Statements
ELSEIF
var = 0 .
Statements
ELSE . Statements
CASE
ENDIF .
mycarrid.
WHEN 'AA'. Statements
WHEN 'LH'. Statements
WHEN OTHERS . Statements
ENDCASE . © SAP AG 2006
In ABAP you have two options for executing different sequences dependent on certain conditions. With the CASE-ENDCASE construct, the similarity of the data objects is the criterion for executing a statement block. If the comparison fails, the OTHERS branch is executed, providing it exists. Until the first WHEN branch, all other additions are optional. With the IF-ENDIF construct you can use any logical expressions you want. If the condition is fulfilled, the relevant sequence is executed. If no condition is fulfilled, the ELSE branch is executed, providing it exists. Until the first query, all other branches are optional. With both constructs, only one statement block is ever executed, namely for the first valid case. Recommendation: If you only look for similarity with a value in each condition, you should use the CASEENDCASE construct. It is more transparent and viable as far as runtime is concerned. Outside loops you can also use CHECK instead of IF. This query places the execution of all statements up to the end of the current processing block under a condition. If this fails, the system continues with the first statement of the next processing block.
© SAP AG
AC400
2-46
Loops DO.
Loop counter sy-index
Statements
IF . ENDDO. DO
n
EXIT.
ENDIF.
Loop counter sy-index
TIMES.
Statements
ENDDO. WHILE . Statements
ENDWHILE.
Loop counter sy-index
SELECT ... FROM ... Statements
ENDSELECT. LOOP AT ... Statements © SAP AG 2006
ENDLOOP.
In ABAP there are four loop constructs. LOOP-ENDLOOP and SELECT-ENDSELECT represent special cases. With the first two of the loop types shown here, the number of the current loop pass is counted by the system in the sy-index field. With nested loops the system always counts the current one. Unconditional/index-controlled loops The statements between DO and ENDDO are executed until the loop is exited through other statements. Another option is to specify the number of loop passes, otherwise you can get a socalled endless loop. Precondition loops The statements between WHILE and ENDWHILE are only executed if the condition is fulfilled. With the statements CHECK and EXIT you can influence loop processing in different ways. For example, you can construct a postcondition loop.
© SAP AG
AC400
2-47
Dialog Messages MESSAGE tnnn(message_class) [ WITH v1 [ v2 ] [ v3 ] [ v4 ] ] .
Type
Meaning
Dialog behavior
Message appears in
i
Info message
Program continues after interruption
modal dialog box
s
Success message
Program continues without interruption
Status bar of next screen
w
Warning
Context-dependent
Status bar
e
Error
Context-dependent
Status bar
a
Abort
Program is terminated
modal dialog box
x
Short dump
Runtime error MESSAGE_TYPE_X is triggered
Short dump
© SAP AG 2006
You can send dialog messages with the MESSAGE statement. You must specify the three digit number of the message and the message class. You can also use the WITH addition to include up to four values. These are set dynamically, dependent on the message text. The type ID t controls the dialog behavior. There are six different qualifications for messages: y a Abort The program is terminated after a dialog box. y x Exit
The program is terminated with a short dump.
y e Error
The runtime behavior is context-dependent.
y w Warning
The runtime behavior is context-dependent.
y i Information
The program continues after a dialog box.
y s Success The message appears on the following screen in the status bar. You will find further information about alternative syntax for the MESSAGE statement in the keyword documentation.
© SAP AG
AC400
2-48
Global Reference Structures Data Dictionary Data element
Field type
DATA wa_focc TYPE sbc400focc. Structure SBC400FOCC DATA wa_spfli TYPE spfli. Transparent table SPFLI
Table types
carrid connid fldate
seatsmax
seatsocc
Structure type Type for internal tables
percentage
wa_focc mandt carrid connid countryfr cityfrom
airpfrom countryto . . .
wa_spfli © SAP AG 2006
In ABAP you can define structured data objects (known as structures for short). You can group values that belong together logically in one object. Structures can be nested so that components can, in turn, be derived from structures or even tables. There are two different ways of defining structures: y With DATA struc_name TYPE struc_type you can use local or global types struc_type. y With TABLES global_struc_type a structure is defined that is technically managed in a special storage area. It has an identical name to the global structure global_struc_type or the transparent table global_struc_type. The global structure has to be "flat" for this variant, in other words, the components must be elementary type components. As of Release 4.0 you only require TABLE structures as interfaces for screen fields.
© SAP AG
AC400
2-49
Structures Without Local Reference
TYPES: BEGIN OF st_flightinfo, Declaration of a carrid TYPE s_carr_id, local structure type connid TYPE s_conn_id, fldate TYPE s_date, seatsmax TYPE sflight-seatsmax, seatsocc TYPE sflight-seatsocc, percentage(3) TYPE p DECIMALS 2, END OF st_flightinfo.
DATA wa_flightinfo TYPE st_flightinfo.
carrid connid fldate
seatsmax
Definition of a structure variable
seatsocc
percentage
wa_flightinfo
© SAP AG 2006
You can also define structure types locally with the TYPE statement. The components are enclosed by y BEGIN OF structure_type_name, y ... , y END OF structure_type_name . Each individual component can also be given any type you wish. You will find further information in the keyword documentation for TYPES. You define the data object itself in the usual way. For compatibility reasons, a structured data object can also be defined directly: y DATA: BEGIN OF structure_name, y ... , y END OF structure_name.
© SAP AG
AC400
2-50
Accessing Structure Components
DATA wa_scarr TYPE scarr. wa_scarr - carrid = 'LH'. SELECT SINGLE * FROM scarr INTO wa_scarr WHERE carrid = wa_scarr - carrid. WRITE: / wa_scarr - carrid, wa_scarr - carrname, wa_scarr - url.
mandt carrid carrname currcode url wa_scarr
400
LH
Lufthansa EUR
www.lufthansa.com
© SAP AG 2006
Components in a structure are always addressed with a hyphen: structure_name-component_name. For this reason, you should not use a hyphen in the name.
© SAP AG
AC400
2-51
Value Assignments Between Structures DATA: wa_sflight TYPE sflight, wa_focc TYPE sbc400focc.
... MOVE-CORRESPONDING wa_sflight TO wa_focc.
mandt carrid connid fldate
price planetype seatsmax seatsocc
...
wa_sflight
wa_focc carrid connid fldate
seatsmax seatsocc percentage
© SAP AG 2006
The MOVE-CORRESPONDING source_struc TO target_struc statement copies the content of the source_struc structure component for component to the target_struc structure. The precondition for the value assignment is that the components have the same name. The other components remain unchanged.
© SAP AG
AC400
2-52
internal Tables Screen display
Print list
Files
Dynamic increase in storage capacity
© SAP AG 2006
Database tables
Internal tables are data objects with which you can hold a number of data records with the same structure in the working memory. The number of data records is unlimited. It is only restricted by the limits placed on capacity by actual system installations. The length of internal tables is managed dynamically by the ABAP runtime system. This means that the developer does not need to do anything with regard to managing the working memory. The individual data records of an internal table as known as table entries. The individual components of a line are also known as the columns of the internal table. The line types of internal tables can be any ABAP data types. They can be elementary, structured or even internal tables themselves. Internal tables therefore provide you with a very convenient option for processing large data volumes in a structured form in the program. Typical areas of application are: y Retaining data from database tables for processing at a later stage, y Structuring and staging data for output, y Staging data for use by other services.
© SAP AG
AC400
2-53
Properties of an Internal Table
1
Line type
CARRID CONNID DISTANCE 2
Index
AA LH
0017 0400
2.572 6.162
5
LH QF SQ
0402 0005 0866
7.273 10.000 1.625
6
UA
0007
2.572
1 2 3 4
Key • Components • Uniqueness • Sequence
3
Table type • Standard • Sorted • Hashed
© SAP AG 2006
The data type for an internal table is completely specified through the following properties: Line type The properties of the individual columns are derived from this. You usually specify a structure type, however, any data types are possible. Key definition The key columns and their sequence determine the criteria for identifying lines in a table. The key can be defined as unique or non-unique, depending on the access type. With unique keys there are no multiple entries in internal tables with identical keys. Access type y With key access, data is accessed - in the same way as for database tables - by way of field contents. Example: Read access with the search term 'UA 0007' to an internal table with a unique key CARRID CONNID and the same data as above will yield exactly one data record. y Index access: In contrast to database tables, the system can, under certain circumstances, number the lines for internal tables. This means that it is also possible to use this Index to access table lines. Example: A read access to the data record with index 5 supplies the fifth data record from the internal table.
© SAP AG
AC400
2-54
Table Type and Access Type Index tables
Table type
STANDARD TABLE
SORTED TABLE
Hashed table HASHED TABLE
Index access
n Key access
Key uniqueness NON-UNIQUE
Usage with
predominant index access
UNIQUE | NON-UNIQUE
predominant key access
UNIQUE
exclusive key access
© SAP AG 2006
Another property of an internal table is the table type. Internal tables can be divided into three table types using the possible access types: y With Standard tables, line numbering is maintained internally. Both index and key access is possible. y With sorted tables, the data records are always saved sorted according to the key. With sorted tables, the index is maintained internally too. Both index and key access is possible. y With hashed tables, the data records are managed in the optimum way for runtime. A unique key is required for this. With hashed tables you can only use key access. The table type to be used in each individual case depends on the way in which table entries are normally accessed: y Standard tables are normally used for index access: y Sorted tables are used for unique keys and fixed sorting. y With hashed tables, runtime optimization is only noticeable if read access with a unique key is predominantly used. In this course, although only standard tables are dealt with, the syntax is identical for all three table types - with the odd exception.
© SAP AG
AC400
2-55
Global Table Types
Table type
SBC400_T_SBC400FOCC
Line type
SBC400FOCC
Access
Standard table
Key Key type Key components
DATA itab_flightinfo
non-unique CARRID, CONNID, FLDATE
TYPE sbc400_t_sbc400focc.
carrid connid fldate
seatsmax
seatsocc
percentage
itab_flightinfo
© SAP AG 2006
Table types can be defined locally for a program or globally in the ABAP Dictionary. With DATA itab_name TYPE itab_type you can use local or global types itab_type. You will find detailed information about defining global table types in the ABAP Dictionary in the SAP Library under Basis ABAP Workbench BC - ABAP Dictionary Types Table Types.
© SAP AG
AC400
2-56
Local Table Types
TYPES
tt_flightinfo
Local table type
TYPE STANDARD TABLE OF sbc400focc WITH NON-UNIQUE KEY carrid connid fldate.
DATA
itab_flightinfo
TYPE tt_flightinfo.
carrid connid fldate
seatsmax
seatsocc
Internal tables
percentage
itab_flightinfo
© SAP AG 2006
You can define internal types locally too, using a TYPES statement. The table type is specified between TYPE and TABLE OF. The line type follows TABLE OF. The key fields are listed after the WITH addition. Note that the sequence of the key fields is important here. You will find detained information about the definition of table types that are local to programs in the keyword documentation for TYPES. You define the data object itself in the usual way. For compatibility reasons, you can define an internal table directly too: DATA itab_name TYPE table_kind TABLE OF struc_type WITH key_def.
© SAP AG
AC400
2-57
Overview of Complex Data Types ABAP program DATA wa TYPE spfli.
ABAP Dictionary Transparent table
SELECT ... FROM spfli INTO wa ... wa
DATA wa TYPE sbc400focc. wa
DATA itab TYPE sbc400_t_sbc400focc.
SPFLI (Description)
Database SPFLI AA 17 AA 64 ... ... LH 400 LH 402
... ... ... ... ...
Structure SBC400FOCC
Table type SBC400_T_SBC400FOCC
itab
© SAP AG 2006
© SAP AG
AC400
2-58
Single Access Overview Append
APPEND wa to itab.
Insert INSERT wa INTO TABLE itab .
Read READ TABLE itab INTO wa .
Change MODIFY TABLE itab FROM wa [ ].
Delete DELETE itab . © SAP AG 2006
© SAP AG
AC400
2-59
Group Access Overview Single record processing over the whole (or part) of the internal table
LOOP AT itab INTO wa . ... ENDLOOP .
Delete several records
DELETE itab .
Insert several lines from another internal table
INSERT LINES OF itab1
Append several lines from another internal table
APPEND LINES OF itab1
INTO itab2 .
TO itab2.
© SAP AG 2006
The following set operations are available for internal tables. wa stands for a structure that must be the same type as the line type of the internal table itab: y LOOP ... ENDLOOP The LOOP places the rows of an internal table one after the other into a structure that is specified in the INTO clause. All single record operations can be carried out within the loop. With single record operations, the system identifies the line to be processed in this case. y DELETE deletes the lines of an internal table that satisfy the requirement. y INSERT copies the content of several lines of an internal table into another internal table. y APPEND appends the content of several lines in an internal table to another standard table. You will find detailed information about the ABAP statements listed here in the respective keyword documentation.
© SAP AG
AC400
2-60
Inserting a Single Record * define internal table and workarea DATA: itab_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo
LIKE LINE OF itab_flightinfo.
itab_flightinfo
wa_flightinfo * fill structure with values wa_flightinfo-carrid wa_flightinfo-connid wa_flightinfo-fldate wa_flightinfo-seatsmax wa_flightinfo-seatsocc wa_flightinfo-percentage
= = = = = =
... ... ... ... ... ...
. . . . . .
* insert structure into internal table INSERT wa_flightinfo INTO TABLE itab_flightinfo. © SAP AG 2006
You can insert lines in an internal table by first filling a structure with the required values and then inserting them into the internal table using the INSERT statement. With standard tables, this appends the line, whereas with sorted and hashed tables, the line is inserted by means of a key.
© SAP AG
AC400
2-61
Reading by Loop * define internal table and workarea DATA: itab_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo
LIKE LINE OF itab_flightinfo.
itab_flightinfo
wa_flightinfo LOOP AT itab_flightinfo INTO wa_flightinfo. WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDLOOP.
sy-tabix
© SAP AG 2006
You can read and process the content of an internal table using a LOOP by accessing the structure components within the loop. In this example, a list is compiled from the field contents using the WRITE statement. If you want to change the contents of the internal table, first change the value of the components within the loop and then overwrite the line in the internal table using the MODIFY statement.
© SAP AG
AC400
2-62
Reading by Index LOOP AT itab_flightinfo INTO wa_flightinfo FROM 1 TO 5 . WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDLOOP.
sy-tabix
READ TABLE itab_flightinfo INTO wa_flightinfo INDEX 3 . WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. © SAP AG 2006
You can use the INDEX addition to limit access to specific line numbers. Index operations can only be performed on index tables. They are therefore only supported for standard and sorted tables. In the above example, only the first five lines of the internal table are processed. In the example below, the third line of the internal table is read.
© SAP AG
AC400
2-63
Reading by Key LOOP AT itab_flightinfo INTO wa_flightinfo WHERE carrid = 'LH' . WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDLOOP.
sy-tabix
READ TABLE itab_flightinfo INTO wa_flightinfo WITH TABLE KEY carrid = 'LH' connid = '0400' fldate = sy-datum . IF sy-subrc = 0. WRITE: / wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDIF.
sy-tabix
© SAP AG 2006
You can use the WHERE addition to limit access to lines with specific values. Key operations are supported for all table types. With a completely specified key, key accesses to sorted and hashed tables normally make less demands on runtime than key accesses to standard tables. In the above example, only those lines in the internal table are processed where the carrid field contains the value "LH". (Performance aspect: The sorted table is best suited for this kind of processing.) The example below shows the syntax for reading a line in the internal table with a completely specified key. The return code sy-subrc is set to zero if a corresponding line exists in the internal table. (Performance aspect: The hashed table is best suited for this type of single record access when the number of data records it contains is very large.) Note that for single record access by key with the addition WITH TABLE KEY all key fields must be supplied. If you want to limit the field content, you have to use the WITH KEY addition.
© SAP AG
AC400
2-64
Sorting a Standard Table
SORT itab_flightinfo.
SORT itab_flightinfo
BY carrid.
SORT itab_flightinfo
BY percentage DESCENDING carrid
ASCENDING .
REFRESH itab_flightinfo.
FREE itab_flightinfo.
© SAP AG 2006
You can sort standard tables into columns of your choice by specifying the column name after the BY clause of the SORT statement. SORT itab [ ASCENDING | DESCENDING ] [ BY f1 [ ASCENDING | DESCENDING ] ... fn [ ASCENDING | DESCENDING ] ] [ AS TEXT ] [ STABLE ]. y Sorting the internal table according to the table key or the specified field sequence: Without addition in ascending order. With the AS TEXT addition you can take account of culture-specific sort rules when sorting according to character type fields. When sorting, the relative sequence of the data records that are not differentiated in the sort key is retained only with the STABLE addition. In this example, the data records for the internal table are sorted in descending order according to the extent to which the flights are used, expressed as a percentage. You will find detailed information in the keyword documentation for SORT.
© SAP AG
AC400
2-65
Internal Tables with and Without Header Lines Explicit syntax
Implicit syntax
DATA itab TYPE STANDARD TABLE OF scarr WITH NON-UNIQUE KEY carrid.
DATA itab TYPE STANDARD TABLE OF scarr WITH NON-UNIQUE KEY carrid WITH HEADER LINE .
DATA wa LIKE LINE of itab . Work area wa
Header line itab
Internal table itab
Internal table itab
INSERT wa INTO itab INDEX n.
INSERT itab INDEX n.
DELETE TABLE itab FROM wa .
DELETE TABLE itab.
READ TABLE itab INTO wa INDEX n.
READ TABLE itab INDEX n.
WRITE wa-carrid.
WRITE itab-carrid.
© SAP AG 2006
Internal tables can de defined with or without header lines (addition WITH HEADER LINE). An internal table with header line is a data set from a work area (header line) and the actual body of the table.. Both objects are addressed using the same name! The interpretation of this names depends on the context. With MOVE, for example, it stands for the header line, with SEARCH for the body of the table. In order to avoid confusion, we recommend you use internal tables without a header line. This is particularly evident with nested tables. On the other hand, with operations on internal tables with header lines, a shortened syntax is often possible (APPEND, INSERT, MODIFY, COLLECT, DELETE, READ, LOOP AT). Within ABAP objects, only internal tables without header lines are allowed. You can always address the body of an internal table itab uniquely by using the following syntax: itab[]. This is the case regardless of whether the internal table has a header line or not. y Example - DATA itab1 TYPE TABLE OF i WITH HEADER LINE. - DATA itab2 LIKE itab1. itab1 = itab2. " only the header lines are copied itab1[] = itab2[]. " the actual table content is copied
© SAP AG
AC400
2-66
Database Accesses Application server
ABAP Open SQL
Table buffer
Database server
Native SQL
Database interface
Native SQL
© SAP AG 2006
Open SQL statements are a subset of SQL Standards that are fully integrated in ABAP. They allow the ABAP developer unified access to data, independent of the installed database system. The database interface converts Open SQL to database-dependent SQL statements.
© SAP AG
AC400
2-67
Table Drilldown Report Application-related search Search within a particular application component: Application hierarchy Program-related search Search within a program that accesses the required table:
Source text search: Search in the editor for the SELECT statement
Function debugging: Prior to executing a subfunction switch to debugging mode ("/h") and set breakpoint at SELECT statement
Using screen field information: Display corresponding structure field with F1 + "Technical Information", double-click to navigate to the relevant data element and execute "Where-Used-List in Table Fields" © SAP AG 2006
When searching for database tables, you have various options: Using the Application Hierarchy or the Repository Information System. If you already know a program that accesses the required database table: y Debugger: - Start this program in debugging mode and set a breakpoint at the SELECT statement. y Editor: - Search for the SELECT statement in the source text. y Input field on a screen: - If you know a program that contains a screen with input fields for the table you are looking for, you can use F1 Technical Information and double-click on the technical name of the screen field to navigate to the ABAP Dictionary. This is frequently a structure field. Double-click to navigate to the data element. You can then use the Where-Used-List to search for transparent tables with the field type.
© SAP AG
AC400
2-68
Read Database Access
SELECT FROM INTO WHERE
Which columns ?
Which table ?
Where ?
.
Which lines ?
single/multiple lines
specific columns
© SAP AG 2006
You program read database accesses with the open SQL statement SELECT. The SELECT statement is comprised of a number of clauses with different tasks: y The SELECT clause describes amongst other things whether the selection result should cover several lines or an individual data record, and which fields and tables should be read. y The FROM clause names the source (database table or view) from which the data is to be selected. y The INTO clause determines the internal data objects into which the selected data is to be placed. y The WHERE clause gives the conditions that the selection result must fulfill. It therefore determines the lines in the table that are to be selected. y You will find other clauses in the keyword documentation for SELECT.
© SAP AG
AC400
2-69
Reading by Single Record Access
Database interface
pa_car wa_scarr
Database table SCARR
SELECT SINGLE * FROM scarr INTO wa_scarr WHERE carrid = pa_car . IF sy-subrc = 0. ... ENDIF.
© SAP AG 2006
With the SELECT SINGLE * statement, you read a single record from the database table. To guarantee unique access, all the key fields in the WHERE clause have to be supplied. The asterisk * is used to supply the database interface with the information that all the columns in the line of the database table should be read. If you only want to select certain columns, the required fields can be listed instead. The INTO clause is used to specify the target to which the database interface should copy the data. The target area should be structured with left-alignment in the same way as the required columns from the database table. With the CORRESPONDING FIELDS OF addition for the INTO clause you fill the target area for each component. Only those components are included that have the same name as columns in the database table. Without this addition, the target area is filled aligned to the left, without its structure being taken into account. If a suitable record was found, sy-subrc has the value 0. The SINGLE addition is used to pass the information to the database that only one record is to be read. The database can then terminate the search as soon as the matching record has been found. For this reason SELECT SINGLE is still more efficient at runtime than a SELECT loop when all the key fields are supplied with data.
© SAP AG
AC400
2-70
Reading Several Lines pa_car
Database interface
Database table SFLIGHT
wa_sbc400focc
SELECT carrid connid fldate seatsocc seatsmax FROM sflight INTO wa_sbc400focc " INTO CORRESPONDING " FIELDS OF ... WHERE carrid = pa_car . Statements for each read record
ENDSELECT IF sy-subrc = 0. sy-dbcnt ... ENDIF. © SAP AG 2006
Without the SINGLE addition for the SELECT statement, the system reads several records from the database. The columns with the data to be read by the database are selected using the field list. The number of lines requested can be limited by the WHERE clause. Within the WHERE clause, only the field names of the database table are specified. The FROM clause identifies the database table that is accessed. A number of logical conditions within the WHERE clause can be linked with AND or OR. The database supplies the data to the database interface in packages. The ABAP runtime system then copies the data records line by line in a loop in the target area and ensures that all the statements between SELECT and ENDSELECT. are processed sequentially After the ENDSELECT statement, the return code for the SELECT loop can be read. sysubrc has the value 0 if the solution quantity comprises at least one record. After the ENDSELECT statement, sy-dbcnt contains the entire number of read lines.
© SAP AG
AC400
2-71
Reading Several Lines in an Internal Table
pa_car
Database interface
Database table SFLIGHT
itab_focc
SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO TABLE itab_focc WHERE carrid = pa_car . IF sy-subrc = 0. sy-dbcnt ... ENDIF.
© SAP AG 2006
The addition INTO TABLE itab causes the ABAP runtime system to copy the content of the database interface directly into the internal table itab. This is described as Array Fetch. Since the Array Fetch is not executed as a loop, you cannot program an ENDSELECT statement. If you do not want to overwrite the internal table, but want to append lines to an internal table that has already been filled, you can use the addition APPENDING TABLE itab. sy-subrc has the value 0 if at least one record was read.
© SAP AG
AC400
2-72
Transferring Structures
DATA wa_sbc400focc TYPE sbc400focc. SELECT SINGLE
ABAP program
carrid connid fldate seatsmax seatsocc
FROM sflight INTO wa_sbc400focc WHERE carrid = pa_car AND connid = pa_con AND fldate = pa_date.
Same type as read fields
wa_sbc400focc
© SAP AG 2006
In the program, a suitably typed data object must exist for each column requested by a database table. For maintenance reasons, the data objects should be typed by the appropriate dictionary objects. The INTO clause determines the data object in which the data from the database table is placed. There are two options: y Flat structure: In your program, you define a structure that contains the same fields in the same sequence as the field list in the SELECT clause. In this case you can specify the name of the structure in the INTO clause. The content is copied with left alignment. The field names of the structure are not included in the process. y Individual data objects: You can specify a number of data objects in the INTO clause. y Example: - DATA: gd_carrid TYPE sflight-carrid, gd_connid TYPE sflight-connid, gd_fldate TYPE sflight-fldate, gd_seatsmax TYPE sflight-seatsmax, gd_seatsocc TYPE sflight-seatsocc. - START-OF-SELECTION. - SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO (gd_carrid, gd_connid, gd_fldate, gd_seatsmax, gd_seatsocc)
© SAP AG
AC400
2-73
WHERE ...
© SAP AG
AC400
2-74
Transferring Selected Structure Content DATA wa_sdyn_conn TYPE sdyn_conn. SELECT SINGLE
ABAP program
carrid connid fldate seatsmax seatsocc
FROM sflight INTO CORRESPONDING FIELDS OF wa_sdyn_conn WHERE AND AND
carrid = pa_car connid = pa_con fldate = pa_date .
Same name as read fields
wa_sdyn_conn
© SAP AG 2006
If you use the INTO CORRESPONDING FIELDS clause, the data is placed in fields with the same name in the target structure. Advantages of this construct: y The target structure does not have to be structured with left alignment in the same way as the field list. y The construct is easy to maintain, since the extension of the field list requires no other change to the program, providing a field of the same name and same type exists in the target structure. If you want to use Array Fetch to place data in columns of the same name in an internal table, use INTO CORRESPONDING FIELDS OF TABLE itab.
© SAP AG
AC400
2-75
Client-Dependent Selection
Logged on in client 400 : SELECT * FROM spfli INTO ... WHERE carrid = 'AA'.
SELECT * FROM spfli CLIENT SPECIFIED INTO ... WHERE mandt = 402 AND carrid = 'AA'.
Database table SPFLI MANDT 400 400 ... ... 401 401 ... ... 402 402
CARRID AA AA ... ... AA AA ... ... AA AA
CONNID
CITYFROM
0017 0064 ... ... 0017 0064 ... ... 0017 0064
NEW YORK FRANKFURT ... ... NEW YORK FRANKFURT ... ... NEW YORK FRANKFURT
© SAP AG 2006
In client-dependent database tables, the first key field is always MANDT (data type CLNT). If you select data from client-dependent tables, the data records for the current client are always read, without further specifications. (The ABAP runtime system converts the SELECT statement automatically.) If you explicitly want to include the client field in the WHERE clause, you have to set the CLIENT SPECIFIED addition after the FROM clause. Since this special case is not relevant in the context of this course, the client field is normally omitted from the illustrations.
© SAP AG
AC400
2-76
Selecting with Indices PARAMETERS pa_from TYPE spfli-cityfrom . SELECT * FROM spfli INTO ... WHERE cityfrom = pa_from . ...
Selection screen Departure from
Secondary index for faster access with CITYFROM selection
FRANKFURT
Database table SPFLI
MANDT
CITYFROM
MANDT
CARRID
CONNID
CITYFROM
...
400 400 400 400 400 ... 401 401 401 401 ...
FRANKFURT FRANKFURT FRANKFURT NEW YORK TOKYO ... BERLIN FRANKFURT FRANKFURT NEW YORK ...
400 400 400 400 400 ... 401 401 401 401 ...
AA AA JL LH LH ... AA AA LH UA ...
0017 0064 0407 0400 0402 ... 0017 0064 2407 0941 ...
NEW YORK FRANKFURT TOKYO FRANKFURT FRANKFURT ... NEW YORK FRANKFURT BERLIN FRANKFURT ...
... ... ... ... ... ... ... ... ... ... ...
© SAP AG 2006
As soon as you navigate to the definition of a database table in the ABAP Dictionary, you find information about all the technical properties of that database table. The following information is relevant for efficient database access at runtime: y Key fields: If the required lines from the database are selected according to key fields, the Database Optimizer can access the data using a primary index. y Secondary index: If the required lines from the database are selected according to fields that are listed in a secondary index, the Database Optimizer can use this to access the data. - If you click on the Indexes pushbutton in the Dictionary, the secondary indexes are displayed in a dialog box. If you double-click on an index in the dialog box, the system displays detailed information about the selected index With client-dependent tables the client field is usually included in the index.
© SAP AG
AC400
2-77
Reading Linked Tables
Join tables
SPFLI MANDT CARRID CONNID
Join condition
...
CITYFROM
...
SCARR
MANDT CARRID CARRNAME
...
SPFLI-MANDT = SCARR-MANDT and SPFLI-CARRID = SCARR-CARRID
Table join
Join columns
MANDT CARRID CONNID CITYFROM CARRNAME
© SAP AG 2006
If you want to read data from two databases that are logically related, you can use one database query to access both database tables. Logically, the following information must be specified: y Which database tables should be accessed? y How should the link conditions look? In this condition, columns from both database tables are linked to one another. A shared line in the results table contains an entry if all the field values for the linked columns match. y Which columns should be read? With column names that appear in both database tables, you have to specify the table from which the column should be read.
© SAP AG
AC400
2-78
View and Join View definition in the Dictionary + Selection in program
Direct joining in program (ABAP join)
Database view in Dictionary
Database view ZABC
Program
SELECT ...
Program
SELECT ...
FROM zabc
FROM
WHERE ...
ON spfli~carrid = scarr~carrid
spfli INNER JOIN scarr
WHERE ... © SAP AG 2006
The link conditions can be defined statically or dynamically. y The static links can be defined in the ABAP Dictionary and is labelled a view. There are different types of views. You will find more detailed information in the SAP Library under Basis ABAP Workbench BC ABAP Dictionary Views. y You can implement the dynamic link using ABAP statements. It is known as an ABAP Join. At runtime, a corresponding database query is generated in the database interface. You will find detailed information in the keyword documentation for SELECT FROM clause.
© SAP AG
AC400
2-79
Statements for Database Changes
INSERT
UPDATE SELECT DELETE MODIFY
© SAP AG 2006
With Open SQL, as well as the SELECT statement you can also use UPDATE, INSERT, DELETE and MODIFY. You should not use these changing database accesses unless you are familiar with the SAP transaction concept. All Open SQL statements support the return code sy-subrc. This means that if the data was successfully accessed, the system field sy-subrc has the content 0, if the attempt was unsuccessful, the content is not equal to 0. More detailed information is available in the respective keyword documentation.
© SAP AG
AC400
2-80
Motivation Behind Subroutines . . .
. . .
Subroutine call . . .
... ... ... . . .
Same
... ... ...
source text
. . .
blocks
... ... ...
M or
e tr
ans par ent Eas + ier t om aint ain
Subroutine call . . . Subroutine call . . .
Subroutine
. . .
... ... ...
© SAP AG 2006
A subroutine is a modularization unit inside the program. In a subroutine you store segments of a program to improve the transparency of the main program and/or to be able to use the sequences several times. Data can be exchanged using the subroutine interface. This enables you to call the same functions for different data objects. The above example shows a subroutine that calculates a percentage rate. This subroutine is called a number of times, and in each case, different data objects are transferred to the interface. The use of subroutines makes your program more function oriented: It divides the task into subfunctions to be handled by the subroutine. Under normal circumstances, this also makes your program easier to maintain. You can run these subroutines in the debugger "in the background" and only view the result. This generally enables you to identify the source of an error faster. Structure of a subroutine: A subroutine is enclosed by FORM and ENDFORM. After the name of the subprogram comes the interface definition. Then come the statements that execute the program.
© SAP AG
AC400
2-81
Data Copy when Calling the Subroutine REPORT ... DATA: a TYPE b TYPE c TYPE
... ... ...
, , .
Call subroutine with
( a, b, c )
.. . Copy of a
Subroutine
Formal parameter :
Copy of b
f1 Call by Value
... ... ...
,
f2 Call by Value and Result
,
f3 Call by Reference
© SAP AG 2006
The way in which the data from the main program (actual parameter) is transferred to the data objects of the subroutine (formal parameter) is determined in the interface. There are three possibilities here: Call-by-value y A local copy of the actual parameter is to be transferred to the subroutine. This means that value assignments to the formal parameter have absolutely no influence on the actual parameter. Call-by-reference y The dereferenced address of the actual parameter is to be transferred to the subroutine. This means that value assignments to the formal parameter have a direct influence on the actual parameter. The value of the actual parameter is changed physically by the subroutine through the addressing. Call-by-value-and-result y A local copy of the actual parameter with value return is to be transferred to the subroutine. This means that value assignments to the formal parameter influence the actual parameter only when the subroutine is exited. You should choose this transfer type when you want to ensure that that actual parameters have not been changed when the subroutine is terminated prematurely.
© SAP AG
AC400
2-82
Subroutine Call and Interface REPORT ... DATA: a TYPE b TYPE c TYPE PERFORM xyz USING a CHANGING b c.
... ... ...
, , .
Call
FORM xyz USING " Call by Value value(f1) ... CHANGING " Call by Value and Result value(f2) ... f3 ... . " Call by Reference
Definition
...
ENDFORM. © SAP AG 2006
In the interface definition you count the formal parameters of the various types and type them if necessary. The sequence is fixed: First you have to name all the USING parameters, then all the CHANGING parameters. Within the subroutine you address the transferred data using the formal parameters. When the procedure is called, the actual parameters are also grouped with USING and CHANGING. You determine the transfer type in the interface definition: Call-by-value (f1) y List this kind of parameter after USING and enclose it in brackets with value(f1) too. Call-by-reference (f2) y List this kind of parameter after CHANGING. (For the purpose of documentation you can list a parameter for this transfer type under USING too.) From a technical perspective, USING and CHANGING have the same effect here. (However, if you change a parameter listed under USING in the subroutine, this leads to a warning in the Extended Program Check.) Call-by-value-and-result (f3) y List this kind of parameter after CHANGING and enclose it in brackets with value(f3) too.
© SAP AG
AC400
2-83
Variable and Constant Typing TYPES t_perc TYPE p DECIMALS 2.
TYPES t_perc TYPE p DECIMALS 2.
DATA: a TYPE i, b TYPE i , c TYPE t_perc .
DATA: a TYPE i, b TYPE i , c TYPE t_perc .
...
...
PERFORM calc_perc USING a Varia ble: b Type i CHANGING Risk o nher it ance f con + flict in c. g ty p es FORM calc_perc USING value(f_part) TYPE ANY value(f_all) TYPE ANY CHANGING value(f_pc) TYPE ANY .
PERFORM calc_perc USING a b Cons ta CHANGING Pr esc nt: ribed c. ty p actua e for l para meter FORM calc_perc USING value(f_part) TYPE i value(f_all) TYPE i CHANGING value(f_pc) TYPE t_perc .
CHECK f_all 0. f_pc = f_part * 100 / f_all .
CHECK f_all 0. f_pc = f_part * 100 / f_all .
ENDFORM.
ENDFORM.
© SAP AG 2006
Any type of data object (actual parameters) can be transferred to a subroutine. With elementary types you can decide whether or not you want to type for formal parameter. By typing the formal parameter you ensure that only actual parameters for the specified type can be transferred to the subroutine. This improves the stability of your program, since the syntax check already picks out any type conflicts. TYPE ANY leaves the typing open. (This specification can also be left out for reasons of compatibility.) In this case, the type is "inherited" from the actual parameter to the formal parameter at runtime. If the statements in the subprogram do not match the inherited type, this can lead to runtime errors! If you type with p, n, c or x, the missing type properties are also first "inherited" at runtime. If you want a complete specification here, you have to deploy user-defined types. With string and xstring, the complete specification is only ever available at runtime. The data types i, f, d and t, on the other hand, are completely specified.
© SAP AG
AC400
2-84
Typing with Structures and Internal Tables DATA wa_flightinfo TYPE sbc400focc. ...
DATA it_flightinfo TYPE sbc400_t_sbc400focc. ...
PERFORM fill_wa CHANGING wa_flightinfo . ...
PERFORM fill_itab CHANGING it_flightinfo. ...
Structure type FORM fill_wa CHANGING f_wa TYPE sbc400focc . f_wa-carrid = ... . f_wa-connid = ... .
Table type FORM fill_itab CHANGING f_itab TYPE sbc400_t_sbc400focc . LOOP AT f_itab ... . ... ENDLOOP.
ENDFORM.
Structure components addressable
ENDFORM.
© SAP AG 2006
Structures and internal tables as formal parameters must be typed. This enables you to access these formal parameters as usual within the subroutine. Typing structures identifies the components in the subroutine, so that you can address these with the usual syntax. With internal tables, typing enables you to address the formal parameter as an internal table with the usual syntax. Performance aspect: y With internal tables as the transfer parameter, you should generally select call-byreference as the transfer type, as the effort required to copy data can otherwise be considerable.
© SAP AG
AC400
2-85
Local and Global Internal Tables DATA: it_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo LIKE LINE OF it_flightinfo .
Global variables
... PERFORM fill_itab CHANGING it_flightinfo . ...
FORM fill_itab CHANGING f_itab TYPE sbc400_t_sbc400focc. DATA
l_wa LIKE LINE OF f_itab .
Local variable
LOOP AT f_itab INTO l_wa. ... ENDLOOP. ENDFORM. © SAP AG 2006
You can make so-called local definitions within a subroutine. Both the formal parameters and the local data objects are only active during the subroutine runtime. This means that the corresponding memory space is only allocated at the time the subroutine is called and then freed up again after it has been executed. They can therefore only be addressed from the subprogram. The global data objects of the main program can also be addressed from the subroutine. You should avoid doing this as far as possible, however. Otherwise, you by-pass the interface and your program becomes prone to error. When formal parameters or local data objects and global data objects use the same names, the ABAP runtime system addresses the local data object from within the subroutine and the global data object from outside. This is know as local overcoverage. Summarized advice: y Address the global data objects in the main program and and transfer them to the subroutine via the interface. y Address only the formal parameters and the local data objects in the subroutine. y Avoid using the same names for the sake of clarity. Use simple prefixes such as f_... for "formal parameter" and l_... for "local data object" or similar.
© SAP AG
AC400
2-86
Calling a Subroutine DATA: carrid TYPE sbc400focc-carrid, it_flightinfo TYPE sbc400_t_sbc400focc, lines TYPE i. PERFORM count_lines USING carrid it_flightinfo CHANGING lines. FORM count_lines USING f_carr TYPE sbc400focc-carrid f_itab TYPE sbc400_t_sbc400focc CHANGING value(f_lines) TYPE i. DATA l_wa LIKE LINE OF f_itab. CLEAR f_lines. LOOP AT f_itab INTO l_wa ADD 1 TO f_lines. ENDLOOP.
WHERE carrid = f_carr.
ENDFORM. © SAP AG 2006
This example shows the calling of a subroutine that determines the number of lines in an internal table that fulfill a certain criterion. For performance reasons, the internal table f_itab and the comparison value f_carr are transferred by address and the number of lines f_lines as a value copy. A line-compatible work area is required for the loop access. This is defined locally in the subroutine here by reference to the formal parameter.
© SAP AG
AC400
2-87
Editing a Subroutine System
Help
ABAP Editor: Change Report Z00_FORM Z00_FORM
D
ra g
&
D ro p
...
Subroutines
PERFORM count_lines USING + f_carr f_itab CHANGING f_lines . ...
Use actual parameter
COUNT_LINES
FORM count_lines USING f_carr TYPE ... f_itab TYPE ... CHANGING value(f_lines) TYPE ... . ... ENDFORM. © SAP AG 2006
A subroutine is called with the PERFORM statement. When a subroutine is called, the parameters are transferred in sequence. You should proceed is such a way that you define the subroutine first and then call it. The Object Navigator offers you considerable support here: You can select the subroutine in the navigation area and the "drop" the call statement into the editing area by "drag and drop. Alternatively, you can also use the Template function in the editor to generate the call statement. This ensures that you do not forget or mix up any of the parameters. However, you still have to replace the formal parameters with the actual parameters.
© SAP AG
AC400
2-88
ABAP Workbench Overview: Summary
z The ABAP Workbench contains a number of
tools for developing a wide variety of program objects. z The ABAP Workbench is integrated with the
Repository. z The ABAP Workbench provides a glossary of all
ABAP statements.
© SAP AG 2006
© SAP AG
AC400
2-89
© SAP AG
AC400
2-90
First Attempts at Programming: Overview Diagram
The TheABAP ABAPWorkbench Workbench
Customer CustomerEnhancements Enhancements
First FirstAttempts Attemptsat atProgramming Programming
Extraction Extraction
Dialogs Dialogsand andALV ALVReports Reports
Template TemplateAllocation Allocation
© SAP AG 2006
© SAP AG
AC400
3-91
Programming an Authorization Check
Contents: For the purpose of developing your first program this unit deals with: z Authorization check architecture z The tools for developing function modules z Options for testing the program using the debugger
© SAP AG 2006
© SAP AG
AC400
3-92
The ABAP Workbench: Objectives
At the conclusion of this unit, you will be able to: z Explain the authorization concept z Analyze and write simple function modules z Use the debugger
© SAP AG 2006
© SAP AG
AC400
3-93
Elements of the SAP Authorization Concept
Authorization object class
Authorization object
Authorization
Authorizationprofile
Role
User
1) := assigned 2) := combined 1)
1)
2)
1)
1)
© SAP AG 2006
Authorization field: Smallest unit against which a check can be made (ACTVT, BUKRS). Authorization object: Groups 1 to 10 authorization fields that are then checked in combination (For example.: F_LFA1_APP Vendor: Application authorization). Authorization object class: Logical grouping of authorization objects (for example, all authorization objects for object class FI). Authorization: An attribute for an authorization object, in other words, a combination of permitted values for each authorization field of an authorization object. Authorization profile: Contains attributes (authorizations) for various authorization objects. Role: Is created with the profile generator (transaction PFCG) and enables an authorization profile to be generated automatically. A role describes the activities of an R/3 user. User master record: Used for logging on to the SAP system and allows limited access to functions and objects in the SAP system by way of authorization profiles. Naming conventions for customer developments (see SAP Notes 20643 and 16466) : y Authorizations and authorization profiles are Customizing objects, which is why they do not have to lie in the customer namespace (Y,Z). They cannot have an underscore as the second character, however. y Authorization object classes, objects and fields are development objects and must begin with Y or Z (customer namespace).
© SAP AG
AC400
3-94
Authorization Fields, Objects and Object Classes Authorization fields
BUKRS
Authorization objects
M_RECH_BUK
Authorization object classes MM_R
F_BKPF_BUK FI F_KNA1_BUK ACTVT
C_KAPA_PLA PP C_ARPL_WRK
WERKS
BEGRU
M_MSEG_WWA
MM_B
V_KNA1_BRG
SD
C_DRAW_BGR
CV
© SAP AG 2006
Example: The authorization fields BUKRS (company code) and ACTVT (activity) are used, amongst others, in the following authorization objects: y M_RECH_BUK: Authorization to release locked invoices for certain company codes. y F_BKPF_BUK: Authorization to process documents for certain company codes. y F_KNA1_BUK: Authorization to maintain the customer master record for certain company codes. In the authorizations for the respective authorization object, you can determine which activities (for example, create, change, display, and so on) are allowed to be executed in which programs. Each object has a number of possible activities that are described in the documentation for the object. All possible activities (ACTVT) are defined in the table TACT (transaction SM30). You will find the valid activities for each authorization object in the table TACTZ (transaction SE16).
© SAP AG
AC400
3-95
Authorizations as Attributes Authorization A BUKRS ACTVT
1000
2000
3000
BUKRS ACTVT
1000, 2000 01, 02, 03
2000
3000
BUKRS ACTVT
1000, 2000. 3000 03
Create Change Display
Authorization B BUKRS ACTVT
1000
Create Change Display
© SAP AG 2006
Example: y Authorization A allows you to execute the activities create, change and display in the company codes 1000 and 2000. y Authorization B allows you to execute only the display activity in company codes 1000, 2000 and 3000. If a user has authorization A and B, these operative in an additive way. In other words, the user can execute the activities create, change and display in the company codes 1000 and 2000. In company code 3000, the user can only execute the display activity.
© SAP AG
AC400
3-96
Events for Authorization Checks Change accounting document T code "FB02" Start transaction System program Authorization for the transaction (authorization object S_TCODE)?
No
Authorization for authorization object in table TSTCA?
No
STOP
Yes ABAP program Authorization checks "AUTHORITY-CHECK"
Initial screen Next screen
© SAP AG 2006
When the transaction is started, a system program performs various checks to ensure that the user has the corresponding authorizations. Step 1: Check whether the user is authorized to start the transaction. The authorization object S_TCODE (transaction start) contains the authorization field TCD (transaction code). Users have to have authorization for the transaction code they want to execute (for example FB02, Change Document). Step 2: Check whether the an authorization object is assigned to the transaction code. If this is the case, the system checks whether the user has authorization for this authorization object. The transaction code/authorization object assignment is defined in the table TSTCA. Of one of the above checks is negative, the transaction is not started and the system displays a corresponding message. IMPORTANT: The authorization object assigned to the transaction is checked with the ABAP statement AUTHORITY-CHECK. The check is carried out by the ABAP program that is called by the transaction when the transaction is started.
© SAP AG
AC400
3-97
Programming Authorization Checks
Transaction FB02 Program SAPMF05L
Change accounting document ....
User authorizations Object F_BKPF_BUK Authorization BUK 1000
Check Result
The authorizations are read using the buffer
AUTHORITY-CHECK OBJECT ´F_BKPF_BUK´ ID ´ACTVT´ FIELD ´02´ ID ´BUKRS´ FIELD BUK. IF SY-SUBRC NE 0. MESSAGE E083 WITH BUK. ENDIF. .....
Authorization BUK 1000 Field ACTVT BUKRS
Value 02, 03 1000
© SAP AG 2006
Authorization checks are carried out in programs with the ABAP statement AUTHORITYCHECK. A program can contain any number of these checks. For example, the user wants to call transaction FB02. An AUTHORITY-CHECK is programmed in the ABAP program SAPMF05L that calls transaction FB02. The following authorization is checked: y Authorization object F_BKPF_BUK y Authorization field ACTVT (activity) for the value 02 (change). y Authorization field BUKRS (company code) for the value 1000. The user can only execute the transaction if he/she has the authorization object F_BKPF_BUK with the authorization fields ACTVT (02) and BUKRS (1000) as authorization. The system returns a return code after the authorization check. The valid return codes for the ABAP statement AUTHORITY-CHECK are: y 0: The user has authorization for the authorization object with the correct field values. y 4: The user has authorization for the authorization object, however, the checked values are not assigned to the user y 12: The user has no authorization for the authorization object.
© SAP AG
AC400
3-98
Logical View of a Function Group
Fu In nc ter tio fa n c FB mo e 2 du le
Interface
f ace Inter
ul m od ction Fun FB5
Subroutine
Inte rf ac e
n tio B1 c n F Fu
e
Fun ction m FB3 odule
I
ce le fa odu r nte m
Function module FB4
Interface
© SAP AG 2006
Function modules are special procedures that can be viewed globally and can be called from other ABAP programs. They can only be defined and implemented in special ABAP programs. These programs are called function groups. Function groups are not executable programs, in other words, they cannot be started using transaction codes or by entering the name of the program. They serve exclusively as framework programs for the function modules. In most cases, a function group contains several function modules that offer related functions or operate on the same data. As well as function modules, function groups can also contain the following elements: y Data declarations (global data objects) y Subroutines y Screens y These elements can by used by all function modules in the function group.
© SAP AG
AC400
3-99
Technical Structure of a Function Group
Framework program SAPL INCLUDE LTOP.
Include programs FUNCTION-POOL . TYPES: … DATA: … CONSTANTS: …
INCLUDE LUXX. INCLUDE LU01.
INCLUDE LF.
FORM
...
ENDFORM.
INCLUDE LO.
MODULE OUTPUT.
...
ENDMODULE.
INCLUDE LI. ...
MODULE INPUT.
Global data for the function group Function modules FUNCTION . FUNCTION . ... FUNCTION . ... ENDFUNCTION. ... ENDFUNCTION. ENDFUNCTION.
Subroutines
PBO module
PAI module ENDMODULE.
© SAP AG 2006
From a technical point of view as far as the program is concerned, a function group comprises a framework program and a range of include programs. When you create a function group, the framework program and the include programs are created automatically. The names of the individual components are generated from the name of the function group (). This name can have up to 26 characters. The framework program SAPL contains only INCLUDE statements for the following include programs: y TOP include - The include program LTOP contains the FUNCTION-POOL statement and global data declarations. y U includes - The include program LUXX contains additional INCLUDE statements for the include programs LU01, LU02, ... . The latter contain the actual function modules. y F includes - The include programs LF01, LF02, ... can be used to define subroutines to which all the function modules in the group have access by internal call. y O includes
© SAP AG
AC400
3-100
- The include programs LO01, LO02, ... can be used to define PBO modules (OUTPUT) for the function group screens.
© SAP AG
AC400
3-101
y I includes - The include programs LI01, LI02, ... can be used to define PAI modules (INPUT) for the function group screens. The creation of these include programs is to a large extent automated by forward navigation in the ABAP Workbench.
© SAP AG
AC400
3-102
Function Groups vs. Global Classes
Function groups
Global classes
-
Instantiability
+
+
Screens
-
+
Remote capability
-
+
Update
-
+
Asynchronous execution
-
© SAP AG 2006
Advantages. y As well as important object-oriented concepts such as inheritance, polymorphism and interfaces, the main advantage is the multiple instantiability of the classes. Function groups continue to play an important role in ABAP programming, however. In the following important application cases you cannot use global classes as an alternative to function modules: Screens y In contrast to classes, function groups can contain screens. This allows you to encapsulate user dialogs in function modules too. Remote capability y Function modules can be called from external systems (Remote Function Call). Update y Special function modules can be used for updates (update function modules). They are not executed directly when called, but at the end of the Logical Unit of Work (LUW). Asynchronous execution y The function module is executed in parallel in a separate work process. The calling program does not wait until the function module has finished processing.
© SAP AG
AC400
3-103
Creating a Function Group
© SAP AG 2006
Creating a function group Start transaction SE80 In the navigation area, select object list for function group Enter the name of a new function group (ZBC402_EXAMPLE) (->Screenshot) Clock on Display, "Create Object" popup (->Screenshot) Confirm with "Yes", "Insert Function Group" popup (->Screenshot)
© SAP AG
AC400
3-104
Creating Function Modules
© SAP AG 2006
Start transaction SE80 In the navigation area, select object list for function group Enter the name of the new function group (ZBC402_EXAMPLE) and click on "Display" In the tree structure, open the context menu (right mouse click) for the uppermost node (ZBC402_EXAMPLE) Open submenus: "Create" -> "Function Module". (->Screenshot) Enter data in the "Create Function Module" popup. (->Screenshot)
© SAP AG
AC400
3-105
Function Module Properties Function module
Edit Goto
Utilities
Environment System Help
Function Builder: Display BC402_FMDD_DIVIDE1_PACKED Function module documentation Function module
Properties
Active
BC402_FMDD_DIVIDE1_PACKED
Import
Export
Changing
Tables
Exceptions
Source text
Classification
Function group
BC402_FMDD_EXAMPLE
Short text
Divides two packed numbers
Process type
Demonstration Function modules
General data
Normal function module Remote-enabled module
Package
BC402
Update function module
© SAP AG 2006
In the properties, as well as the general administrative data, you also determine the process type: y Remote-enabled modules can also be called from other systems. y Update function modules are used for bundled database changes and have additional functions for this purpose.
© SAP AG
AC400
3-106
Defining Interface Parameters Function module
Edit
Goto
Utilities
Environment System Help
Function Builder: Display BC402_FMDD_DIVIDE1_PACKED Function module documentation Function module
Active
BC402_FMDD_DIVIDE1_PACKED
Properties
Import
Export
Changing
Tables
Exceptions
Source text
Function Builder: Display BC402_FMDD_GET_FREE_SEATS Parameter name Typing Associated type Default value I_NUMBER1 TYPE DEC8_2 1 I_NUMBER2 TYPE DEC8_2 Function module BC402_FMDD_GET_FREE_SEATS
Properties Parameter name E_RESULT
Import Typing TYPE
Export
Changing
Associated type Pass by value DEC8_2
Optional Pass by value Short text First number Function module documentation Second number Active
Tables
Exceptions
Source text
Short text Results
© SAP AG 2006
Interface parameters are used to exchange data between calling programs and the function module. Parameter types y You distinguish between the following types of parameters: - Import parameters are transferred from the calling program to the function module. - Export parameters are transferred from the function module to the calling program. - Changing parameters act as both import and export parameters at the same time. They are transferred from the calling program to the function module. The function module can change the contents and then return them to the calling program. - Tables parameters are a special option for transferring internal tables. The tables are both imported and exported. You should no longer use tables parameters for normal function modules. Instead, you should transfer internal tables using the other parameter types (typing with a table type from the Dictionary or a generic table type).
© SAP AG
AC400
3-107
Optional Parameters FUNCTION bc402_fmdd_divide1_packed. *"-----------------------------------------------*"*"Local Interface: *" IMPORTING *" VALUE(I_NUMBER1) TYPE DEC8_2 DEFAULT 1 *" REFERENCE(I_NUMBER2) TYPE DEC8_2 *" EXPORTING *" VALUE(E_RESULT) TYPE DEC8_2 *" EXCEPTIONS *" ... *"-----------------------------------------------IF i_number1 IS SUPPLIED. "optional parameter ... ENDIF. IF e_result IS SUPPLIED. "export parameter ... ENDIF. © SAP AG 2006
You can mark import, change and table parameters as optional. Such parameters do not need to be supplied by the caller. Export parameters are always optional. You can define default values for optional import and change parameters that can be used if the caller does not enter any values. When programming function modules you can make the program flow dependent on whether the caller has supplied optional parameters or not. To do this, use logical expressions in the form of IS SUPPLIED or IS NOT SUPPLIED, where stands for the name of the optional parameter. Note that EXPORT parameters are always optional parameters.
© SAP AG
AC400
3-108
Exceptions Function module
Edit
Goto
Utilities
Environment System Help
Function Builder: Display BC402_FMDD_DIVIDE2_GENERIC Function module documentation Function module
Properties
Active
BC402_FMDD_DIVIDE2_GENERIC
Import
Export
Changing
Tables
Exceptions
Source text
Exception classes Exception ZERO_DIVIDE OVERFLOW
Short text Division by zero One of the transferred figures is too large
RAISE . *** with default message: MESSAGE () RAISING . © SAP AG 2006
Function modules can trigger exceptions in order to display errors to the calling program. To do this you have to declare the exceptions in the function module interface. Choose an identifier for each exception that the function module may trigger. You have two options for triggering an exception in a function module when an error occurs: y RAISE . - If is specified in the function module call, control goes directly back to the calling program. If it is not executed, the program is terminated with a runtime error. y MESSAGE () RAISING . - If the exception is specified in the call, processing takes place in the manner described above. If the exception is not specified in the calling program, the message from the message class is sent. The message type determines whether the program is terminated or continues to run. No runtime error is triggered.
© SAP AG
AC400
3-109
Class-Based Exceptions Function module
Edit
Goto
Utilities
Environment System Help
Function Builder: Display BC402_FMDD_DIVIDE4_EXCP_CLASS Function module documentation Function module
BC402_FMDD_DIVIDE4_EXCP_CLASS
Properties
Import
Export
Changing
Tables
Active
Exceptions
Source text
Exception classes
Exception CX_SY_ZERODIVIDE CX_SY_CONVERSION_OVERFLOW
Short text System exception for division by zero. System exception for conversion overflow
RAISE EXCEPTION TYPE [EXPORTING ... ].
© SAP AG 2006
As an alternative to defining identifiers you can also list exception classes in the interface for the function module. To do this, select the Exception Classes checkbox. The exception classes must first be created as global classes belonging to the .Exception Class. type (naming convention: y Exception classes beginning with .CX_. or .ZCX_.). The course BC401 ABAP Objects describes how to work with class-based exceptions. To trigger a class-based exception, for example, you use the statement y RAISE EXCEPTION TYPE . - If the constructor for the exception class has parameters, use the EXPORTING addition to supply them with data.
© SAP AG
AC400
3-110
Documentation
Division of two numbers …
Function module documentation This function module can only be used for training purposes.
Parameter name Short text I_NUMBER1 First number I_NUMBER2 Second number Function module
Long text Change Create
Number to be divided
- 10 000 000 000 000 < i_number1 < 10 000 000 000 000
1 © SAP AG 2006
Function modules can and should be used in other programs. Thorough documentation of the function and interface is therefore particularly important. A distinction is made between function module documentation and parameter documentation. In the function module documentation, you describe the functions offered by the function module. The information contained therein should be sufficiently detailed to make an analysis of the source code unnecessary in order to use the function module. As well as describing the functions, you can also include sample calls, notes on usage and additional sources of information in the documentation. You can access the function module documentation in change mode for the Function Builder using the Function Module Documentation pushbutton, or by following the menu path Goto→ Documentation. In the parameter documentation you enter information about the individual parameters and exceptions for the function module. For parameters, you describe the meaning and, if necessary, the value range and default value. With exceptions, you should describe precisely for which error the exception is triggered and what effect this has. You can access the documentation for parameters and exceptions in the Long Text column of the Parameter/Exception List in the Function Builder.
© SAP AG
AC400
3-111
Source Text of a Function Module Function module
Edit Goto Utilities
Environment System Help
Function Builder: Display BC402_DIVIDE1_PACKED Function module documentation Function module
Properties
Active
BC402_FMDD_DIVIDE1_packed
Import
Export
Changing
Tables
Exceptions
Source text
FUNCTION bc402_fmdd_divide1_packed. *"--------------------------------*"*"Local Interface: *" IMPORTING *" EXPORTING *" EXCEPTIONS *"--------------------------------... ENDFUNCTION.
© SAP AG 2006
When you create a function module the system automatically generates a corresponding U include. The actual functions of the function module are programmed in this include. You cannot load a U include directly to the ABAP Editor, however. It can only be processed within the Function Builder. The FUNCTION and ENDFUNCTION statements mark the beginning and end of the function module. The function module interface is displayed in the form of generated comment lines. These lines are automatically updated when changes occur to the interface. The interface is actually defined on the corresponding tab titles.
© SAP AG
AC400
3-112
Testing Function Modules Function module
Edit Goto Utilities Environment System Help
Function Builder: Change BC402_FMDD_DIVISION1_PACKED
Function module
BC402_FMDD_DIVISION1_PACKED
Active
© SAP AG 2006
You test a function module in the Function Builder by clicking on the pushbutton (Test/Execute). This generates a test framework from the active interface definition. Here you have the opportunity to provide all import, changing and tables parameters with input values. To enter table or structure parameters, double-click on the parameter name. Then execute the function module either directly (pushbutton) or in debugging mode (Debugging pushbutton).
© SAP AG
AC400
3-113
Running a Program in Debugging Mode Debugging from a specific line in a program
+ REPORT sapbc400wbt_getting_started. Program ZBC400_00_GS ZBC400_00_GS Execute
Debugging from start of program
TABLES sbc400_carrier. DATA wa_scarr TYPE scarr. PARAMETERS pa_car TYPE scarr-carrid. ... SELECT SINGLE * FROM scarr Debugging INTO wa_scarr ... WHERE carrid = pa_car. IF sy-subrc = 0. MOVE-CORRESPONDING wa_scarr TO sbc4 CALL SCREEN 100. MOVE-CORRESPONDING sbc400_carrier T ...
© SAP AG 2006
You have several options for starting a program from the Object Navigator in debugging mode without having to change the program: y In the navigation area for the selected program, choose Execute Debugging. y In the editing area, select the required program line and choose Set/Delete Breakpoint. Then start the program with Execute Direct or .
© SAP AG
AC400
3-114
Switch to debugging mode at runtime System
Help
/h Utilities "/ h " to the command field
Debugging screen Debugging ABAP
+ Enter key
Alternative to "/ h "
© SAP AG 2006
If you only want to debug certain parts of the program, you should start it first and then switch to debugging mode before changing screens. There are two possible ways of doing this: y Choose System Utilities Debug ABAP or Debug Screen. y Enter /h in the command field in the toolbar and click on .
© SAP AG
AC400
3-115
Single Step and Field Contents X
SAP
ABAP debugger Watchpoint r
Single-step ZJJ_FORMS
Fixed point arithmetic 15 30
SELECT SINGLE * FROM scarr INTO CORRESPONDING FIELDS OF wa_scarr WHERE carrid = pa_carr. IF sy-subrc = 0. MOVE-CORRESPONDING wa_scarr TO sbc400_carrier. Double-click on CALL SCREEN 100. data object Current statementMOVE-CORRESPONDING sbc400_carrier TO wa_scarr. LH
1 - 4
Field names
pa_carr
SY-SUBRC © SAP AG 2006
0
SY-TABIX
0
SY-DBCNT
Field contents
1
SY-DYNNR
1000
You can execute the program statement for statement in debugging mode with Single Step. You can also display the content of up to eight data objects. To do this, enter the names in the input field on the left or double-click on the names in the displayed code.
© SAP AG
AC400
3-116
Breakpoints ABAP Debugger Watchpoint
Continue
Fixed point arithmetic 15 30
SELECT SINGLE * FROM scarr INTO wa_scarr WHERE carrid = pa_carr. IF sy-subrc = 0. MOVE-CORRESPONDING wa_scarr TO sbc400_carrier. CALL SCREEN 100. MOVE-CORRESPONDING sbc400_carrier TO wa_scarr. LH
1 - 4
Field names
pa_carr
SY-SUBRC
0
SY-TABIX
0
SY-DBCNT
Field contents
1
SY-DYNNR
1000
© SAP AG 2006
You can set a breakpoint by double-clicking in front of a line in the source text. You can also set breakpoints at a specific ABAP statement: Breakpoint Breakpoint at Statement. If you click on Continue, the program is run as far as the next breakpoint. If you Save the breakpoints, they are retained throughout the time you are currently logged on to the system. With breakpoints, the ABAP Workbench changes to debugging mode only for the developer who set the breakpoint. All other users can run the program directly or set their own breakpoints.
© SAP AG
AC400
3-117
Change Tracking
Create/change watchpoint Watchpoint
Local watchpoint (only in specified program) Program Field name
pa_carr
= Comparison operator Comparison field (if not selected: Comparison value) Comparison field/value LH
Watchpoints No. Local Program 1 2 3 ... 10
Field name pa_carr
Logical operator between the watchpoints:
Operator =
Field Comparison field/value LH
OR
AND
© SAP AG 2006
A watchpoint is a breakpoint that is dependent on field content: You can create the following types of watchpoints: y Field name: - The program is run until the content of the field has changed. y Field name, relational operator, comparison value: - The program is run until the field content has changed in such a way that the defined logical condition in relation to a value has been fulfilled. y Field name, relational operator, comparison field: - The program is run until the field content has changed in such a way that the defined logical condition in relation to the content of a field has been fulfilled. You can set up to ten watchpoints an link them using the logical operators AND or OR.
© SAP AG
AC400
3-118
Structure Contents ABAP Debugger Watchpoint Fields Main program
Fixed point arithmetic
Source text from
SELECT SINGLE * FROM scarr INTO CORRESPONDING FIELDS OF wa_scarr WHERE carrid wa_sbc400 Structured field= pa_carr. IF sy-subrc = 0. Length (in bytes)TO sbc400_carrier. 58 MOVE-CORRESPONDING wa_scarr CALL SCREEN 100. Double-click No. Component name TO Type Length Content MOVE-CORRESPONDING sbc400_carrier wa_scarr. Field name
wa_sbc400
SY-SUBRC
0
1 2 3 4 5 6 7 8
MANDT CARRID CARRNAME CURRCODE MARK TRANS TIME DATE
C C C C C C T D
3 3 20 5 1 12 6 8
800 AA American Airlines USD X SMITH 143059 20061224
© SAP AG 2006
You can track the field contents of a structure by entering the structure name in the left column. Double-click on this entry to access the component display for the structure.
© SAP AG
AC400
3-119
Internal Table Contents ABAP Debugger
Alternative
Watchpoint Table
Fixed point arithmetic 15 30
LOOP AT it_flightinfo INTO wa_flightinfo. WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, Double-click on data object Internal table it_flightinfo
Field names
it_flightinfo
SY-SUBRC
0
1 2 3 4 5 6 7 8
Type STANDARD
CARRID
CONNID
FLDATE
...
PERCENTAGE
AA AA AA AA LH LH LH LH
0017 0017 0017 0017 0400 0400 0400 0400
20060512 20060724 20060828 20061224 20060626 20060715 20061113 20061212
... ... ... ... ... ... ... ...
66 120 560 470 240 123 273 280
© SAP AG 2006
You can track the line content of an internal table by entering the name in the left column. Double-click on this entry to access the table display.
© SAP AG
AC400
3-120
Debugging Subroutines ABAP Debugger Watchpoint
Main program
Execute Source text from
Z00_FLIGHTINFO Z00_FLIGHTINFO
Return
15
FORM COUNT_LINES
...
FORM count_lines USING f_carr TYPE ... f_itab TYPE ... CHANGING value(f_lines) TYPE ... . DATA l_wa LIKE LINE OF f_itab. CLEAR f_lines. ... LH
1 - 4
Field names
f_carr
© SAP AG 2006
SY-SUBRC
0
SY-TABIX
0
SY-DBCNT
Field contents
1
SY-DYNNR
1000
You can execute a subroutine without stopping in debugging mode. The main program is then stopped again after the subroutine has been executed. Alternatively, you can execute the subroutine statement for statement with Single Step. If the current statement is within a subroutine, you can click Return () to execute the remainder of the subroutine without stopping. The main program is then stopped again after the subroutine has been executed.
© SAP AG
AC400
3-121
First Attempts at Programming: Summary
z You are familiar with the authorization concept
and can apply it. z You can program function modules. z You can use the debugger.
© SAP AG 2006
© SAP AG
AC400
3-122
© SAP AG
AC400
3-123
Exercises Unit : First Attempts at Programming
At the conclusion of this exercise, you will be able to: • Analyze existing function modules • Program your own function modules • Debug programs • Create authorization objects and evaluate them technically in relation to the program
1-1
© SAP AG
Analysis of the delivered function module BAPI_COMPANYCODE_GETDETAIL 1-1-1 Start the Function Builder to analyze the function module BAPI_COMPANYCODE_GETDETAIL. 1-1-2 What is the name of the function group in which the function module BAPI_COMPANYCODE_GETDETAIL is located? How many function modules are there in total in this function group? Which other object types does this group have, other than function modules? 1-1-3 What are the names of the input and output parameters for the function module? 1-1-4 Test the function module: What is the name of the company code 1000? 1-1-5 How many function modules are called directly from the function module BAPI_COMPANYCODE_GETDETAIL? 1-1-6 Does an authorization check take place? If so, how is it encapsulated? 1-1-7 Follow the execution of the function module in the debugger.
AC400
3-124
1-2
© SAP AG
Programming a function module for the authorization check 1-2-1 Create a function group Y_## as a local object. 1-2-2 Analyze the authorization fields ACTVT and BUKRS. What meaning do the attributes “01”, “06” and “10” for the ACTVT field have? In which table can you find the permitted attributes for the authorization field BUKRS? 1-2-3 Define the authorization object Y## in the authorization class “AC40” with the authorization field “ACTVT”. 1-2-4 Define a role Y## and assign the profile Y##_123456 to it. Assign the authorization object Y## to the role. Define an authorization by giving attributes to the authorization object Y## for the role Y##, such as setting the activities "Change” and “Display”, for example. Assign the role Y## to yourself. 1-2-5 Program a function module, Y##AUTHORIZATION, for the authorization object Y## that provides the authorization to create, change and display dependent on the company code. 1-2-6 Test the function module. Play with the function module by extending your authorization and then calling the function module again. Develop an additional function module, Y##BERECHTIGUNGSTEST, that calls the first one.
AC400
3-125
Solutions Unit : First Attempts at Programming
1-1
© SAP AG
Analysis of the delivered function module BAPI_COMPANYCODE_GETDETAIL 1-1-1 Start the Function Builder to analyze the function module BAPI_COMPANYCODE_GETDETAIL. Start the transaction SE37 under the menu path Tools>ABAP Workbench>Development>Function Builder. Function module BAPI_COMPANYCODE_GETDETAIL Press button “Display” 1-1-2 What is the name of the function group in which the function module BAPI_COMPANYCODE_GETDETAIL is located? How many function modules are there in total in this function group? Which other object types does this group have, other than function modules? Tab page “Attributes” The function group is called “0002”. When you click on the “Display Object List” key, a structure tree is displayed that contains all the objects in the function group. Amongst other objects, there are six function modules in the group. There are also objects for the "DDIC Structures", “Fields”, “Subroutines” and “Includes” types for this group. 1-1-3 What are the names of the input and output parameters for the function module? Tab page “Import” or “Export” Input parameter COMPANYCODEID Output parameter COMPANYCODE_DETAIL COMPANYCODE_ADDRESS RETURN 1-1-4 Test the function module: What is the name of the company code 1000? Press button “Test/Execute” COMPANYCODEID 1000 Press button “Execute” The name of the company code is “IDES AG”.
AC400
3-126
1-1-5 How many function modules are called directly from the function module BAPI_COMPANYCODE_GETDETAIL? Start the transaction SE37 under the menu path Tools>ABAP Workbench>Development>Function Builder. Function module BAPI_COMPANYCODE_GETDETAIL Press button “Display” Tab page “Source Code” The function modules that are called directly can be listed using the “Find/Replace” pushbutton and entering “Call Function” as the search text . Five function modules are called directly. 1-1-6 Does an authorization check take place? If so, how is it encapsulated? Yes, and authorization check is made. It is encapsulated by the “CHECK_AUTHORITY_T001” subroutine. 1-1-7 Follow the execution of the function module in the debugger. Press button “Test” Press button “Debugging” 1-2
© SAP AG
Programming a function module for the authorization check 1-2-1 Create a function group Y_## as a local object. Start the transaction SE80 under the menu path Tools>ABAP Workbench>Overview>Object Navigator. View “Local Objects” Local Objects AC400-## Select the “Function Groups” line in the object tree. Use the context menu to choose the “Create” function. Function group Y_## Short text … Person responsible AC400-## Press button “Save” Press button “Local Object”
AC400
3-127
1-2-2 Analyze the authorization fields ACTVT and BUKRS. What meaning do the attributes “01”, “06” and “10” for the ACTVT field have? In which table can you find the permitted attributes for the authorization field BUKRS? Start the transaction SU20 under the menu path Tools>ABAP Workbench>Development>Other Tools> Authorization Objects>Fields. Select the field ACTVT. The corresponding table name "TACT" can be found by clicking on "Display". Transaction SE16 provides the table content for TACT. The attributes have the following meaning: 01 Insert or Create 06 Delete 10 Post In transaction SU20, select the field BUKRS. The corresponding table name "T001" can be found by clicking on "Display". 1-2-3 Define the authorization object Y## in the authorization class “AC40” with the authorization field “ACTVT”. Start the transaction SU21 under the menu path Tools>ABAP Workbench>Development>Other Tools> Authorization Objects>Objects. Select the authorization object class “AC40”. You can use the context menu to create authorization objects for this class: Object Y## Field name ACTVT BURKS After you have created the documentation, save your data.
© SAP AG
AC400
3-128
1-2-4 Define a role Y## and assign the profile Y##_123456 to it. Assign the authorization object Y## to the role. Define an authorization by giving attributes to the authorization object Y## for the role Y##, such as setting the activities "Change” and “Display”, for example. Assign the role Y## to yourself. Start the transaction PFCG under the menu path Tools>Administration>User Maintenance>Role Administration>Roles Press button “Create Role” Role Y## … Press button “Save” Tab page “Authorizations” Press button “Propose Profile Names” Press button “Save” Press button “Change Authorization Data” Press button “Do Not Select Template” Press button “Manual Entry of Authorization Objects” Authorization Object “Y##” Expand the structure tree that then appears as far as the lowest level. Select the “Activity” line. Press button “Change” Select the entries “01”, “02” and “03”, for example. Press button “Save“ Select the “Company Code” line. Press button “Change” Select the entry “1000”, for example. Press button “Save” Press button “Generate” Press button “Back” Tab page “User” ID AC400-## Press button “Save“
© SAP AG
AC400
3-129
1-2-5 Program a function module, Y##AUTHORIZATION, for the authorization object Y## that provides the authorization to create, change and display dependent on the company code. Start the transaction SE37, for example. Function module Y##AUTHORIZATION Press button Create Function group Y_## Short text … Tab page “Import” Set the parameters according to the “Source Text” information. Tab page “Export” Set the parameters according to the “Source Text” information. Tab page “Exceptions” Set the parameters according to the “Source Text” information. Tab page “Source Text” The following program text offers a possible solution. The import and export parameters are listed in the first section under “Local Interface”. Messages are also used in the function module. The messages used can be created using transaction SE91, for example. The messages referenced here have the following message short text: Message Short text 102 User &1 has no authorization 103 User &1 is not known
© SAP AG
AC400
3-130
FUNCTION Y##AUTHORIZATION. *"--------------------------------------------------------------------*"*"Local interface: *" IMPORTING *" REFERENCE(ID_ACTVT) TYPE ACTIV_AUTH *" REFERENCE(ID_BUKRS) TYPE BUKRS *" REFERENCE(ID_UNAME) TYPE SY-UNAME DEFAULT SY-UNAME *" EXPORTING *" REFERENCE(ED_ANSWER) TYPE CHAR2 *" EXCEPTIONS *" NO_AUTHORITY *" USER_UNKNOWN *"--------------------------------------------------------------------* data DATA: ld_subrc LIKE sy-subrc. * Check AUTHORITY-CHECK OBJECT FOR USER * for activity ID FIELD * and for company code ID FIELD ld_subrc = sy-subrc.
'Y##' id_uname 'ACTVT' id_actvt 'BUKRS' id_bukrs.
* Evaluation of sy-subrc CASE ld_subrc. WHEN 0. ed_answer = 'YES'. WHEN 4 or 12. ed_answer = 'NO'. MESSAGE ID 'AC400' TYPE 'S' NUMBER '102' WITH id_uname RAISING no_authority. WHEN 40. ed_answer = 'NO'. MESSAGE ID 'AC400' TYPE 'S' NUMBER '103' WITH id_uname RAISING user_unkown. WHEN OTHERS. ed_answer = 'NO'. ENDCASE. ENDFUNCTION.
1-2-6 Test the function module. Play with the function module by extending or limiting your authorization and then calling the function module again. Develop an additional function module, Y##AUTHORIZATIONTEST, that calls the first one. Create the function module Y##AUTHORIZATIONTEST in the same way you created your function module Y##AUTHORIZAITON. It © SAP AG
AC400
3-131
could look as follows: FUNCTION Y##AUTHORIZATIONTEST. *"--------------------------------------------------------------------*"*"Local interface: *"--------------------------------------------------------------------DATA: ld_answer TYPE char2. BREAK-POINT. * Test should deliver: ed_answer = 'YES' * and sy-subrc = 0 CALL FUNCTION 'Y##AUTHORIZATION' EXPORTING id_actvt = '01' id_bukrs = '1000' id_uname = 'AC400-##' IMPORTING ed_answer = ld_answer EXCEPTIONS authority_incomplete = 1 no_authority = 2 user_unknown = 3 OTHERS = 4.
© SAP AG
AC400
3-132
* Test should deliver: ed_answer = 'NO' * and sy-subrc = 4 CALL FUNCTION 'Y##AUTHORIZATION' EXPORTING id_actvt = '01' id_bukrs = '2000' id_uname = 'AC400-99' IMPORTING ed_answer = ld_answer EXCEPTIONS authority_incomplete = 1 no_authority = 2 user_unknown = 3 OTHERS = 4. * Test should deliver: ed_answer = 'NO' * and sy-subrc = 40 CALL FUNCTION 'Y##AUTHORIZATION' EXPORTING id_actvt = '01' id_bukrs = '2000' id_uname = 'ODYSSEUS' IMPORTING ed_answer = ld_answer EXCEPTIONS authority_incomplete = 1 no_authority = 2 user_unknown = 3 OTHERS = 4. ENDFUNCTION.
© SAP AG
AC400
3-133
Dialogs and ALV Reports: Overview Diagram
The TheABAP ABAPWorkbench Workbench
Customer CustomerEnhancements Enhancements
First FirstAttempts Attemptsat atProgramming Programming
Extraction Extraction
Dialogs Dialogsand andALV ALVReports Reports
Template TemplateAllocation Allocation
© SAP AG 2006
© SAP AG
AC400
4-134
Dialogs and ALV Reports – Overview
Contents: z This unit provides an overview of dialog programming and ALV as a reporting tool.
© SAP AG 2006
© SAP AG
AC400
4-135
Dialogs and ALV Reports: Unit Objectives
At the conclusion of this unit, you will be able to: z Program dialogs z Program ALV reports
© SAP AG 2006
© SAP AG
AC400
4-136
Parameter Definition ABAP program * PARAMETERS pa_carr TYPE s_carr_id . PARAMETERS pa_carr TYPE spfli-carrid . pa_carr
program-internal variable
Global types Structure field
Selection screen
Data element Airline
Sema nt
ic info
rmatio
n
• Technical type • Documentation • Field label • Search help
© SAP AG 2006
If an input field is typed with a data element, the following semantic information is also available: y A field label can be adopted as the selection text. y The input help (F1 help) from the data element is automatically available for the input field. y An input help (F4 help) is automatically available for the input field if a search help is coupled to the data element. A search help is an independent object that is defined in the Dictionary and that controls the dialog and data retrieval for the input help. If an input field is typed with a structure field that uses a data element, the following semantic information is also available: y The field label and the input help (F1 help) are copied from the data element with which the Dictionary structure field is typed. y If a search help is coupled to the structure field, this is drawn upon for the input help (F4 help) and overcovers the search help for the data element. If no search help is coupled to the field, the search help from the data element is drawn upon. Note that the choice of the global type that you use for typing the input field affects the semantic information available to the user. You will find more information in the online documentation for the ABAP Dictionary.
© SAP AG
AC400
4-137
Selection Texts ABAP program Text elements ( multilingual ) ...
List header
PARAMETERS pa_city TYPE ...
Text symbols
SELECT-OPTIONS so_carr FOR ...
Selection texts PA_CITY
Dictionary
DE Abflugort reference EN
… SO_CARR
Dictionary reference
DE Fluggesellschaft EN
… Selection screen Point of departure Airline
LH
to
© SAP AG 2006
The field names appear as text in front of the input fields of a selection screen by default. You can replace them with selection texts and translate them into the required language. The selection texts appear for the user in the logon language. If the input field is typed directly or indirectly with a data element, you can copy the field labels from one of the texts stored in the Dictionary.
© SAP AG
AC400
4-138
Using Parameters
ABAP program ... DATA wa_spfli TYPE spfli. PARAMETERS pa_car TYPE s_carr_id. Selection screen LH
pa_car LH
SELECT * FROM spfli INTO wa_spfli
Database table
WHERE carrid = pa_car . WRITE: / ... ENDSELECT.
© SAP AG 2006
To get the standard selection screen in an executable program, all you need to do is program a PARAMETERS statement. The statement PARAMETERS name TYPE typename or PARAMETERS name LIKE data_object generates an elementary input field on the selection screen and declares a data object name of the same type. If the user enters a value and chooses Execute, the input value is placed in the internal data object name for the program. Only entries that conform to the type are permitted.
© SAP AG
AC400
4-139
Using Select Options
ABAP program ... DATA wa_spfli TYPE spfli. SELECT-OPTIONS so_car FOR wa_spfli-carrid .
Internal table so_car ( Selection conditions ) Selection screen AA DL
sign option low EQ I LH I BT AA BA E EQ
high DL
SELECT * FROM spfli INTO wa_spfli
Database table
WHERE carrid IN so_car . WRITE: / ... ENDSELECT. © SAP AG 2006
You define selection options using the SELECT-OPTIONS name FOR data_object statement: Two data objects of the same type appear on the selection screen as input fields for entering range limits by default. A pushbutton also appears for carrying out complex range selections. The ABAP runtime system defines an internal table name with four columns as a data object inside the program: y sign to indicate whether the value or the interval should be included (I) or excluded from the range (E), y option for the operator (BT, ...): You will find all the possible operators in the keyword documentation for SELECT-OPTIONS, y low for the lower limit of an interval or individual value, y high for the upper limit of an interval. This selection table name always refers to a data object that has already been defined. The data object normally serves as the target field in data selection and the selection table as the possible range of values. For this reason there is a special form of WHERE clause for the database selection that queries whether the corresponding field is contained in the range on the database. Note: y A similar inclusion query is also define for the IF statement. © SAP AG
AC400
4-140
Example: Authorization Check for the Selection Screen ... PARAMETERS pa_car TYPE s_carr_id. CONSTANTS actvt_display(2) VALUE '03'. * Event processed after leaving the selection screen AT SELECTION-SCREEN. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD pa_car ID 'ACTVT' FIELD actvt_display. IF sy-subrc NE 0. * Show selection screen again with error message MESSAGE e045(bc400) WITH pa_car. ENDIF. START-OF-SELECTION. ...
© SAP AG 2006
By way of example of an additional input check with an error dialog, a program with an input field for the abbreviation of an airline is to be extended. The authorization check is to be performed at the selection screen: y If the user has display authorization for the airline that was entered, the program is to continue processing. y If the user has no display authorization, the selection screen should be displayed again with an error message in the status bar.
© SAP AG
AC400
4-141
Dynpro Properties
Input help
?
Formatting options
Possible values
Type checks
Flexible program flow 100
120
200
140
Consistency check at data input
300
© SAP AG 2006
Dynpros contain not only screen layouts with input and output fields but also their own processing logic. By integrating the ABAP Dictionary, automatic consistency checks are available for screen input fields. As well as the type check, this also includes foreign key checks and checks against fixed values. Information from the Dictionary is automatically used for these checks. The checks can be extended to include checks specific to the program. Technology is available for dynpros that controls the check sequence and makes the fields ready for input again when errors are discovered. The layout can be structured very flexibly, with input fields, output fields, radio buttons, checkboxes, and above all, pushbuttons that enable the user to influence the further course of the program. The same formatting options are available for the dynpro as for the list and the selection screen: Fixed point numbers and dates are formatted according to the settings in the user fixed values, time according to hh:mm:ss, amounts according to the contents of a currency field and lengths, weights and so on according to the content of a unit of measure field.
© SAP AG
AC400
4-142
Dynpro calls Dynpro sequence
100
120
200
140
ABAP program
CALL SCREEN 100.
300
Next dynpro = 0
© SAP AG 2006
You start a dynpro sequence y by specifying the first dynpro as the start dynpro for a transaction code belonging to the "dialog transaction" type, or y by calling a dynpro from any ABAP processing block in the program. In this unit we will limit ourselves to the latter option.
© SAP AG
AC400
4-143
Dynpro Components
Screen Painter Layout editor
Properties Dynpro number Short description
Layout Departure
Element list
CHAR20 Required Entry field ...
Arrival
Dynpro type Next dynpro
...
Field A
Field B
Flow logic (flow control) PROCESS BEFORE OUTPUT. MODULE clear_ok_code. PROCESS AFTER INPUT. MODULE user_command.
... ...
...
© SAP AG 2006
The following components belong to a dynpro: y Properties: - They contain a four figure number for the dynpro name, a short text and information about the dynpro type (for example normal for full screen). y Layout: - You can place elements on your dynpro. Elements that appear on the dynpro are called screen elements. y Element list: - This contains the properties of the screen elements such as position, size and data type. y Flow control: - This contains processing logic that should be processed before the dynpro is sent to the presentation server (PBO) and processing logic that should be processed after a user action (PAI).
© SAP AG
AC400
4-144
The Graphical Layout Editor
Graphical Layout Editor Properties of an element
Layout area Create fields with Dictionary reference
Toolbar Element list
© SAP AG 2006
You can start other functions from the graphical Layout Editor: y Element properties: - This dialog box shows all the attributes for a screen element. You can change some of these attributes directly in the dialog box. Example: Readiness for input of an input/output field. y Fetch from Dictionary / Fetch from Program: - In this dialog box you can generate fields with typing for a global type or fields of the same type for data objects in the program. y Element list: - This shows all the elements displayed on the dynpro together with the relevant attributes. Attributes can be changed directly here too.
© SAP AG
AC400
4-145
Calling Modules
ABAP program Dynpro 100 ... CALL SCREEN 100.
PBO
MODULE abc.
100 PAI
MODULE xyz.
... MODULE abc OUTPUT. ... ENDMODULE. MODULE xyz INPUT. ... ENDMODULE.
© SAP AG 2006
The ABAP statement CALL SCREEN interrupts processing of the processing block and calls the dynpro. Two event blocks are available for each dynpro: y PROCESS BEFORE OUTPUT (PBO) is processed before the dynpro is displayed. At this event, modules can be called that preassign values to the screen fields, for example. y PROCESS AFTER INPUT (PAI) is processed after a user action. The program logic, which depends on the user action, has to be encoded at PAI. Beachten Sie: y The source text for the PBO and PAI events is created with the Screen Painter and not with the ABAP Editor. Both event blocks together are termed the flow logic of the dynpro. y A separate, small command record (no ABAP statement!) is available for programming the flow logic. The most important statement in this record is MODULE module_name. This calls the ABAP processing block module_name, within which you can enter ABAP code as normal. Modules are processing blocks without an interface that can only be called from the flow logic. A module is enclosed by the ABAP statements MODULE and ENDMODULE.
© SAP AG
AC400
4-146
Analyzing the Function Code for PAI ABAP program Dynpro 100 PROCESS BEFORE OUTPUT. ...
Save
... CALL SCREEN 100. ...
Back
MODULE user_command_0100 INPUT. PROCESS AFTER INPUT. CASE ok_code. WHEN 'BACK'. WHEN 'SAVE'. ENDCASE.
MODULE user_command_0100.
... ...
ENDMODULE.
© SAP AG 2006
You can analyze the user actions in a PAI module. This PAI module is normally named user_command_nnnn (nnnn stands for the dynpro number). Analyze the function code in this module in the ok_code field. Note: y For historical reasons, modules have no interface and no local variables. In modules you can access all the global data in the ABAP program.
© SAP AG
AC400
4-147
Creating Modules Using Forward Navigation
Screen painter
Dynpro flow control
Create object
PROCESS BEFORE OUTPUT.
... Double-click
PROCESS AFTER INPUT. MODULE user_command_100.
PAI module USER_COMMAND_100 does not exist. Do you want to create the object?
Yes
No
Cancel
Create PAI module ABAP Editor ...
PAI module
USER_COMMAND_0100
Include election
ZBC400_00_DYNPRO
MODULE user_command_100 INPUT.
New include Framework program
ENDMODULE.
© SAP AG 2006
In the flow control (PBO and PAI) you normally implement MODULE calls. The modules themselves are created in ABAP. There are two options for creating a module: y Forward navigation: From the Screen Painter you create a module by double-clicking on the module name in the flow logic. y Navigation area: If you want to create a module from the object list of the program, choose a new program object "PBO module" or "PAI module". A module can be called from several dynpros (reusability). Note that a module that you call at the PBO event is defined with the MODULE ... OUTPUT statement; you can only call a module that is defined with the MODULE ... INPUT statement at the PAI event.
© SAP AG
AC400
4-148
Fixed Screen Sequences
ABAP program Dynpro 100 ... CALL SCREEN 100.
PBO
MODULE abc.
100
Dynpro attributes: Next dynpro : 100
PAI
MODULE xyz.
... MODULE abc OUTPUT. ... ENDMODULE. MODULE xyz INPUT. ... ENDMODULE.
© SAP AG 2006
If the next dynpro for dynpro 100 is set to 100, the dynpro is processed again after PAI has finished.
© SAP AG
AC400
4-149
Ending Dynpro Sequences - Fixed Rule
ABAP program Dynpro 100 ... CALL SCREEN 100.
PBO
MODULE abc. Dynpro attributes
100 : Next dynpro : 0 PAI
MODULE xyz.
... MODULE abc OUTPUT. ... ENDMODULE. MODULE xyz INPUT. ... ENDMODULE.
© SAP AG 2006
By specifying the next dynpro here, you determine that after the dynpro has been completely processed, processing continues at the dynpro callpoint.
© SAP AG
AC400
4-150
Ending Dynpro Sequences - Variable Rule
ABAP program Dynpro 100 ... CALL SCREEN 100.
PBO
MODULE abc. Dynpro attributes
100 :Next dynpro : 100 0 PAI
MODULE xyz.
... MODULE abc OUTPUT. ... ENDMODULE. MODULE xyz INPUT. SET SCREEN 0. ENDMODULE.
© SAP AG 2006
The next dynpro can be set dynamically from a PAI module using the ABAP statement SET SCREEN nnnn. This represses the static entry. The system enters the number of the current dynpro as the next dynpro by default. As a result, the enter key or the green checkmark only leads to a field check, and the dynpro is sent again after this, with a corresponding error message, if applicable. You can only exit it using a pushbutton intended for this purpose that is caught in a PAI module. Note that when the same dynpros are processed again, all the PBO modules are run again. If you decide to fill the TABLES structure in a PBO module, you must ensure that this does not overwrite the changes made to the data on the dynpro by the user when it is called again.
© SAP AG
AC400
4-151
Syntax Example: Analyzing the Function Code DATA ok_code LIKE sy-ucomm. START-OF-SELECTION. ... AT LINE-SELECTION. ... CALL SCREEN 100. ... MODULE user_command_0100 INPUT.
© SAP AG 2006
CASE ok_code. WHEN 'BACK'. SET SCREEN 0. MESSAGE s057(bc400). WHEN 'SAVE'. * Saving changes in data base ... SET SCREEN 0. MESSAGE s058(bc400). ENDCASE. ENDMODULE.
For our scenario, two pushbuttons should be caught: y With 'BACK', the next dynpro is set to 0 dynamically. This takes you back to the callpoint. In our case, this means returning to the basic list. The message 057 appears in the status bar in the following screen. y With 'SAVE' the program behaves in the same way as for 'BACK'. It returns to the basic list, however, a different message appears in the status bar. In the unit Cross-Program Modularization the program is extended with a change to the data record.
© SAP AG
AC400
4-152
Terms for the User Interface Flight data Edit
Goto
System
Help
Change flight times …
…
GUI title
GUI status Menu bar Toolbar Application toolbar Function key settings
Function key settings Help Select Back ...
F1 F2 F3
© SAP AG 2006
The user interface appears with the following elements: The title bar contains the title of the actual screen. The menu bar contains expandable menus. The menus contain the functions that you can execute in the program. Menus can contain submenus (cascading menus). The "System" and "Help" menus are available with identical functions on all screens in the R/3 system. Neither of these menus can be changed or hidden. The toolbar contains icons for functions that are used very frequently. The toolbar contains the same icons on every screen in the R/3 system with function keys that have been permanently assigned. The icons for functions that cannot be executed on the actual screen are grayed out. The (function) key setting can be displayed with a right mouse click. All functions that can be executed by way of the menu should also be executable by way of a function key. The application toolbar enables frequently used function keys on a screen to be executed by clicking on an icon or a pushbutton too. An interface is created for each program that contains the elements listed above. Views can be created on the user interface for different screens: GUI status.
© SAP AG
AC400
4-153
Status in the Menu Painter – Function Keys
i i i
Menu bar Application toolbar Function keys
Menu bar flight data Application toolbar flight data Function keys flight data
Toolbar BACK %EX
RW
%PRI
%SC
%SC+
P-Ï Ï
P-
P+
Ï Ð
P++ Ð Ð
?
Recommended function key settings F2 F9 ...
Choose Select
PICK
User-determined function keys F5 F6 ... © SAP AG 2006
The key assignment is divided into three areas: y Toolbar: Specific function codes are required for the functions Save, Back, Program Exit, Cancel, Print and the Scroll icons, as well as for the Enter key. The corresponding function key is automatically assigned when you assign a function code to the icon in the toolbar. y Recommended function key settings: Functions are proposed here that should normally be assigned to specific function keys. y User-determined function keys: All the other function codes are listed here that are not covered by standard icons. You can look for suitable keys here for functions specific to a particular program. In addition, you can define a pushbutton in the application toolbar for function keys that are often required. Icons or text can be represented on pushbuttons.
© SAP AG
AC400
4-154
Status in the Menu Painter – Menu Bar
i
Menu bar Flight data Code
PRI
%EX
Print >
Exit
Application toolbar Function keys
Goto
Edit
Text
Save /Send
Menu bar flight data
Code
Text
Code
Text
PICK
Select
BACK
Return
%SC
Search
%SC+
Extend search
RW
Cancel
i i
Application toolbar flight data Function keys flight data
© SAP AG 2006
The system proposes standard layouts for the menu bar which you can also modify, however. The menu bar can contain a maximum of eight menus, six user-definable menus as well as System and Help, which are automatically inserted as standard menus.
© SAP AG
AC400
4-155
Including Existing Status Elements
Selection and Integration of subobjects of an already defined status
Menu bar Application toolbar Function keys
i i i
SCREEN SCREEN SCREEN
© SAP AG 2006
Create a new status for the dynpro and use an icon to display all the menu bar or function key assignments that have already been defined. In the example program only one menu bar or function key assignment is displayed. Double-click on this to select it so that you can reference the same menu bar and the same function key assignment for the dynpro status as in the list status.
© SAP AG
AC400
4-156
Deactivating Status Functions 2
Set to active/ inactive
Function code
i
Menu bar Flight data
Menu bar flight data Goto
Edit
Code
1
Application toolbar Function keys
Select function code
i i
BACK
Text
Back
Application toolbar flight data Function keys flight data
© SAP AG 2006
To set an active or inactive status for functions, proceed as follows: y Switch to change mode status by double-clicking and the Display Change icons. y Place the cursor on the required function code and click on the active inactive icons in the application toolbar In our example, we add the SAVE function, which does not belong to the standard list functions, to the toolbar and the Flight Data menu. The system points out that we are referencing the menu bar and the toolbar. If we confirm the dialog box, the SAVE function is automatically included in the status for the menu bar and the toolbar and displayed as inactive there. The functions BACK and SAVE in our example are analyzed in the PAI module user_command_0100.
© SAP AG
AC400
4-157
Defining GUI Titles SET TITLEBAR 'T_ABC'.
START-OF-SELECTION block ( for list ) or PBO module ( for dynpro )
Doubleclick
Create object GUI interface: Title T_ABC does not exist. Do you want to create the object? Yes
No
Cancel
Create title
© SAP AG 2006
Program
xxxxx
Title code
T_ABC
Title
Change flight times
Confirm
There are three options for creating or maintaining a title: y From the object list of the repository browser, y by forward navigation from the ABAP Editor, or y directly, using the Menu Painter tool. A name of a title can have a maximum of 20 characters. Note: If you create the proposed PBO module status_nnnn by forward navigation, the SET TITLEBAR 'XXX'. statement is automatically generated in the module. It is turned into a comment. You can use this proposal by deleting the asterisk and entering the number of the title. Then you can create the title by forward navigation.
© SAP AG
AC400
4-158
Concept of Object-Oriented Programming Objects (instances) of the class Class (Formal description of objects) attr1
meth1
Object attribute
8
attr2 ABC
• attr1 • attr2 • ...
meth2
Object methods
attr1
meth1
• meth1 • meth2 • ...
3
attr2 XYZ meth2
meth1
attr1
5
attr2 SAP meth2 © SAP AG 2006
The first impression of a class is that it is like a function group: It contains data objects (attributes) and functions (methods). These components can be protected from external access. Then only methods can be used to access them. In contrast to function groups, however, classes can be instanced several times. In other words, more than one runtime object can be generated for a class for each program. Another way of looking at it is that a class contains the technical description of objects (instances). All these objects therefore have the same attributes and offer the same methods. They can all be physically distinguished from one another, however. Their attributes can have different characteristic values. Classes can be defined locally, within an executable program, or globally. As of release 4.6a, the ABAP runtime system supports standard object-oriented syntax elements. However, these cannot be discussed properly in the time available in this training course. You will find detailed information about this in the SAP Library.
© SAP AG
AC400
4-159
Instantiation of Objects and Method Calls ref1
ABAP program
ref2
DATA ref1 TYPE REF TO myclass. DATA ref2 TYPE REF TO myclass. meth1
CREATE OBJECT ref1 ...
meth2
...
CREATE OBJECT ref2 ... meth1 CALL METHOD ref1->meth1 EXPORTING ... IMPORTING ... EXCEPTIONS ...
meth2
CALL METHOD ref2->meth1 EXPORTING ... IMPORTING ... EXCEPTIONS ... … © SAP AG 2006
To generate and address class instances you need so-called reference variables. These are pointers to the instances. You define such reference variables with DATA reference_name TYPE REF TO class_name. The data objects are created in the memory when the program starts. However, because no instances have yet been generated, the reference variables are still empty at this point. At runtime you can generate as many class instances as you want using y CREATE OBJECT reference_name. - The import parameters for a special method, the CONSTRUCTOR, may have to be populated. This special method is executed immediately after the instance has been generated. Basic settings for the actual instance are normally made. You call the methods for an instance using y CALL METHOD reference_name->method_name. - In contrast to calling a function module, the function name is not sufficient here, as several instances of a class normally exist for each program. You use the reference variable, followed by the object component selector ->, to cause a specific instance to call its method.
© SAP AG
AC400
4-160
EnjoySAP Controls as Standard Classes CL_GUI_PICTURE
CL_GUI_ALV_GRID
Picture control
Grid control
CL_SIMPLE_TREE_MODEL
CL_GUI_HTML_VIEWER http://www.sap.com
Airlines AA 0017 0064 LH 0400 0402
HTML viewer control
Tree control
© SAP AG 2006
As of release 4.6a the ABAP Workbench offers a large range of new EnjoySAP controls to relocate dialog functions from the application server to the presentation server. The steering of these controls is object-oriented, and takes place with the help of classes, the SAP Control Framework. Method calls steer the controls from your ABAP program. The Control Framework sends your requirements to the presentation server, where they are converted in accordance with the platform. You can give the user the option of triggering events on the presentation server. These are converted in turn by the Control Framework, so that your ABAP program can respond to them. You will find detailed information about EnjoySAP controls and the Control Framework in the SAP Library.
© SAP AG
AC400
4-161
The SAP Grid Control Details
Search Sort
Total Filter
Download Print
Display variant
Toolbar AA AA AA AA LH LH LH LH LH
17 17 17 64 400 400 400 402 402
2000-01-17 2000-02-20 2000-03-11 2000-05-19 2000-01-13 2000-02-26 2000-03-21 2000-03-04 2000-05-28
USD USD USD USD EUR EUR EUR EUR EUR
513,69 513,69 513,69 369,00 1234,56 1234,56 1234,56 1234,56 1234,56
A321 A321 747-400 747-400 A310-300 A310-300 A310-300 A319 A319
© SAP AG 2006
The ALV grid control is used for displaying non-hierarchical data in a table. Numerous user functions are already implemented. In the control, the columns can be made wider and smaller, or adapted to fit the data that is currently being output using the Optimum Width function. Columns can also be swapped around by selecting a column and dragging it to another position. Standard functions are offered in the control toolbar. The Details View displays the fields in the line on which the cursor was positioned in a modular dialog box. The ALV control provides a Sort Function for any number of columns. You can determine complex sort criteria and arrange the columns in ascending or descending order. With the Search function you can search in lines or columns within a selected area for a character string (generic search without *). Totals can be requested for one or more numeric columns. Using the Subtotals function you can then build control level lists: You select the column (non-numeric fields only) you want to consider and the system provides you with the control level totals. With Print and Download the complete list is always processed and not just the section in the screen display. The user can also make Display Variant settings.
© SAP AG
AC400
4-162
The Custom Container as a Dynpro Object
Dynpro 100
Control area
Area
Custom container control
Container instance
Grid instance
SAP grid control
Process Before Output Process After Input
PBO module ...
...
© SAP AG 2006
An EnjoySAP control must be embedded in an SAP container control. This manages the embedded controls and provides a physical area for visualization. The container becomes the parent of the embedded control. Since containers are themselves controls, they can be nested within one another. This allows you to work with controls both flexibly and in a modular way. You require at least one container and an ALV grid instance in order to use an ALV grid control in your program.
© SAP AG
AC400
4-163
The SAP Grid in the Custom Container CLASS BUILDER CL_GUI_CUSTOM_CONTAINER CL_GUI_ALV_GRID Area
Custom container control
Container instance
Grid instance
SAP grid control © SAP AG 2006
Global classes (object types) are available in the Class Builder for steering the custom container control and the ALV grid control : y CL_GUI_CUSTOM_CONTAINER and CL_GUI_ALV_GRID.
© SAP AG
AC400
4-164
The Constructor Method CL_GUI_CUSTOM_CONTAINER
Is called implicitly with
CREATE OBJECT
Superclasses Methods CONSTRUCTOR
Class Builder Class
CL_GUI_CUSTOM_CONTAINER
Properties
Interfaces
Parameter for method Parameter PARENT CONTAINER_NAME ...
Attributes
Methods
Events
Int. types
CONSTRUCTOR Value
Optional
...
Associated type ...
Description
Mandatory parameter of the CONSTRUCTOR method have to be supplied with CREATE OBJECT.
© SAP AG 2006
For more detailed information about the global class CL_GUI_CUSTOM_CONTAINER, navigate to the Class Builder: Display the object list for the class in the navigation area of the Object Navigator. Then display the entire class or individual components in the editing area. Alternatively, you can double-click on the class name from an ABAP program to access the Class Builder. Depending on the display mode you then click on Parameter or Signature to get detailed information about the interface parameters. The global class CL_GUI_CUSTOM_CONTAINER only has the CONSTRUCTOR method. When the instance is generated using CREATE OBJECT in the program, you have to transfer at least the mandatory parameter container_name. The name of a custom container area on a dynpro must be transferred to this parameter.
© SAP AG
AC400
4-165
Important SAP Grid Control Methods If an implicit call is made at CREATE OBJECT ;
CL_GUI_ALV_GRID Superclasses Interfaces Attributes Methods ...
Mandatory parameter : i_parent
CONSTRUCTOR ...
Mandatory parameter : it_outtab (Display data)
SET_TABLE_FOR_FIRST_DISPLAY
Optional parameter : i_structure_name (global structure for describing the table line type)
... REFRESH_TABLE_DISPLAY ... Redefinitions Events © SAP AG 2006
The global class CL_GUI_ALV_GRID has numerous methods.. To display the content of an internal table with an ALV grid control it is sufficient to examine three methods more closely. CONSTRUCTOR: y The pointer to the container control instance must be transferred to the constructor. SET_TABLE_FOR_FIRST_DISPLAY: y The internal table with the data to be displayed must be transferred to the it_outtab parameter. This table must be a standard table so that the user can deploy the sort functions. y In addition, technical information is required for formatting the grid columns. The easiest thing to do is to use a flat structure or a transparent table - in other words, a global type - as the line type for the internal table. In this case, all you need to do now is transfer the name of the line type to the i_structure_name parameter. y Alternatively, you can also construct a so-called field catalog and transfer it to it_fieldcatalog. REFRESH_TABLE_DISPLAY: y You only need to execute this method if the contents of the internal table have changed since the first time they were displayed.
© SAP AG
AC400
4-166
Placing the Custom Control Container on the Dynpro
Screen Painter
Custom control area
Type: Custom control Name: CONTAINER_1
C
Resizing Vertical : ( Horizontal : (
Min. lines: 5 Min. columns: 20
© SAP AG 2006
To reserve an area for an EnjoySAP control on a dynpro, you have to use the Screen Painter (Layout pushbutton) to create a custom container area. To the left of the toolbar next to the editing area you will find an icon with the description Custom Control: y Choose the Custom Control pushbutton. Then determine the size and position of the area on the dynpro. To do this, you should proceed as follows: You determine the top left corner of the area by pressing the selection key of your mouse. Holding the mouse button down, drag the mouse diagonally to the bottom right as far as the required lower right corner of the area to be created. As soon as you release the mouse button, the lower right corner is fixed. y You can change the size and position of the area at any time by drag and drop using the "pull symbol" that appears on the edge of the area. Assign a name to your newly created dynpro element (here: CONTAINER_1). You can use the attributes Vertical Resizing and Horizontal Resizing to determine whether or not the area should be extended accordingly when you resize the dynpro. If you set the attributes, you can determine the minimum size to which the area can be reduced using the additional attributes Min. Lines and Min. Columns. The upper limit is determined by the size of the area.
© SAP AG
AC400
4-167
Custom Control Containers as Data Objects
DATA gdt_spfli TYPE sbc400_t_spfli.
gdt_spfli
container_r DATA: container_r TYPE REF TO cl_gui_custom_container , grid_r
TYPE REF TO cl_gui_alv_grid .
DATA ok_code TYPE sy-ucomm.
grid_r
ok_code
START-OF-SELECTION. * fill internal table ... CALL SCREEN 100.
© SAP AG 2006
Two reference variables are required in the ABAP program. The reference variable that points to the container control instance is called container_r here, and is typed with the global class cl_gui_custom_container. The reference variable that points to the grid control instance is called grid_r here, and is typed with the global class cl_gui_alv_grid.
© SAP AG
AC400
4-168
Instantiation of Custom Control Containers
MODULE create_control OUTPUT. IF container_r IS INITIAL. CREATE OBJECT container_r EXPORTING container_name = 'CONTAINER_1'
CREATE OBJECT grid_r EXPORTING i_parent = container_r.
container_r
grid_r
... ENDIF. ENDMODULE.
© SAP AG 2006
You generate control instances with the CREATE OBJECT statement. Make sure that you let the system create the statement for you. In this way, you avoid spelling mistakes and errors. Similar to function module calls, the complete interface is implemented in your program. CREATE OBJECT is the interface for the constructor method. Optional parameters are inserted as a comment. Control editing must be processed before the dynpro is displayed. It should also be coupled in a modular way to the processing of the respective dynpro. For this reason we recommend you implement a PBO module here. The controls should be instantiated only once - before the dynpro is first displayed. This can be realized simply by querying the content of one of the two reference variables. Since the instantiation of the container control is implemented in the corresponding PBO module here, it is sufficient to supply the name of the customer container area. In other cases, the program name and dynpro number can be given as well. When instantiating the grid control, it is sufficient to transfer the pointer to the container instance. Thus the container control manages the technical linking of the grid control to the dynpro.
© SAP AG
AC400
4-169
Containing SAP Grids
MODULE create_control OUTPUT. IF container_r IS INITIAL. CREATE OBJECT container_r EXPORTING container_name = 'CONTAINER_1' .
CREATE OBJECT grid_r EXPORTING i_parent = container_r .
container_r
grid_r
CALL METHOD grid_rgrid_r->set_table_for_first_display EXPORTING i_structure_name = 'SPFLI' CHANGING it_outtab = gdt_spfli . ENDIF. ENDMODULE. © SAP AG 2006
To send the content of the internal table and the line type to the grid control, you have to call the method set_table_for_first_display. You transfer the name of the internal table to the it_outtab parameter. Since the internal table was typed with the transparent table SPFLI as the line type, it is sufficient to transfer this name to the i_structure_name parameter. y Basic settings for the grid control could also be supplied here too. If the content of the internal table changes while the program is running, you have to call the refresh_table_display method before you display the dynpro again.
© SAP AG
AC400
4-170
Dialogs and ALV Reports: Summary
z Dialogs are programmed with the help of dynpro
technology. z By using the custom container, ALV reports can
be linked to dynpro technology.
© SAP AG 2006
© SAP AG
AC400
4-171
Exercises Unit 1: Dialogs and ALV Reports
At the conclusion of this exercise, you will know about: • The program library • The basic concept of dynpro logic • The custom control container • Database accesses • ALV as a tool for creating reports
1-1
The program library 1-1-1 Search for the custom container and ALV grid control documentation in the program library. 1-1-2 Select a simple example program for an ALV grid control. Analyze the program. Use the debugger for this too. Is a customer container used in the ALV grid control?
1-2
Programming an ALV report using a template 1-2-1 Copy the program BCALV_GRID_DEMO with all the subobjects to your local objects under the new name Y##ALV_GRID_DEMO. 1-2-2 Change the program Y##ALV_GRID_DEMO so that it displays company codes instead of flights. 1-2-3 Change the screen output. Remove the text “This belongs to the dynpro”. Then maximize the screen and the custom container to use all the existing screen space to display the data. 1-2-4 Enter the title “List of all company codes” for your company code list.
© SAP AG
AC400
4-172
© SAP AG
AC400
4-173
Solutions Unit 1: Dialogs and ALV Reports
1-1
© SAP AG
The program library 1-1-1 Search for the custom container and ALV grid control documentation in the program library. Tools>ABAP Workbench>Overview>Reuse Library Function Subscribe to Library Selection SAP Technology Navigation in the structure tree SAP Technology >Controls>Control Container or SAP Technology>Controls>ALV Grid Control You will learn more about programs under the four tab pages “Overview”, “Documentation”, “Examples”, and “Program Objects”. 1-1-2 Select a simple example program for an ALV grid control. Analyze the program. Use the debugger for this too. Is a customer container used in the ALV grid control? Tools>ABAP Workbench>Overview>Reuse Library Navigation in the structure tree SAP Technology>Controls>ALV Grid Control Tab page “Examples” Examples>Simplest Call>BCALV_GRID_DEMO The custom container G_CUSTOM_CONTAINER is typed under the data declaration. The custom container is instantiated in the “PBO” module. G_CUSTOM_CONTAINER is listed under the “Element List” tab page for dynpro “100”.
AC400
4-174
1-2
Programming an ALV report using a template 1-2-1 Copy the program BCALV_GRID_DEMO with its subobjects to your local objects under the new name Y##ALV_GRID_DEMO. Tools>ABAP Workbench>Overview>Object Navigator View Program Program BCALV_GRID_DEMO Selection Folder BCALV_GRID_DEMO Context menu Copy Target program Y##ALV_GRID_DEMO Selection for Interface, dynpros, includes Function Copy Function Local object 1-2-2 Change the program Y##ALV_GRID_DEMO so that it displays company codes instead of flights. First you have to ascertain in which table the company codes are listed. You can do this, for example, by following the path Tools>ABAP Workbench>Overview>Business Object Browser. The company code can be found under the Financial Accounting application components. Double-click on it to see a list of the key fields. By double-clicking on the key field you will see the reference table T001. Call the editor in change mode. Function “Find/Replace” Find SFLIGHT Replace with T001 … Function “Activate” (activate all subobjects) Test your program.
© SAP AG
AC400
4-175
1-2-3 Change the screen output. Remove the text “This belongs to the dynpro”. Then maximize the screen and the custom container to use all the existing screen space to display the data. Edit the dynpro “100”. Under the “Properties” tab page, set the maintainable coordinates to 200 / 255. Function Layout In the new layout mode, remove the text “This belongs to the dynpro”. Then select close. Function Attribute window Visualized length 255 Visualized height 196 Function Close Function Activate Exit layout maintenance and the flow logic of the dynpro. Test your program again. 1-2-4 Enter the title “List of all company codes” for your company code list. Edit your program. Include a new line before the IF condition in the module “PBO”. SET TITLEBAR '100'. Double-clicking on the title „100“ allows you to create the title manually. Title List of all company codes Function “Copy” Function “Activate” (all objects) Test your program again.
© SAP AG
AC400
4-176
© SAP AG
AC400
4-177
Course Overview Diagram: Customer Enhancements
The TheABAP ABAPWorkbench Workbench
Customer CustomerEnhancements Enhancements
First FirstAttempts Attemptsat atProgramming Programming
Extraction Extraction
Dialogs Dialogsand andALV ALVReports Reports
Template TemplateAllocation Allocation
© SAP AG 2006
© SAP AG
AC400
5-178
Customer Enhancements - Unit Overview
Contents: z This unit presents customer modifications and enhancements. A Business Add-In is implemented.
© SAP AG 2006
© SAP AG
AC400
5-179
Customer Enhancements: Unit Objectives
At the conclusion of this unit, you will be able to: z Differentiate between modifications and
enhancements z Implement BAdIs
© SAP AG 2006
© SAP AG
AC400
5-180
Change Levels
R/3 Business Applications (Standard SAP system)
Customizing
Personalizing
Customer programs
Modification
Customizing
Enhancement
Custom development
ABAP Workbench
© SAP AG 2006
You can adapt the R/3 system to your requirements in the following ways: y Customizing: For configuring your business processes and functions using the Implementation Guide. Possible changes are thus planned and organized. y Personalizing: For changing the global display properties of fields (default settings, hidden/visible), user-specific menu navigation. y Modification: Changes to SAP Repository objects in the customer's system. If SAP ships a modified version of the object, the customer version must be adjusted with regard to the new SAP version. Up to Release 4.0B, this must be performed manually using the upgrade utilities. As of Release 4.5A, this technical adjustment is largely automated by means of the Modification Assistant. y Enhancement: For creating customer Repository objects that are integrated in SAP Repository objects. y Custom development: For creating custom Repository objects in line with customer namespaces. Customizing and most personalizing settings are configured with the Business Engineer tools. Custom developments, enhancement concepts, and modifications, on the other hand, are are managed with the ABAP Workbench tools.
© SAP AG
AC400
5-181
Originals and Copies
Development system
Follow-on system
Customer object
Customer object
Original
Copy Transport of development
SAP object
Original
SAP object
Copy
SAP object
Copy
© SAP AG 2006
An original object can exist in one system only. In the case of objects shipped by SAP, the "original system" is located at SAP. These objects are merely copies in your customer system. This applies to both your development system and all other follow-on systems. If you create your own objects, these objects are original objects in your development system. You always assign developments to a change request using a "development/correction" task. This request is then used to transport the objects from your development system to your follow-on systems.
© SAP AG
AC400
5-182
Corrections and Repairs
Development system
Customer object
Corrected original Correction
SAP object
Corrected original Correction
Follow-on system
Customer object
Copy Transport of correction
SAP object
Modified copy Repair
SAP object
Copy Transport of the repair
© SAP AG 2006
Changes to original objects are referred to as corrections. For this reason, the system records these changes in a transport request along with tasks of the type "development/correction". If a copy is changed (that is, an object is not changed in the original system), this change is included in a task of the type"repair". Repairs to SAP objects are known as modifications. When you make repairs to your own objects (for example, following an emergency in your production system), you can also make the changes to the original objects in your development system straight away. It is essential that any changes you make to copies are also made to the original objects immediately. This option is not available for SAP objects because the originals are not available in one of your systems. You should only make modifications to the standard system if these are essential for optimizing certain processes in your company. You should also be aware that good background knowledge of the structure and process flow of an application is essential as a basis for assessing modification options and for designing effective modifications to change the standard system.
© SAP AG
AC400
5-183
Modifications During an Upgrade
Development system
SAP object
Corrected original
Follow-on system
Customer object
Customer object
Corrected original
Copy
SAP object
SAP object
Modified copy Modification adjustment
Copy Transport of adjustment
Upgrade
Upgrade © SAP AG 2006
Conflicts can occur when you import an upgrade, Support Package, or any other transport request from SAP to your system. Conflicts only occur when you modify an SAP object and the same object is shipped again by SAP. In this case, the object shipped by SAP becomes the active object in the Repository within your R/3 system. If you want to rescue your changes, you have perform a modification adjustment for the objects in question. If you have modified many SAP objects, you may experience considerable delays when you install an upgrade. To ensure consistency between your development system and your follow-on systems, we recommend that you perform the modification adjustment in your development system only. The adjustment objects are then transported to your follow-on systems.
© SAP AG
AC400
5-184
Customizing
Procedure for Functional Changes
Is there a standard function that can be adapted to the customer's requirements in Customizing?
Customizing Personalizing Yes
No
Development
Does the standard SAP system contain a similar function at all?
Custom development CSP solution No
Yes Does the SAP application support the integration of additional functions with enhancements? No
Custom development with SAP program as template
Enhancement Yes
No
Modification
© SAP AG 2006
If the standard functions cannot be adapted to the customer's requirements using the available Customizing or personalizing options, a development project must be started or, if available, a CSP solution (CSP = Complementary Software Product) must be used. A list of CSP solutions certified by SAP is available on SAP Service Marketplace under the alias /softwarepartner. Development projects are used to manage custom developments if similar functions are not available in the standard SAP system. Otherwise, standard SAP objects are used as a basis for enhancements, user exits, modifications, or copies of SAP programs. Modifications are problematic because, following a system upgrade, the new SAP version must be adjusted with regard to the modified customer version. Up to Release 4.0B, this must be performed manually using the upgrade utilities. As of Release 4.5A, this technical comparison is largely automated by means of the Modification Assistant. For this reason, you should only use modifications if y The Customizing or personalizing options do not satisfy your requirements y Suitable enhancements or user exits are not available or planned y Copying the SAP object to the customer namespace is not practical.
© SAP AG
AC400
5-185
ABAP Workbench Change Levels R/3 Business Applications (Standard SAP system) Modification
Customer programs
Enhancement z ABAP Dictionary
z Modification Assistant
z Tables z Data elements
z Program enhancements
Custom development z With call of SAP objects z Without call of SAP objects
z Function module exits z Business Transaction Events z Business Add-Ins
z Menu enhancements z Menu exits z Business Add-Ins
z Screen enhancements z Screen exits z Business Add-Ins
z User exits © SAP AG 2006
Modifications are changes to SAP objects in customer systems. They are: y Located at user exits (subroutines reserved for customers in objects within the SAP namespace) y Hard-coded at various positions in SAP Repository objects. In custom developments, SAP Repository objects can be called from custom-defined programs. Example: A customer writes a program that calls an SAP function module. In the enhancement concepts, the roles are reversed: Repository objects that you have created or changed are called by programs shipped by SAP. Example: You are using a function module exit that is called by SAP. Enhancements can be made at the following levels: y In the ABAP program (function module exit) y In the GUI (menu exit) y In screens for displaying a subscreen in a screen area provided by SAP (screen exit) y As runs of custom program sections based on a screen field (field exit) y In tables or structures of the ABAP Dictionary (table enhancement).
© SAP AG
AC400
5-186
Program Enhancements: Functionality *** SAP program *** ********************************* PROGRAM .
call>
Customer exit
Exit function module
Business Transaction Event Function module Business Add-In
Method
© SAP AG 2006
The basic purpose of a program enhancement is to call an object in the customer namespace. There are various ways of doing this: y Customer exits - A special exit function module is called by the SAP application program. The function module is part of a function group that is handled by the system in a specific manner. y Business Transaction Events - A function module is called dynamically by the SAP application program in the customer namespace. y Business Add-Ins - The application program calls a method of a class or instance of a class. This class is in the customer namespace.
© SAP AG
AC400
5-187
Program Enhancements: SAP and Customer
SAP
Customer Customer exit: Function module exit
FM coding
Call Admin. Interface
Business Transaction Events
Function module in customer namespace
Business Add-Ins
Method in customer class
Documentation
© SAP AG 2006
Program enhancements enable you to define additional program logic for an SAP application program. At present, SAP provides the options shown above. The advantages and limitations of each enhancement option are discussed in greater detail in the relevant units.
© SAP AG
AC400
5-188
Modifications
SAP SAP Program PROGRAM ... ...
Customer SAP Program
.
*Original Coding.. ... ... ...
... *Original Coding.. ...
PROGRAM ... ...
.
*Original Coding.. ... ... ... * Added/changed by customer * Coding ... *Original Coding.. ...
© SAP AG 2006
When you make a modification, you modify the object shipped by SAP directly. This has certain consequences the next time you perform an upgrade. If the object is shipped again, you have to decide whether the new object shipped by SAP or the one you modified is to be valid in your system. Up to Release 4.0B, the finest level of granularity at which modifications were recorded was the Repository object itself, such as an include program. As of Release 4.5A, modifications are recorded with a finer level of granularity. This is facilitated by the Modification Assistant, which is discussed in the Unit on "Modifications". The modification adjustment concept was also thoroughly revised as a result. The procedure for adjusting modifications is also discussed in this unit.
© SAP AG
AC400
5-189
Business Add-Ins: Components
BAdI
Properties.
INTERFACE . Multiple Use
DATA:
a1 ...
Filter Dependent
FCodes Program
Function Code +ABC
METHODS m1 EXPORTING e_par1 e_par2 IMPORTING i_par1.
Generated BAdI Class
METHODS m2 ... ENDINTERFACE. Subscreens Calling Program
Screen No. Subscreen Area Desc. 0200 ABCD Scr..
© SAP AG 2006
Business Add-Ins group the components of an enhancement. A Business Add-In can provide the following enhancement options: y Program enhancement: The interfaces for program enhancements are defined in the Business Add-In in the form of interface methods. This interface is used to implement the enhancement. The SAP program calls the interface methods for the generated BAdI class. y Menu enhancement: Like customer exits, function codes can be entered in a BAdI. The corresponding menu entries are included in the CUA definition and are visible when the BAdI is implemented. y Screen enhancement: Like customer exits, screen enhancements can be defined in a BAdI and then implemented. Several components are created when you define a BAdI: y Interface y Generated class (BAdI class) that implements the interface The generated class (BAdI class) has the following tasks: y Filtering: If a BAdI is to be executed under certain conditions only, the BAdI class ensures that only the valid implementations are called. y Control: The BAdI class calls the active implementations.
© SAP AG
AC400
5-190
Business Add-Ins: Flowchart Application prog. Service class CL_EXITHANDLER
1
Process active implementations
Instance of BAdI class
BAdI: Instance of implement. class
2
© SAP AG 2006
This slide shows the process flow of a program that contains a BAdI call. You can use this slide to help you understand the features and limitations of Business Add-Ins. Not shown: A reference variable that refers to the BAdI interface must be declared in the declaration section. An object reference is generated in the first step. This is carried out by the service class CL_EXITHANDLER shipped by SAP. The exact syntax will be explained on a later slide. The requirements for calling the methods of the program enhancement are thus fulfilled. The BAdI class that implements the interface is generated in the BAdI definition. The interface method of the BAdI class is called in the second call (2). The BAdI class searches for all of the active implementations for the Business Add-In and calls the implemented methods.
© SAP AG
AC400
5-191
Business Add-Ins: Calling Program REPORT . Instance of
DATA: r_var TYPE REF TO . START-OF-SELECTION. CALL METHOD cl_exithandler=>get_instance CHANGING instance = r_var.
CALL METHOD r_var->method EXPORTING IMPORTING .
1 r_var
2
END-OF-SELECTION.
© SAP AG 2006
The above syntax is required to call a Business Add-In. The numbers shown correspond to the calls on the last slide. First, you have to define a reference variable that refers to the BAdI interface. The name of the reference variable does not have to contain the name of the BAdI. An object reference is generated in the first call (1). This creates an instance of the generated BAdI class. This object reference can address only the methods of the interface. This object reference can then be used to call the methods provided by the enhancement (2).
© SAP AG
AC400
5-192
Implementing BAdIs: Methods Properties Interface
Interface Name Name of Implementing Class Method
FCodes
Description BAdI method
Class Builder: Edit Method ~ METHOD ~. *... ENDMETHOD.
© SAP AG 2006
You can choose any name for the implementing class. However, SAP recommends that you follow the proposed naming convention. The proposed name consists of y Namespace prefix, Y or Z y CL_ (stands for class) y IM_ (stands for implementation) y Name of the implementation (without namespace prefix) By double-clicking the name of the method, you can go to the editor for implementing the method. Finally, you have to activate the objects.
© SAP AG
AC400
5-193
Implementing BAdIs: Private Methods
Class Builder: Edit Method ~ METHOD ~. CALL METHOD EXPORTING ... . ENDMETHOD.
Class Builder: Change Class
Properties Methods
Exceptions
Parameters Method
Events
Type Description New method in implementation
© SAP AG 2006
In the implementing class, you can create private methods that you call from the interface method. To do so, you edit the implementing class directly in the Class Builder. Here, you create the private method and interface. You specify whether the method should be visible and implement it.
© SAP AG
AC400
5-194
Implementing BAdIs: Activation
Business Add-Ins: Implem. Maintenance Initial Screen
Implementation Name Display
Change
Create
z Activate z Undo activation
© SAP AG 2006
You can use the relevant icons to activate the implementation of a Business Add-In. From this point on, the methods of the implementation are processed when the calling program is executed. If you deactivate the implementation, the methods are no longer called. The calls in the application program are still processed. However, the instance of the adapter class is no longer able to find an active implementation. Unlike the call "CALL CUSTOMER-FUNCTION", the call "CALL METHOD CL_EXITHANDLER=>GET_INSTANCE" is still executed even though there is no implementation. This also applies to the method call that calls the method of the adapter class. You can activate or deactivate a BAdI only in the original system of the implementation without having to make actual modifications. When you do so, you have to transport the activation/deactivation to the downstream systems. Multiple implementations can exist in a system for a Business Add-In that can have only one implementation. Only one implementation can be active at any one time.
© SAP AG
AC400
5-195
Customer Enhancements – Unit Summary:
z Modifications must be maintained when SAP
Notes and system upgrades are implemented. z SAP recommends that customer enhancements
do not contain modifications. z BAdIs are used in particular to implement
customer enhancements without the need for modifications.
© SAP AG 2006
© SAP AG
AC400
5-196
© SAP AG
AC400
5-197
Exercises Unit: Customer Enhancements
At the conclusion of this exercise, you will be able to: • Explain the concept of BAdIs • Implement BAdIs
1-1
© SAP AG
Research the BAdIs shipped as standard 1-1-1 Use the Repository Information System of the Object Navigator to find out how many BAdIs are shipped for Financial Accounting and Cost Accounting. 1-1-2 Take a closer look at BAdI FAGL_AUTHORITY_CHECK. To which component does the BAdI FAGL_AUTHORITY_CHECK belong? How many methods does the BAdI have? 1-1-3 What parameters does the CHECK_LEDGER_AUTHORITY method have? How does the method output the result of an authorization check? 1-1-4 How many implementations already exist for the BAdI FAGL_AUTHORITY_CHECK? 1-1-5 Implement the BAdI FAGL_AUTHORITY_CHECK. Use the implementation name Y##FAGL_AUTHORITY. Save your implementation as a local object. You do not have authorization for ledger AL but do have authorization to display documents for ledger 0L. As an optional requirement, you could use the function module Y##AUTHORIZATION in your implementation to evaluate the authorization that you grant according to the ledger. In this case, you have to enhance the function module and your authorization object. 1-1-6 Now test your implementation in the BAdI environment. Then post a G/L account document and check the document display.
AC400
5-198
© SAP AG
AC400
5-199
Solutions Unit: Customer Enhancements
1-1
Research the BAdIs shipped as standard 1-1-1 Use the Repository Information System of the Object Navigator to find out how many BAdIs are shipped for Financial Accounting and Cost Accounting. Use transaction SE84 or choose Tools → ABAP Workbench → Overview → Information System.. Open the "Enhancements" folder in the object tree. Look for "Definitions" under "Business Add-Ins". Use the following search criteria Application component FI* and CO* Max. no. of hits 5000 1-1-2 Take a closer look at BAdI FAGL_AUTHORITY_CHECK. To which component does the BAdI FAGL_AUTHORITY_CHECK belong? How many methods does the BAdI have? Use the following search criterion this time: BAdI Name FAGL_AUTHORITY_CHECK The "Attributes" tab page shows the package "FAGL_POSTING_SERVICES". Double-click this package to view the package properties. The package belongs to the component "FIGL". The "Interface" tab page lists exactly one method – "CHECK_LEDGER_AUTHORITY". 1-1-3 What parameters does the CHECK_LEDGER_AUTHORITY method have? How does the method output the result of an authorization check? The "Interface" tab page lists the method "CHECK_LEDGER_AUTHORITY". Double-click the method to view its parameters. It has six import parameters. You can view the exception messages by choosing the "Exceptions" pushbutton. The result of the authorization check is provided by means of the "NO_AUTHORITY" exception.
© SAP AG
AC400
5-200
1-1-4 How many implementations already exist for the BAdI FAGL_AUTHORITY_CHECK? You can view the implementations from the menu on the initial screen by choosing Implementation → Overview. 1-1-5 Implement the BAdI FAGL_AUTHORITY_CHECK. Use the implementation name Y## FAGL_AUTHORITY. Save your implementation as a local object. You do not have authorization for ledger AL but do have authorization to display documents for ledger 0L. As an optional requirement, you could use the function module Y##AUTHORIZATION in your implementation to evaluate the authorization that you grant according to the ledger. In this case, you have to enhance the function module and your authorization object. You can create your own implementations from the menu on the initial screen by choosing Implementation → Create. On the "Interface" tab page, you can double-click a method to program it. 1-1-6 Now test your implementation in the BAdI environment. Then post a G/L account document and check the document display. On the "Interface" tab page, you can both program and test methods.
© SAP AG
AC400
5-201
Overview Diagram: Extraction
The TheABAP ABAPWorkbench Workbench
Customer CustomerEnhancements Enhancements
First FirstAttempts Attemptsat atProgramming Programming
Extraction Extraction
Dialogs Dialogsand andALV ALVReports Reports
Template TemplateAllocation Allocation
© SAP AG 2006
© SAP AG
AC400
6-202
Extraction – Overview
Contents: z This unit describes how data is extracted to the BW system. In particular, it explains how to extract data using function modules that you have created yourself.
© SAP AG 2006
© SAP AG
AC400
6-203
Extraction: Unit Objectives
At the conclusion of this unit, you will be able to: z Describe how data is extracted to the BW
system z Write your own extraction functions
© SAP AG 2006
© SAP AG
AC400
6-204
The Administrator Workbench Modeling
BW creation
Maintenance
Administration
Scheduling
Schedule data transfer
Load data
Administrator Workbench
Monitoring
Monitor data transfer
Monitor update process
© SAP AG 2006
The Administrator Workbench is a tool for maintaining, controlling, and monitoring Business Information Warehouse. For this reason, the Administrator Workbench is used at all levels in the BW system: y To create all the components of Business Information Warehouse, including Customizing settings. y To schedule data transfer from different data sources. y To load data y To monitor data transfer and data updates
© SAP AG
AC400
6-205
Data Flow from the Source to the Target System Data targets
BW server
Update rules
InfoSource
Communication structure
Mapping & transfer rules Flat file DataSource
DataSource (replicate)
Transfer structure
DataSource (replicate) Transfer structure
DataSource – File
File system
Transfer structure
DataSource
Transfer structure
Transfer structure
Extraction structure
Extraction structure
SAP system
© SAP AG 2006
An InfoSource is a set of logically related information that is grouped together in one unit. InfoSources contain transaction data (stored in InfoCubes) and master data (attributes, texts, and hierarchies - stored in separate tables). InfoSources describe the set of all available information about a business transaction or a type of business transaction (such as cost center accounting). Transfer structures are used to transfer data in a DataSource between a source system and the associated SAP BW system. The transfer structure transports the data in the DataSource from a source system to an SAP BW system and forwards it to the InfoSource using transfer rules. The communication structure is independent of the source system and is generated from the InfoSource. It is filled from the transfer structure in accordance with the transfer rules. The communication structure contains all the fields in an InfoSource. The process of extracting and transferring cleansed data to the communication structure is referred to as "data staging".
© SAP AG
AC400
6-206
Verification Between the Source and Target System BW server
1
DataSource (replicate)
When the DataSource is replicated, fields in the extraction structure are used as a template for the transfer structure in BW.
Transfer structure
1
2
2
When the (local) transfer rules are activated, the transfer structure is generated both in the BW system and in the SAP source system.
DataSource
Transfer structure Extraction structure
SAP source system © SAP AG 2006
The extraction tables in the source system represent the basis for a DataSource in an R/3 source system. The structure is created in the source system using the data elements that describe the available data (usually in a table view). With an R/3 source system, the "DataSource Replication" step copies the DataSource extraction source structure as a template from the source system to the BW system.
© SAP AG
AC400
6-207
Defining Transfer Rules InfoSource
COSTC##
GR## Cost Center 13
Communication Structure InfoObject
Description
Status Type Length …
0CO_AREA
Controlling area
CHAR
4
COSTC##
GR## Cost Center 13
CHAR
13
0CURRENCY
Currency
CUKY
5
CHAR
10
0PROFIT_CTR Profit Center
Source System
Transfer Method
IDES R/3
PSA
ZGR##CC_ATTR
DataSource
Communication Str./Transfer Rules InfoObject 0CO_AREA COSTC## 0CURRENCY 0PROFIT_CTR 0COMP_CODE
IDOC
Transfer Rules
Transfer structure
InfoObject – Field Assignment
Tp Rule 0CO_AREA COSTC## 0CURRENCY 0PROFIT_CTR 0COMP_CODE
InfoObject
Field
0CO_AREA
KOKRS
COSTC## 0CURRENCY 0PROFIT_CTR 0COMP_CODE
KOSTL WAERS PRCTR BUKRS
© SAP AG 2006
Transfer rules determine which fields in the transfer structure are transferred to which fields in the communication structure. You can create detailed conversion rules to change or extend the data that is transferred. You can choose only one of the three types of transfer rule for each InfoObject in the communication structure: y The fields are copied from the transfer structure and are not modified. y You can assign a fixed value to a field. y You can create/assign local transfer routines. Local transfer routines are ABAP programs that you can copy or modify. The routine affects only the selected InfoObject in the associated communication structure. You have to activate the transfer rules before they can be applied.
© SAP AG
AC400
6-208
Extraction – Unit Summary:
z You can use function modules to select the data
in the source system that you want to extract.
© SAP AG 2006
© SAP AG
AC400
6-209
Extraction -
Exercises
Unit: Extraction
At the conclusion of this exercise, you will be able to transfer data from a source system (such as R/3) to a BW system. You will be familiar with: • The data export concept using DataSources and extraction from the source system • The procedure for importing data using InfoSources in the target system • How to program an extraction using function modules. 1-1
© SAP AG
Program an extraction module 1-1-1 Create the function module Y##BW. Use the extraction documentation in SAP Library to define the interface. Use your function module to select certain cost centers, such as all cost centers that belong to profit center 1402 or those where Mr. Janning is the cost center manager. 1-1-2 Configure your function module Y##BW as an extractor by specifying Y##DS as the master data DataSource. When you define the DataSource, also enter "AC400AKR3" as the application component and the export structure of your function module as the extraction structure. 1-1-3 Test your extractor and use the debugger to analyze the extraction. 1-1-4 Log onto the BW system. Replicate the DataSource.
AC400
6-210
1-2
© SAP AG
Transfer data from the source system to the BW data model After you have imported the data from the source system by replicating the DataSource, you can transfer it to the BW data model. To do so, you first have to define a data model and then verify the DataSource. 1-2-1 Define the characteristic TE_Y##M with the description "Y## Cost Center" as an InfoObject for the BW model. The data type is CHAR with length 10. Choose ALPHA as the conversion routine. Define the following fields as characteristic attributes: 0CO_AREA 0COMP_CODE 0BUS_AREA 0PROFIT_CTR 0RESP_PERS 0EVCURRCOST. 1-2-2 Create the InfoSource TE_Y##M in the component "AC400AKBW" to update master data of the InfoObject with the same name (TE_Y##M) directly. Assign the DataSource Y##DS to the InfoSource. In the transfer rules, assign your BW field TE_Y##M to the source field KOSTL. 1-2-3 Control the transfer by creating an InfoPackage. On the "Processing" tab page, choose "PSA and then in the InfoObject"; on the "Update" tab page, choose "Full Update" and on the "Schedule" tab page, choose "Start Data Load Immediately". 1-2-4 Load the cost centers from the source system. Observe the transfer in the monitor and analyze the result.
AC400
6-211
Solutions Unit: Extraction
1-1
© SAP AG
Program an extraction module 1-1-1 Create the function module Y##BW. Use the extraction documentation in SAP Library to define the interface. Use your function module to select certain cost centers, such as all cost centers that belong to profit center 1402 or those where Mr. Janning is the cost center manager. The extraction documentation is available at: SAP Library → SAP NetWeaver → Information Integration → Business Intelligence Then choose: SAP Business Information Warehouse → Data Warehousing → Data Retrieval → Data Extraction from SAP Source Systems → Customizing Extractors → Maintaining Generic Data Sources → Function Module: Interface Description and Procedure You can display a list of the existing cost centers in transaction KS13 by choosing Accounting → Controlling → Cost Center Accounting → Information System → Reports for Cost Center Accounting Master Data Indexes → Cost Centers: Master Data Report Table CSKS contains the cost center master data. This table must type the export parameter E_T_DATA. 1-1-2 Configure your function module Y##BW as an extractor by specifying Y##DS as the master data DataSource. When you define the DataSource, also enter "AC400AKR3" as the application component and the export structure of your function module as the extraction structure. DataSources are defined with transaction RSO2. IMG → Integration with Other mySAP.com Components → Data Transfer to the SAP Business Information Warehouse → Generic DataSources → Maintain Generic DataSources 1-1-3 Test your extractor and use the debugger to analyze the extraction. DataSources are also tested with transaction RSO2. IMG → Integration with Other mySAP.com Components → Data Transfer to the SAP Business Information Warehouse → Generic DataSources → Maintain Generic DataSources You can simulate the extraction by choosing DataSource → Test Extraction in the maintenance transaction. AC400
6-212
1-1-4 Log onto the BW system. Replicate the DataSource.
© SAP AG
AC400
6-213
1-2
© SAP AG
Transfer data from the source system to the BW data model After you have imported the data from the source system by replicating the DataSource, you can transfer it to the BW data model. To do so, you first have to define a data model and then verify the DataSource. 1-2-1 Define the characteristic TE_Y##M with the description "Y## Cost Center" as an InfoObject for the BW model. The data type is CHAR with length 10. Choose ALPHA as the conversion routine. Define the following fields as characteristic attributes: 0CO_AREA 0COMP_CODE 0BUS_AREA 0PROFIT_CTR 0RESP_PERS 0EVCURRCOST 1-2-2 Create the InfoSource TE_Y##M in the component "AC400AKBW" to update master data of the InfoObject with the same name (TE_Y##M) directly. Assign the DataSource Y##DS to the InfoSource. In the transfer rules, assign your BW field Y##_KOSTL to the source field KOSTL. 1-2-3 Control the transfer by creating an InfoPackage. On the "Processing" tab page, choose "PSA and then in the InfoObject"; on the "Update" tab page, choose "Full Update" and on the "Schedule" tab page, choose "Start Data Load Immediately". 1-2-4 Load the cost centers from the source system. Observe the transfer in the monitor and analyze the result.
AC400
6-214
Overview Diagram: Template Allocation
The TheABAP ABAPWorkbench Workbench
Customer CustomerEnhancements Enhancements
First FirstAttempts Attemptsat atProgramming Programming
Extraction Extraction
Dialogs Dialogsand andALV ALVReports Reports
Template TemplateAllocation Allocation
© SAP AG 2006
© SAP AG
AC400
7-215
Template Allocation – Unit Overview
Contents: z This unit presents the concept of template allocation and describes interfaces that allow you to implement specific data access and cost calculations.
© SAP AG 2006
© SAP AG
AC400
7-216
Template Allocation: Unit Objectives
At the conclusion of this unit, you will be able to: z Use your own methods in template allocation.
© SAP AG 2006
© SAP AG
AC400
7-217
The Template as a Costing Tool
Routing
No. BOM Items
No. work centers
External systems
BOM
Template
Weight
Meas. data
Material master data
No. value fields
CO-PA
Lot size
Standard cost estimate
© SAP AG 2006
Cost drivers can originate from many areas in the integrated R/3 system. Bills of material can provide the number of components in a cost object, for example, and the routing can indicate the number of work centers through which the cost object must pass. The standard cost estimate can provide the lot size of the material produced.
© SAP AG
AC400
7-218
Product Costing with Templates
Cost element: R-4000
Material: R-4000
Material Lot size Rout Bill - of ing
Functions
materials Template
Statistical key figures
Prod_1
CO - values Material Activities Overhead
Processes: 300000 300100
Processes ss Proce ities t quan
Other SAP sources
© SAP AG 2006
Product cost planning includes the quantities and prices from the planned consumption of process quantities. The cost component view can be maintained in Customizing to include processes in an aggregated view of process costs and quantities for individual product cost plans. In Customizing for cost components, you can define each component as valuation relevant if the process costs should be included in inventory. In the itemization view of the product cost estimate, process values are marked "X." Overhead values calculated using a costing sheet are marked "G".
© SAP AG
AC400
7-219
Derivation of Templates in the Cost Estimate
Unit cost estimate/ standard cost estimate
Costing variant PPC1 Valuation variant 001
Costing sheet
Template Prod _1 Main template Template Prod _2 Template Prod _3 Process
Overhead group: SAP900
Overhead key
Cleaning Q. insp.
10 Valuation time Quantity 10 30 Order-start 20 20 Delivery 20
Material: R 4000
© SAP AG 2006
The link between the template and the cost estimate is created through a template assignment function in Customizing. The template is assigned to a combination of overhead key and costing sheet. The costing sheet is linked to a valuation variant, which, in turn, is linked to a costing variant that is linked to the order type. The overhead group belongs to the material master data. It is assigned to an overhead key in Customizing. You can still use a costing sheet for overheads that are not modeled using processes.
© SAP AG
AC400
7-220
Template Rows as Formula Vectors
Template for cost element Object
Pl. Qty.
Pl. Activ.
Act. Qty .
Act. Activ. .
Act. Val. Ev.
Under what conditions? Which process?
When? Which process quantity?
© SAP AG 2006
A template is created within a certain environment, which is determined by the cost object that will consume the process quantities. A process that is consumed by a PP production order, for example, is controlled by a template created in environment 001. Conversely, a process (possibly the same process) that is consumed by a sales order is controlled by a template created in environment 008. A template consists of pre-defined columns. Each of these columns looks for information that is, it asks a question. The answer may be entered by the user, or determined dynamically by the system. The real power of Activity-Based Costing in R/3 is realized when the system answers these questions dynamically.
© SAP AG
AC400
7-221
"Functions" as Form Components
Template for cost element Object
Pl. Qty.
Pl. Activ.
Act. Qty .
Act. Activ. .
Under what conditions? Which process? ns
ns io
How much of the process quantity?
t nc Fu
io ct n Fu
io ct n Fu
Act. Val. Ev.
ns io ct n Fu
ns
When?
© SAP AG 2006
Each environment contains a specific set of functions for the user to select in order to answer the questions shown above. You create a template using the functions in the individual cells. Each template can contain as many rows as are necessary. There are 3 different types of rows that can be created and combined in one template. Each type of row serves a different purpose. A Comment row is used for documentation. A Business Process row is used for process consumption by a cost object. A Subtemplate row is used to link templates for a nested template structure. A Calculation row can be used when multiple Business Process rows use the results of a single calculation (in the same template only). If the template is created in the SBP (Structured Business Process) environment, an additional TASK row type is available so that a cost center or activity type can be used in the "Object" column.
© SAP AG
AC400
7-222
Subenvironments as Function Groups PP production order
Subenvironment 101: Processes Functions:
Under what conditions?
...... ......
Subenvironment 103: Material Which process?
Functions: Material_Characteristic_value ......
When? Subenvironment 107: General data Which process quantity?
Functions:
...... ......
© SAP AG 2006
Each cost object in the system is permanently assigned to an environment. You cannot change these assignments. Each environment contains predefined subenvironments. This assignment is also fixed and cannot be changed. Each subenvironment contains a collection of specific functions that refer to the data in that particular subenvironment. For instance, a function designed to read the material characteristics assigned to a material in the material master is located in the Material subenvironment in the environment defined by the consuming cost object. The template, which is assigned to a specific environment when it is created, can access all the functions that are assigned to the subenvironments.
© SAP AG
AC400
7-223
Environments and Subenvironments New functions Optional
Standard Subenvironment 105: Routing
Environment 001: mat. c. est./ production orders
Subenvironment 103: Material
Environment 003: matl c. est. without quantity structure
Subenvironment 101: Sender process Environment PAC: costing-based profitability analysis
Subenvironment 107: General data
© SAP AG 2006
A subenvironment can be assigned to more than one environment, which means that the functions within the subenvironment are available to more than one type of cost object. For instance, the functions of the subenvironment that involve routings are available for sales orders and production orders, but not for cost estimates without a quantity structure. You can assign your own functions to either a subenvironment or an environment directly. Assigning functions to a subenvironment provides you with greater flexibility, because more than one type of cost object can use the available functions. In Customizing, you can restrict the use of each new function to a single cell in the template. Inside each cell, you can restrict how the function is used even further. By doing so, you can ensure that the functions are used effectively. For instance, if a function requires a material number as a parameter, only material number functions are made available.
© SAP AG
AC400
7-224
Function Modules as Functions
Functions Table field Material Master
ABAP-Functions View:MRP. 2
K_ABC_ORDER_MAT_CONFIRMATION
Procurement Storage location:
0001
Table name: MARC Field name:LGPRO
© SAP AG 2006
There are two different kinds of functions: table-field and ABAP functions. A table-field function allows a function to use fields from tables that have been allowed in the specific, shipped environments. An ABAP function is required if you need access to a field in a table that is not included in the specific, shipped environments. New functions must be created within the template environment area in Customizing. When you create new functions, you must observe the three-level naming convention that requires an external name, an internal name, and a logical function name. Functions can be copied, changed, and/or renamed.
© SAP AG
AC400
7-225
Template Allocation – Unit Summary:
z You can create your own allocation methods in
template allocation. z By doing so, you can implement your own
access types and cost calculations. z The allocation methods are realized by function
modules.
© SAP AG 2006
© SAP AG
AC400
7-226
Exercises Unit: Function Modules in Template Allocation
At the conclusion of this exercise, you will be able to: • Use function modules in template allocation
1-1
Program your own function module for template allocation 1-1-2 Analyze the storage conditions for material R-F100 in plant 1000 at storage location 002. Does a temperature condition exist? 1-1-3 Create a function module Y##WHENERGY that calculates and outputs the warehouse energy consumption for a specific material number, whose volume is measured in cubic meters, according to the following formula: energy = volume x 1000 x temperature condition 1-1-4 Before your function module Y##WHENERGY can be used in the template allocation, it must satisfy certain interface requirements. Find out what these requirements are. To do so, use SAP Library or analyze a function module that is already used in the template allocation.
1-2
Use your own function modules in the template allocation 1-2-1 First analyze the process costs in the cost estimate for material RF100. Which processes are involved and in what quantity? How is the output quantity maintained? 1-2-2 Create a Y##Energy_consumption function with the same logical function name in the "Materials" subenvironment in environment 001 (material cost estimate/production orders) . Assign your Y##WHENERGY function module to this function. On the "Usage" tab page for business processes, allow the function to calculate quantities. 1-2-3 Create a template Y##. In this template, the quantity of the business process 300901 ("Cooling") is calculated as a product of the warehouse energy consumption for the order material and the total material quantity for the order. 1-2-4 Add your template Y## to the template COPC-10 as a subtemplate. 1-2-5 Check the rate specified in annual planning for business process 300901 ("Cooling"). 1-2-6 Recalculate the cost of goods manufactured for material R-F100.
© SAP AG
AC400
7-227
© SAP AG
AC400
7-228
Solutions Unit: Function Modules in Template Allocation
1-1
© SAP AG
Program your own function module for template allocation 1-1-1 Analyze the storage conditions for material R-F100. Does a temperature condition exist? Which fields contain a temperature condition and volume? Start transaction MM03 by choosing Logistics → Materials Management → Material Master → Material → Display → Display Current Material R-F100 Pushbutton "Select (views)" Choose General Plant Data / Storage 1 Choose General Plant Data / Storage 2 Choose "Continue" Plant 1000 Storage location 0002 The "Plant Data / Stor. 1" tab page shows the temperature condition 01; the "Plant Data / Stor. 2" tab page shows the volume 0.75 M3. You can use the input help to display the "Technical Information" for a selected field. This information provides the names of the database fields. These fields are: Temperature conditions MARA-TEMPB Volume MARA-VOLUM Volume Unit MARA-VOLEH
AC400
7-229
1-1-2 Before your function module Y##WHENERGY can be used in the template allocation, it must satisfy certain interface requirements. Find out what these requirements are. To do so, use SAP Library or analyze a function module that is already used in the template allocation. You can find the interface conditions in SAP Library by choosing Financials → Controlling → Activity-Based Costing → Template → Environment of Templates → Implementing ABAP Functions. In the template allocation function in the system (transaction CTU6), you can find the "MaterialCharacteristicValue" function in the "Materials" subenvironment of environment 001 by choosing IMG → Controlling → Activity-Based Costing → Templates → Define Environments and Function Trees. This is assigned to the function module K_ABC_MATERIAL_FEATURE_VALUE and can be analyzed with transaction SE37, for example. 1-1-3 Create a function module Y##WHENERGY that calculates and outputs the warehouse energy consumption for a specific material number, whose volume is measured in cubic meters, according to the following formula: energy = volume x 1000 x temperature condition * The table parameter RTABLE_VAL of type TPLIC_RVAL_TAB * is defined in the type group TPLIC. This must be stored in the * top include in the following format: * TYPE-POOLS: tplic. FUNCTION Y##WHENERGY. *"--------------------------------------------------------------------*"*"Local interface: *" IMPORTING *" REFERENCE(ID_MATNR) TYPE MATNR *" REFERENCE(PERIOD_FROM) *" REFERENCE(PERIOD_CNT) *" REFERENCE(CALL_PROG) TYPE SY-REPID *" TABLES *" RTABLE_VAL TYPE TPLIC_RVAL_TAB *"--------------------------------------------------------------------* data DATA: DATA: DATA: DATA:
ls_mara ld_temp_faktor ld_quantity ld_wa_rval
TYPE TYPE TYPE TYPE
mara. i. tplic_rval-value. tplic_rval.
* Clear output CLEAR rtable_val[]. * Get master data SELECT SINGLE * FROM mara INTO ls_mara
© SAP AG
AC400
7-230
WHERE
matnr = id_matnr.
* Master record found? CHECK sy-subrc = 0. * Evaluate temperature CASE ls_mara-tempb. WHEN '01'. ld_temp_faktor = WHEN '02'. ld_temp_faktor = WHEN '03'. ld_temp_faktor = WHEN OTHERS. ENDCASE.
condition
1. 2. 3.
* Evaluate volume and determine result CASE ls_mara-voleh. WHEN 'M3'. ld_quantity = ls_mara-volum * 1000 * ld_temp_faktor. WHEN OTHERS. "nothing to do. ENDCASE. * if no periodic result, fill the result table for periods DO period_cnt TIMES. ld_wa_rval-period = period_from + sy-index - 1. ld_wa_rval-value = ld_quantity. APPEND ld_wa_rval TO rtable_val. ENDDO. ENDFUNCTION.
1-2
© SAP AG
1-1-4 Test your function module for material R-F100. Use your own function modules in the template allocation 1-2-1 First analyze the process costs in the cost estimate for material RF100. Which processes are involved and in what quantity? How is the output quantity maintained? To find the material cost estimate (transaction CK13N), choose Accounting → Controlling → Product Cost Controlling → Product Cost Planning → Material Costing → Cost Estimate with Quantity Structure → Display. Material R-F100 Plant 1000 Costing variant PPC1 The costing structure functions include the "Materials Only/All Items" pushbutton. You can use this pushbutton to expand the list to show all
AC400
7-231
cost items and, in particular, the list of processes. A process is allocated for the cost of goods manufactured: Process Number Quantity Work Scheduling 300900 1 pc 1-2-2 Create a Y##Energy_consumption function with the same logical function name in the "Materials" subenvironment in environment 001 (material cost estimate/production orders) . Assign your Y##WHENERGY function module to this function. On the "Usage" tab page for business processes, allow the function to calculate quantities. Start the template allocation function in the system (transaction CTU6) by choosing IMG → Controlling → Activity-Based Costing → Templates → Define Environments and Function Trees and select the "Materials" subenvironment in the object tree. Choose "Create Function" from the context menu. Function Y##Energy_consumption Radio button "Lower Level" Tab page "Basic Data" Log. Function Name Y##WHENERGY Tab page "Implementation" ABAP Function Name Y##WHENERGY Tab page "Usage" Tab page "All Columns" Select "Quantity Plan" in the "Business Process" row. Pushbutton "Save"
© SAP AG
AC400
7-232
1-2-3 Create a template Y##. In this template, the quantity of the business process 300901 ("Cooling") is calculated as a product of the warehouse energy consumption for the order material and the total material quantity for the order. Start the template allocation function (transaction CTU6) in the system by choosing IMG → Controlling → Activity-Based Costing → Templates → Maintain Templates and choose "Create Template: Template Y## Environment 001 Enter another row: Type "Business Process" Object "300901" Plan Quantity Double-click the field In the editor, enter: Y##Energy_consumption ( ID_MATNR = OrderMaterial ) * OrderTotalQuantity Pushbutton "Confirm Plan Quantity" Enter "ACTIVE" in the "Plan Activation" column. 1-2-4 Add your template Y## to the template COPC-10 as a subtemplate. Start the template allocation function (transaction CTU6) in the system by choosing IMG → Controlling → Activity-Based Costing → Templates → Maintain Templates and choose "Change Template": Template COPC-10 Environment 001 Enter another row: Pushbutton "Insert Row" Type "Subtemplate" Object Y## Plan Activation "ACTIVE"
© SAP AG
AC400
7-233
1-2-5 Check the rate specified in annual planning for business process 300901 ("Cooling"). Start transaction CP26 by choosing Accounting → Controlling → Activity-Based Costing → Planning → Process Quantities/Prices → Change Version 0 From Period: Current period To Period current period Fiscal Year Current fiscal year Pushbutton Overview Screen Make sure that a price has been defined. 1-2-6 Recalculate the cost of goods manufactured for material R-F100. You can find the material cost estimate (transaction CK13N) by choosing Accounting → Controlling → Product Cost Controlling → Product Cost Planning → Material Costing → Cost Estimate with Quantity Structure → Create Material R-F100 Plant 1000 Costing variant PPC1 The costing structure functions include the "Materials Only/All Items" pushbutton. You can use this pushbutton to expand the list to show all cost items and, in particular, the list of processes. Process "300901" here shows the quantity that was calculated using your function module.
© SAP AG
AC400
7-234
Appendix
z Optional exercise 1 – Write a program for maintaining customer address data z Optional Exercise 2 – Write a program for opening and closing FI periods z Optional exercise 3 – Program a report for master data groups in Cost Accounting
© SAP AG 2006
© SAP AG
AC400
8-235
© SAP AG
AC400
8-236
Optional Exercise F1 Write a Program for Maintaining Customer Address Data
At the conclusion of this exercise, you will be able to: • Create tables • Select records from tables and write to tables • Call function modules Requirement The following function is available for vendors and is also required for customers: Changes to addresses that are already known but will not take effect until a future date can be maintained in advance. This takes place in three steps: Future changes can be entered on a key-date basis using transaction MK12 (see path below). The planned changes can be viewed with transaction MK14. Changes that have been flagged for key dates can be activated with transactions MKH3 and MKH4. The paths are as follows: MK12 Logistics → Materials Management → Purchasing → Master Data → Vendor → Purchasing → Change (Planned) MK14 Logistics → Materials Management → Purchasing → Master Data → Vendor → Purchasing → Planned Changes MKH3 … → Vendor → Activate Planned Changes → Activation Online System Analysis Find out which tables store the customer master data. If necessary, use the ABAP Workbench or debugger to do so. Program Design The following functions are required to maintain the future customer address data: (a) The existing address data is modeled as a template for future changes in the form of a copy of the customer address data stored in a custom address table (b) There must be an option of maintaining the custom address table so that key-date based updates can be flagged. (c) The release of flagged updates is modeled in the form of a copy of the custom address data to the standard address data table. (d) It must be possible to reactivate the previous address data so that any update errors can be rectified. The custom address table is a copy of the standard address table ADRC with the name Y##ADRC. If the definition of table Y##ADRC allows data to be displayed and © SAP AG
AC400
8-237
maintained ("Delivery and Maintenance" tab page), you do not need to program the function listed under (b) because you can use transaction SE16 instead. In this case, write a program that offers three options: (a) "INITI" for modeling the function listed under (a) (b) "ACTIV" for modeling the function listed under (c) (c) "REACT" for modeling the function listed under (d) Task F1-1 Create table Y##ADRC as a copy of table ADRC. Allow table maintenance. F1-2
Create a domain Y##ACTION called "Action". The data type is CHAR and the number of characters 10. For the range, define three fixed values "INITI" with the description "Initialize", "ACTIV" with the description "Activate Changes", and "REACT" with the description "Undo Changes".
F1-3
Create a data element Y##ACTION with the name "Action". Assign the domain Y##ACTION to the data element.
F1-4
Create a Y##CUSTOMER program that contains the functions of the actions.
© SAP AG
AC400
8-238
Solution for Optional Exercise F1 Write a Program for Maintaining Customer Address Data
Requirement The following function is available for vendors and is also required for customers: Changes to addresses that are already known but will not take effect until a future date can be maintained in advance. This takes place in three steps: Future changes can be entered on a key-date basis using transaction MK12 (see path below). The planned changes can be viewed with transaction MK14. Changes that have been flagged for key dates can be activated with transactions MKH3 and MKH4. The paths are as follows: MK12 Logistics → Materials Management → Purchasing → Master Data → Vendor → Purchasing → Change (Planned) MK14 Logistics → Materials Management → Purchasing → Master Data → Vendor → Purchasing → Planned Changes MKH3 … → Vendor → Activate Planned Changes → Activation Online System Analysis Find out which tables store the customer master data. If necessary, use the ABAP Workbench or debugger to do so. Program Design The following functions are required to maintain the future customer address data: (a) The existing address data is modeled as a template for future changes in the form of a copy of the customer address data stored in a custom address table (b) There must be an option of maintaining the custom address table so that key-date based updates can be flagged. (c) The release of flagged updates is modeled in the form of a copy of the custom address data to the standard address data table. (d) It must be possible to reactivate the previous address data so that any update errors can be rectified. The custom address table is a copy of the standard address table ADRC with the name Y##ADRC. If the definition of table Y##ADRC allows data to be displayed and maintained ("Delivery and Maintenance" tab page), you do not need to program the function listed under (b) because you can use transaction SE16 instead. In this case, write a program that offers three options: (a) "INITI" for modeling the function listed under (a) (b) "ACTIV" for modeling the function listed under (c)
© SAP AG
AC400
8-239
(c) "REACT" for modeling the function listed under (d) Task F1-1 Create table Y##ADRC as a copy of table ADRC. Allow table maintenance. Tools → ABAP Workbench → Development → ABAP Dictionary (SE11) Select Database table Function
"Database table" ADRC "Copy"
From Table To Table
ADRC Y##ADRC
Function
“Local Object”
Tools → ABAP Workbench → Development → ABAP Dictionary (SE11) Select Database table Function
"Database table" Y##ADRC “Change”
Tab page Date Browser…
"Delivery and Maintenance" X Display/Maintenance Allowed
Function
F1-2
"Activate"
Create a domain Y##ACTION called "Action". The data type is CHAR and the number of characters 10. For the range, define three fixed values "INITI" with the description "Initialize", "ACTIV" with the description "Activate Changes", and "REACT" with the description "Undo Changes". Tools → ABAP Workbench → Development → ABAP Dictionary
(SE11)
© SAP AG
Select Domain Function
"Domain" Y##ACTION "Create"
Short description Tab page Data Type No. Characters
Action for program Y##Customer "Definition" "CHAR" 10
Tab page Fixed Value
"Value Range" INITI
AC400
8-240
Short Text Fixed Value Short Text Fixed Value Short Text
Initialize ACTIV Activate changes REACT Undo changes
Function Function F1-3
"Activate" “Local Object”
Create a data element Y##ACTION with the name "Action". Assign the domain Y##ACTION to the data element. Tools → ABAP Workbench → Development → ABAP Dictionary
(SE11) Select Data Type Function
"Data Type" Y##ACTION "Create"
Select
"Data Element"
Short Text Tab page Select Select Domain
Action for program Y##Customer "Data Type" "Elementary Type" "Domain" Y##ACTION
Tab page Short label Medium Long label Heading
"Field Label" Action Action Action Action
label
Function Function F1-4
"Activate" "Local Object"
Create a Y##CUSTOMER program that contains the functions of the actions. You can create the message of class AC400 with the number 600 in the same way as described for program Y##CUSTOMER. As soon as you have created the program (as described below), you can maintain the selection texts in the editor menu under Goto → Text Elements → Selection Texts by referencing the Data Dictionary. Tools → ABAP Workbench → Overview → Object Navigator
© SAP AG
AC400
8-241
View Local objects
Local objects AC400-##
Select the rood node $TMP AC400-## Context menu Create → Program Program
Y##CUSTOMER (without top
Title Type Function Function
Maintain future customer master data "1 Executable Program" "Save" "Local Object"
include)
In the proposed solution, we will use "AC400" instead of "Y##".
*&--------------------------------------------------------------------*& Report AC400CUSTOMER *& *&---------------------------------------------------------------------* *& *& *&---------------------------------------------------------------------* REPORT
ac400customer.
* Tables TABLES: kna1. * Parameters PARAMETERS: p_date TYPE date_from DEFAULT sy-datum NO-DISPLAY. SELECT-OPTIONS: r_kunnr FOR kna1-kunnr. PARAMETERS: p_action TYPE ac400action. * Types TYPES: yt_kunnr LIKE TABLE OF r_kunnr. TYPES: yt_kna1 TYPE TABLE OF kna1. TYPES: ys_kna1 TYPE kna1. TYPES: ys_adrc TYPE adrc. TYPES: yt_adrc TYPE TABLE OF ys_adrc. TYPES: ys_ac400adrc TYPE ac400adrc. TYPES: yt_ac400adrc TYPE TABLE OF ys_ac400adrc. * Constants CONSTANTS: gc_first_date CONSTANTS: gc_last_date
© SAP AG
LIKE sy-datum VALUE '00010101'. LIKE sy-datum VALUE '99991231'.
AC400
8-242
CONSTANTS: gc_empty_nation TYPE ad_nation VALUE IS INITIAL. * Call the main program PERFORM main USING p_date r_kunnr[] p_action. *&---------------------------------------------------------------------* *& Form main *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * -->P_P_DATE text * -->P_R_KUNNR[] text * -->P_P_ACTION text *----------------------------------------------------------------------* FORM main USING id_date LIKE sy-datum it_kunnr TYPE yt_kunnr id_action TYPE ac400action. * data DATA: lt_kna1 TYPE yt_kna1. DATA: ls_kna1 TYPE ys_kna1. DATA: ld_answer TYPE char3. * Authorization check CALL FUNCTION 'Y_AC400AUTHORITY' IMPORTING ed_answer = ld_answer. CASE ld_answer. WHEN 'IES'. "ok WHEN OTHERS. MESSAGE e600(f1) WITH sy-uname text-001. ENDCASE. * select from kna1 SELECT * FROM kna1 INTO TABLE lt_kna1 WHERE kunnr IN it_kunnr[]. * insert ykna1 LOOP AT lt_kna1 INTO ls_kna1. *
*
Evaluate according to action CASE p_action. Initialize WHEN 'INITI'. PERFORM initialize
© SAP AG
AC400
8-243
USING
p_date ls_kna1.
*
Activate WHEN 'ACTIV'. PERFORM activate USING p_date ls_kna1.
*
Reactivate WHEN 'REACT'. PERFORM react USING p_date ls_kna1.
*
Undefined input WHEN OTHERS. MESSAGE ID 'AC400' TYPE 'E' NUMBER '600' WITH 'Choose a valid action". ENDCASE. WRITE: / 'Vendor', ls_kna1-kunnr, 'has been maintained'.
ENDLOOP. ENDFORM.
" main
*&---------------------------------------------------------------------* *& Form initialize *&---------------------------------------------------------------------* FORM initialize USING id_date TYPE date_from is_kna1 TYPE ys_kna1. * data DATA: ls_adrc TYPE ys_adrc. DATA: ls_yadrc TYPE ys_ac400adrc. SELECT SINGLE * FROM adrc INTO ls_adrc WHERE addrnumber AND date_from AND nation
= is_kna1-adrnr = gc_first_date = gc_empty_nation.
* Delete existing entries DELETE FROM ac400adrc WHERE addrnumber = is_kna1-adrnr. * Insert new from kna1 MOVE-CORRESPONDING ls_adrc TO ls_yadrc. ls_yadrc-date_from = id_date. INSERT ac400adrc FROM ls_yadrc. ENDFORM.
© SAP AG
" initialize
AC400
8-244
*&---------------------------------------------------------------------* *& Form activate *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * -->P_ID_DATE text * -->P_LS_KUNNR text *----------------------------------------------------------------------* FORM activate USING id_date TYPE date_from is_kna1 TYPE ys_kna1. * data DATA: DATA: DATA: DATA:
ls_adrc ls_ac400adrc ls_adrc_old ls_adrc_new
TYPE TYPE TYPE TYPE
ys_adrc. ys_ac400adrc. ys_adrc. ys_adrc.
SELECT SINGLE * FROM adrc INTO ls_adrc WHERE addrnumber AND date_from AND nation
= is_kna1-adrnr = gc_first_date = gc_empty_nation.
SELECT SINGLE * FROM ac400adrc INTO ls_ac400adrc WHERE addrnumber = is_kna1-adrnr AND date_from = id_date AND nation = gc_empty_nation. IF sy-subrc = 0. *
init ls_kna1_new MOVE-CORRESPONDING ls_ac400adrc TO ls_adrc_new. ls_adrc_new-date_from = gc_first_date.
*
Update customers UPDATE adrc FROM ls_adrc_new.
*
Archive previous entry ls_adrc_old = ls_adrc. ls_adrc_old-date_from = id_date - 1. ls_adrc_old-date_to = id_date - 1. MODIFY adrc FROM ls_adrc_old. ELSE. "nothing to do ENDIF.
ENDFORM.
© SAP AG
" activate
AC400
8-245
*&---------------------------------------------------------------------* *& Form react *&---------------------------------------------------------------------* FORM react USING id_date TYPE date_from is_kna1 TYPE ys_kna1. * data DATA: DATA: DATA: DATA:
ls_adrc_r ls_adrc_f lt_adrc ld_len
SELECT FROM INTO TABLE WHERE AND AND
TYPE TYPE TYPE LIKE
ys_adrc. ys_adrc. yt_adrc. sy-tabix.
* adrc lt_adrc addrnumber date_from nation
= is_kna1-adrnr 0. *
*
Incorrect sentence LOOP AT lt_adrc INTO ls_adrc_f WHERE date_from = gc_first_date. EXIT. ENDLOOP. ls_adrc_f-date_from = id_date - 1. ls_adrc_f-date_to = id_date - 1. MODIFY adrc FROM ls_adrc_f. Correct sentence READ TABLE lt_adrc INDEX ld_len INTO ls_adrc_r. ls_adrc_r-date_from = gc_first_date. ls_adrc_r-date_to = gc_last_date. MODIFY adrc FROM ls_adrc_r. ENDIF.
ENDFORM.
© SAP AG
" react
AC400
8-246
Optional Exercise F2 Write a Program for Opening and Closing FI Periods
At the conclusion of this exercise, you will be able to: • Create tables • Select records from tables and write to tables • Call function modules • Display data records • Evaluate pushbuttons pressed by the user Requirement In Customizing for Accounting, periods can be opened or closed for posting. The relevant path is: IMG → Financial Accounting → Financial Accounting Global Settings → Document → Posting Periods For selected variants, you want the open periods interval to be shifted by one period on a recurring key date (such as the end of the month). Assume that today is April 1 and this is our key date. The periods open for posting up to now are February and March. As of today, March and April are open for posting. System Analysis Find out which table contains the interval for open periods. If necessary, use the ABAP Workbench or debugger to do so. Program Design The following objects are required to maintain the future customer address data: (a) A custom table containing an (optional) key date for each period interval (b) A program with the variant of the posting periods as a parameter. When called, it determines the corresponding key date for the entered period interval variant. If the key date has been exceeded, the period interval is shifted by one period. Before the data is saved, the current and new statuses are displayed. Task Implement the above requirement. Your custom table is Y##T001B. Your program for maintaining the posting periods is Y##PV.
© SAP AG
AC400
8-247
© SAP AG
AC400
8-248
Solution for Optional Exercise F2 Write a Program for Opening and Closing FI Periods
Requirement In Customizing for Accounting, periods can be opened or closed for posting. The relevant path is: IMG → Financial Accounting → Financial Accounting Global Settings → Document → Posting Periods For selected variants, you want the open periods interval to be shifted by one period on a recurring key date (such as the end of the month). Assume that today is April 1 and this is our key date. The periods open for posting up to now are February and March. As of today, March and April are open for posting. System Analysis Find out which table contains the interval for open periods. If necessary, use the ABAP Workbench or debugger to do so. For example, call the transaction for maintaining the open periods: IMG → Financial Accounting → Financial Accounting Global Settings → Document → Posting Periods → Open and Close Posting Periods Select the first variant ("0001"). Press F1. Choose the "Technical Information" pushbutton. The referenced table is "V_T001B" (this is actually a table view). You can use the Data Dictionary (SE11) to take a look at this view. The table referenced in view V_T001B is T001B. The entries in table T001B (which you can view with SE16) are those that are proposed for maintenance in Customizing for open periods. Program Design The following objects are required to maintain the future customer address data: (a) A custom table containing an (optional) key date for each period interval (b) A program with the variant of the posting periods as a parameter. When called, it determines the corresponding key date for the entered period interval variant. If the key date has been exceeded, the period interval is shifted by one period. Before the data is saved, the current and new statuses are displayed. Task Implement the above requirement. Your custom table is Y##T001B. Your program for maintaining the posting periods is Y##PV.
© SAP AG
AC400
8-249
For more information on how to create a program and tables, refer to the solution for the task "Write a Program for Maintaining Customer Address Data". *&---------------------------------------------------------------------* *& Report AC400PV *& *&---------------------------------------------------------------------* * The custom table ac400t001b referenced in the report is * activated for maintenance and belongs to delivery class c. * The technical settings are data type APPL2 and * size category 0. * The table has the following structure: * Field Key Data element Data type Length * Mandt x Mandt * Rrcty x Rrcty * Opvar x Opvar * Mkoar x Mkoar * Key date Numc 2 * * * *
Status 1000 referenced in the report uses the functions of the function keys: SAVE for save ENTR for continue
REPORT
ac400pv.
* Types TYPES: ys_t001b TYPES: yt_t001b TYPES: ys_ac400t001b TYPES: yt_ac400t001b
TYPE TYPE TYPE TYPE
t001b. TABLE OF ys_t001b. ac400t001b. TABLE OF ys_ac400t001b.
* Parameters PARAMETERS: p_opvar TYPE opvar OBLIGATORY. * Data DATA: ls_t001 DATA: ls_t001b_old DATA: ls_t001b_new DATA: lt_t001b_old DATA: lt_t001b_new DATA: ls_ac400t001b DATA: lt_ac400t001b DATA: ld_result DATA: ld_day_found
TYPE TYPE TYPE TYPE TYPE TYPE TYPE TYPE TYPE
t001. ys_t001b. ys_t001b. yt_t001b. yt_t001b. ys_ac400t001b. yt_ac400t001b. c. c.
* Set status SET PF-STATUS '1000'. * Load T001b with the open periods for selected variant PERFORM load_t001b USING p_opvar CHANGING lt_t001b_old.
© SAP AG
AC400
8-250
* Load ac400t001b with the key dates for selected variant PERFORM load_ac400t001b USING p_opvar CHANGING lt_ac400t001b. * Load Periv from reference company code for variant PERFORM load_periv USING p_opvar CHANGING ls_t001. * Edit the records for the variant LOOP AT lt_t001b_old INTO ls_t001b_old. * Restrict table ac400t001b depending on t001b record PERFORM get_day USING lt_ac400t001b ls_t001b_old CHANGING ls_ac400t001b ld_day_found. * Depending on key date maintenance CASE ld_day_found. *
Key date maintained WHEN 'Y'.
*
Key date reached? PERFORM check_day USING ls_t001 ls_ac400t001b ls_t001b_old CHANGING ld_result.
*
Branch according to ld_result CASE ld_result.
*
Key date reached => maintain periods WHEN 'Y'.
*
Calculate Customizing PERFORM calc_t001b USING ls_t001 ls_t001b_old CHANGING ls_t001b_new.
*
Display Customizing PERFORM show_t001b USING ls_t001b_old ls_t001b_new. APPEND ls_t001b_new TO lt_t001b_new.
© SAP AG
AC400
8-251
*
Key date NOT reached WHEN 'N'.
*
Undefined WHEN OTHERS. ENDCASE.
*
Key date not maintained WHEN OTHERS. "nothing to do
ENDCASE. ENDLOOP. * at user-command AT USER-COMMAND. PERFORM do_ucomm USING sy-ucomm lt_t001b_new. *&---------------------------------------------------------------------* *& Form load_t001b *&---------------------------------------------------------------------* FORM load_t001b USING id_opvar TYPE opvar CHANGING et_t001b TYPE yt_t001b. * Clear output CLEAR et_t001b. * data DATA: ld_empty_bkont TYPE bkont_001b. * select SELECT FROM * INTO INTO TABLE WHERE AND * AND * AND
* t001b es_t001b et_t001b rrcty = '0' bukrs = id_opvar. mkoar = '+' bkont = ld_empty_bkont.
ENDFORM.
" load_t001b
*&---------------------------------------------------------------------* *& Form load_ac400t001b *&---------------------------------------------------------------------* FORM load_ac400t001b USING id_opvar TYPE opvar CHANGING et_ac400t001b TYPE yt_ac400t001b. * Clear output
© SAP AG
AC400
8-252
CLEAR et_ac400t001b[]. * Select SELECT FROM INTO TABLE WHERE AND
* ac400t001b et_ac400t001b opvar = id_opvar rrcty = '0'.
ENDFORM.
" load_ac400t001b
*&---------------------------------------------------------------------* *& Form load_periv *&---------------------------------------------------------------------* FORM load_periv USING id_opvar TYPE opvar CHANGING es_t001 TYPE t001. * Clear output CLEAR es_t001. * get priv SELECT * FROM t001 INTO es_t001 WHERE opvar = id_opvar. EXIT. ENDSELECT. ENDFORM.
" load_periv
*&---------------------------------------------------------------------* *& Form get_day *&---------------------------------------------------------------------* FORM get_day USING it_ac400t001b TYPE yt_ac400t001b is_t001b TYPE ys_t001b CHANGING es_ac400t001b TYPE ys_ac400t001b ed_day_found TYPE c. * Clear output CLEAR es_ac400t001b. ed_day_found = 'N'. * Get sentence LOOP AT it_ac400t001b INTO es_ac400t001b WHERE opvar = is_t001b-bukrs AND mkoar = is_t001b-mkoar AND rrcty = is_t001b-rrcty. ed_day_found = 'Y'. ENDLOOP.
© SAP AG
AC400
8-253
ENDFORM.
" get_day
*&---------------------------------------------------------------------* *& Form check_day *&---------------------------------------------------------------------* FORM check_day USING is_t001 TYPE t001 is_ac400t001b TYPE ys_ac400t001b is_t001b TYPE ys_t001b CHANGING ed_result TYPE c. * Clear output CLEAR ed_result. * data DATA: DATA: DATA: DATA:
ld_systemday ld_actbuper ld_actgjahr ld_check
TYPE TYPE TYPE TYPE
n LENGTH 2. poper. bdatj. i.
* Determine current date ld_systemday = sy-datum+6(2). * Get current period CALL FUNCTION 'DATE_TO_PERIOD_CONVERT' EXPORTING i_date = sy-datum i_periv = is_t001-periv IMPORTING e_buper = ld_actbuper e_gjahr = ld_actgjahr. * 1.) Check whether key date exceeded IF ld_systemday >= is_ac400t001b-stichtag. ld_result = ld_result + 1. ENDIF. * 2.) Check whether set period < current period IF is_t001b-tope1 < ld_actbuper AND is_t001b-toye1 = ld_actgjahr. ld_result = ld_result + 1. * 3.) Check whether set year < today ELSEIF is_t001b-toye1 < ld_actgjahr. ld_result = ld_result + 1. ENDIF. IF ld_result = 2. ed_result = 'Y'. ELSE. ed_result = 'N'. ENDIF. ENDFORM.
© SAP AG
" check_day
AC400
8-254
*&---------------------------------------------------------------------* *& Form calc_t001b *&---------------------------------------------------------------------* FORM calc_t001b USING is_t001 TYPE t001 is_t001b_old TYPE ys_t001b CHANGING es_t001b_new TYPE ys_t001b. * set output es_t001b_new = is_t001b_old. * Define new start period CALL FUNCTION 'CKML_F_GET_NEXT_PERIOD' EXPORTING input_period = is_t001b_old-frpe1 input_year = is_t001b_old-frye1 input_periv = is_t001-periv IMPORTING next_period = es_t001b_new-frpe1 next_year = es_t001b_new-frye1. * Define new target period CALL FUNCTION 'CKML_F_GET_NEXT_PERIOD' EXPORTING input_period = is_t001b_old-tope1 input_year = is_t001b_old-toye1 input_periv = is_t001-periv IMPORTING next_period = es_t001b_new-tope1 next_year = es_t001b_new-toye1. ENDFORM.
" calc_t001b
*&---------------------------------------------------------------------* *& Form show_t001b *&---------------------------------------------------------------------* FORM show_t001b USING is_t001b_old TYPE ys_t001b is_t001b_new TYPE ys_t001b. WRITE:/ is_t001b_old-mkoar. * Output first line with current status WRITE:/ text-001, "Current open periods is_t001b_old-frpe1, is_t001b_old-frye1, '-', is_t001b_old-tope1, is_t001b_old-toye1. * Output second line with new status WRITE:/ text-002, "Open periods from now on is_t001b_new-frpe1,
© SAP AG
AC400
8-255
is_t001b_new-frye1, '-', is_t001b_new-tope1, is_t001b_new-toye1. WRITE:/. ENDFORM.
" show_t001b
*&---------------------------------------------------------------------* *& Form do_ucomm *&---------------------------------------------------------------------* FORM do_ucomm USING id_ucomm LIKE sy-ucomm it_t001b TYPE yt_t001b. CASE id_ucomm. WHEN 'ENTR'. "nothing to do. WHEN 'SAVE'. PERFORM save USING it_t001b. LEAVE SCREEN. WHEN OTHERS. LEAVE SCREEN. ENDCASE. ENDFORM.
" do_ucomm
*&---------------------------------------------------------------------* *& Form save *&---------------------------------------------------------------------* FORM save USING it_t001b TYPE yt_t001b. UPDATE t001b FROM TABLE it_t001b.
ENDFORM.
© SAP AG
" save
AC400
8-256
Optional Exercise F3 Program a Report for Master Data Groups in Cost Accounting
At the conclusion of this exercise, you will be able to: • Select records from tables and display them with the ALV • Use custom containers • Use the PBO and PAI dialog programming events to modify your user interface • Define and evaluate required entry fields • Define a transaction for calling your report Requirement In Cost Accounting, you can group cost centers, cost elements, internal orders, and so on. You want to program a report that lists these groups. The report should display both the selection parameters and the results list on one screen. The group type (cost center, cost element, and so on) and also the name of the object should be available as selection parameters. The group type should be a required entry. If only the type is entered, all groups of this type should be listed. The second parameter can be used to filter out a specific element of this type. Depending on the selected type, the description of the field should change for positioning purposes: Initial call: Set class Set ID
___________ ____________
Results list empty After 0102 has been entered as the set class, the screen should change to: Set class 0102 Cost element group ____________ Results list contains all cost element groups System Analysis Found out which table stores the master data groups. If necessary, use the ABAP Workbench or debugger to do so.
Task Implement the above requirement. Your program Y##SET is part of your local objects.
© SAP AG
AC400
8-257
© SAP AG
AC400
8-258
Solution for Optional Exercise F3 Program a Report for Master Data Groups in Cost Accounting Requirement In Cost Accounting, you can group cost centers, cost elements, internal orders, and so on. You want to program a report that lists these groups. The report should display both the selection parameters and the results list on one screen. The group type (cost center, cost element, and so on) and also the name of the object should be available as selection parameters. The group type should be a required entry. If only the type is entered, all groups of this type should be listed. The second parameter can be used to filter out a specific element of this type. Depending on the selected type, the description of the field should change for positioning purposes: Initial call: Set class Set ID
___________ ____________
Results list empty After 0102 has been entered as the set class, the screen should change to: Set class 0102 Cost element group ____________ Results list contains all cost element groups Finally, the program should be executable via a transaction. System Analysis Found out which table stores the master data groups. If necessary, use the ABAP Workbench or debugger to do so. Use the transaction, for example, to display the cost element groups (KAH1). After you have entered the cost element group OAL on the initial screen, use the /h command to activate the debugger before you release the data. In debugger mode, set a breakpoint for the "SELECT" command to analyze the further table accesses. Check the tables at which the debugger stops by listing their entries, for example. The table containing the cost element groups must be included in the accesses. Task Implement the above requirement. Your program Y##SET is part of your local objects. Your transaction is Y##SET and is also defined locally.
© SAP AG
AC400
8-259
Instructions on how to use the Program Editor and define screens are provided in the exercise on maintaining customer address data. Once you have created the program (see template below), define a transaction. You can create transactions in the same way as programs using the Object Navigator (SE80). When you define the transaction Y##Set, select "Program and Selection Screen (Report Transaction)" as the initial object. Enter your program Y##SET with selection screen "1000". *&---------------------------------------------------------------------* *& Report AC400SET *& *&---------------------------------------------------------------------* * Screen 1000 referenced in the report has the following settings *Properties *Maintenance 200 240 * *Element list *Name Type Row Column Def.L. Vis.L. Hght Scrollable Format *SETHEADER-SETCLASS Text 1 1 22 22 1 *SETHEADER-SETCLASS I/O 1 26 4 4 1 CHAR *GD_SETCLSTEXT I/O 2 1 22 22 1 CHAR *SETHEADER-SETNAME I/O 2 26 24 24 1 CHAR *ALV CuCtr 4 1 240 240 197 * * Element list (continued) *Name Inp. Outp. Outp Only. Dict Fld *SETHEADER-SETCLASS x *SETHEADER-SETCLASS x x x *GD_SETCLSTEXT x x *SETHEADER-SETNAME x x x *ALV * * Element list (special attributes and display attributes) *Name Input Two-dimensional As desc. left *SETHEADER-SETCLASS x *SETHEADER-SETCLASS O obl. *GD_SETCLSTEXT N n. poss. x *SETHEADER-SETNAME poss. *ALV * *Flow logic *process before output. * ** Set status * module status_1000. * ** Adjust field name and list * module adjust_window. ** *process after input. ** Call following module at "CANC"
© SAP AG
AC400
8-260
* module user_command_1000 at exit-command. * ** Also with all other commands * module user_command_1000. * * * * *
Status 1000 has the following properties Function keys Green arrow BACK Yellow arrow EXIT Red cross CANC (defined as exit command)
* Title 1000 is "Master Data Groups" REPORT
ac400set.
*Referenced tables TABLES: setheader. *Types for master data groups TYPES: ys_setheader TYPE setheader. TYPES: yt_setheader TYPE TABLE OF ys_setheader. *Data declaration. DATA: gt_outtab DATA: gd_setclstext DATA: go_container DATA: go_alv
TYPE TYPE TYPE TYPE
yt_setheader. setclstext. REF TO cl_gui_custom_container. REF TO cl_gui_alv_grid.
*Data instantiation CREATE OBJECT go_container EXPORTING repid = sy-repid dynnr = '1000' container_name = 'ALV'. CREATE OBJECT go_alv EXPORTING i_parent = go_container. *Call dialog box CALL SCREEN 1000. *&---------------------------------------------------------------------* *& Module USER_COMMAND_1000 INPUT *&---------------------------------------------------------------------* MODULE user_command_1000 INPUT. * Evaluation of pushbutton pressed by user CASE sy-ucomm. *
Other or undefined WHEN 'ENTR' OR ' '. PERFORM set_selection_status USING setheader CHANGING gt_outtab.
© SAP AG
AC400
8-261
*
*
Other commands WHEN OTHERS. Exit the transaction SET SCREEN 0. LEAVE SCREEN. ENDCASE.
ENDMODULE. " USER_COMMAND_1000 INPUT *&---------------------------------------------------------------------* *& Module STATUS_1000 OUTPUT *&---------------------------------------------------------------------* MODULE status_1000 OUTPUT. SET PF-STATUS '1000'. SET TITLEBAR '1000'. ENDMODULE. " STATUS_1000 OUTPUT *&---------------------------------------------------------------------* *& Form set_selection_status *&---------------------------------------------------------------------* * This routine determines the status of the selection parameters. * Possible statuses: * UNDEF no selection parameters provided * IDENT already selected with selection parameter * FIRST first selection call * NEW further selection call with new parameters FORM set_selection_status USING is_setheader TYPE setheader CHANGING ct_outtab TYPE yt_setheader. * data DATA: ls_empty_setheader TYPE ys_setheader. STATICS: ls_old_setheader TYPE ys_setheader. DATA: ld_status TYPE string. * Evaluate entered parameters and set status CASE is_setheader. *
Undefined/empty parameters WHEN ls_empty_setheader. ld_status = 'UNDEF'.
*
Unchanged parameters WHEN ls_old_setheader. ld_status = 'IDENT'.
*
Selection parameters not used WHEN OTHERS.
*
First time IF ls_old_setheader = ls_empty_setheader.
© SAP AG
AC400
8-262
ld_status = 'FIRST'. *
Change ELSE. ld_status = 'NEW'. ENDIF.
*
get data PERFORM get_data USING is_setheader CHANGING ct_outtab.
*
Update ls_old_setheader ls_old_setheader = is_setheader. ENDCASE.
* Remember PERFORM USING CHANGING
status remind_status 'SET' ld_status.
ENDFORM. " set_selection_status *&---------------------------------------------------------------------* *& Form get_data *&---------------------------------------------------------------------* FORM get_data USING is_setheader TYPE ys_setheader CHANGING et_outtab TYPE yt_setheader. * Clear output CLEAR et_outtab[]. * data DATA: ld_empty_setname LIKE setheader-setname. * Select according to set ID CASE is_setheader-setname. *
*
All objects WHEN ld_empty_setname. SELECT * FROM setheader INTO TABLE et_outtab WHERE setclass = is_setheader-setclass. One object WHEN OTHERS. SELECT * FROM setheader INTO TABLE et_outtab WHERE setname = is_setheader-setname AND setclass = is_setheader-setclass. ENDCASE.
© SAP AG
AC400
8-263
ENDFORM. " get_data *&---------------------------------------------------------------------* *& Module adjust_window OUTPUT *&---------------------------------------------------------------------* MODULE adjust_window OUTPUT. PERFORM adjust_window USING gt_outtab setheader CHANGING gd_setclstext. ENDMODULE. " adjust_window OUTPUT *&---------------------------------------------------------------------* *& Form adjust_window *&---------------------------------------------------------------------* FORM adjust_window USING it_outtab TYPE yt_setheader is_setheader TYPE ys_setheader CHANGING cd_setclstext TYPE setclstext. * data DATA: ld_status TYPE string. * set ld_status PERFORM remind_status USING 'GET' CHANGING ld_status. * Evaluate status CASE ld_status. * *
Undefined WHEN 'UNDEF'. Maintain cd-setclstext PERFORM get_setclstext USING is_setheader CHANGING cd_setclstext.
*
Existing selection WHEN 'IDENT'. "nothing to do
*
First selection WHEN 'FIRST'.
*
Generate ALV CALL METHOD go_alv->set_table_for_first_display EXPORTING i_structure_name = 'SETHEADER' CHANGING it_outtab = gt_outtab.
*
Maintain cd_setclstext PERFORM get_setclstext USING is_setheader
© SAP AG
AC400
8-264
CHANGING cd_setclstext. *
*
*
New other selection WHEN 'NEW'. CALL METHOD go_alv->refresh_table_display. Maintain PERFORM USING CHANGING
cd_setclstext get_setclstext is_setheader cd_setclstext.
WHEN OTHERS. Maintain cd_setclstext PERFORM get_setclstext USING is_setheader CHANGING cd_setclstext. ENDCASE.
ENDFORM. "adjust_window *&---------------------------------------------------------------------* *& Form remind_status *&---------------------------------------------------------------------* * This routine stores the status of selection parameters and * returns them on request. * PBO and PAI communicate via this routine * The following actions are possible: * SET: Remember status * GET: Return status FORM remind_status USING id_action TYPE string CHANGING cd_status TYPE string. * data STATICS: ld_status TYPE string. * Evaluate action CASE id_action. * Set status WHEN 'SET'. ld_status = cd_status. *
Read status WHEN 'GET'. cd_status = ld_status. ENDCASE.
ENDFORM. "remind_status *&---------------------------------------------------------------------* *& Form get_setclstext *&---------------------------------------------------------------------* FORM get_setclstext
© SAP AG
AC400
8-265
USING is_setheader TYPE ys_setheader CHANGING ed_setclstext TYPE setclstext. * Clear output CLEAR ed_setclstext. * data DATA: ls_setclst TYPE setclst. DATA: ld_empty_setclass TYPE setclst. DATA: ls_dd04v_wa TYPE dd04v. * Processing according to is_setheader-setclass. CASE is_setheader-setclass. *
Class not set WHEN ld_empty_setclass. CALL FUNCTION 'DDIF_DTEL_GET' EXPORTING name = 'SETNAMENEW' langu = sy-langu IMPORTING dd04v_wa = ls_dd04v_wa.
* set output ed_setclstext = ls_dd04v_wa-ddtext.
*
Class set WHEN OTHERS. * select SELECT SINGLE * FROM setclst INTO ls_setclst WHERE langu = sy-langu AND setclass = is_setheader-setclass. * set output ed_setclstext = ls_setclst-descript. ENDCASE.
ENDFORM.
© SAP AG
" get_setclstext
AC400
8-266
View more...
Comments