266
THE BEST-RUN BUSINESSES RUN SAP © SAP AG 2006 AC400 Programming in Financials AC400 Programming in Financials mySAP ERP 2005 Financial Analytics 2006/Q2 Material number: 5008 0584

AC400 Programming in Financials

Embed Size (px)

Citation preview

Page 1: AC400 Programming in Financials

© SAP AG 2006

AC400 Programming in Financials

THE BEST-RUN BUSINESSES RUN SAP

© SAP AG 2006

AC400Programming in Financials

AC400 Programming in Financials

mySAP ERP 2005 Financial Analytics 2006/Q2 Material number: 5008 0584

Page 2: AC400 Programming in Financials

© SAP AG 2006

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.

Copyright

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.

Page 3: AC400 Programming in Financials

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 SAP-Konzern ü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.

Page 4: AC400 Programming in Financials

© SAP AG 2006

Required:

Basic knowledge of programming

Recommended

AC010 – Business Processes in Financial Accounting

AC040 – Business Processes in Management Accounting (Controlling)

BC400 – ABAP Workbench Basics

Course Prerequisites

Note to participants 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.

Page 5: AC400 Programming in Financials

© SAP AG 2006

Participant

Members of financial accounting departments or system administrators who deal with tasks that cover a range of subjects

Consultants

Duration

Three days

Target Group

Page 6: AC400 Programming in Financials
Page 7: AC400 Programming in Financials

© SAP AG AC400 1-7

© SAP AG 2006

Course Goals

Course Objectives

Course Contents

Overview Diagram

Overview of the Exercises

Contents:

Course Overview

Page 8: AC400 Programming in Financials

© SAP AG AC400 1-8

© SAP AG 2006

This course will prepare you to:

Perform technical programming-related tasks for the Accounting departments, above all to

analyze existing programs

create your own programs and reports

Course Goals

Page 9: AC400 Programming in Financials

© SAP AG AC400 1-9

© SAP AG 2006

Course Objectives

Use the development tools of the ABAP Workbench

Analyze and debug Accounting programs

Create function modules

Enable database access

Implement your own ALV reports

Define authorization checks

Develop and incorporate extractors

At the end of this course, you will be able to:

Page 10: AC400 Programming in Financials

© SAP AG AC400 1-10

© SAP AG 2006

Course Content

Unit 1 Overview

Unit 2 The ABAP Workbench

Unit 3 First Attempts at Programming

Unit 4 Dialogs and ALV Reports

Preface

Unit 5 Customer Enhancements

Unit 6 Extraction

Unit 7 Template Allocation

Appendix Self-Study Exercises

Page 11: AC400 Programming in Financials

© SAP AG AC400 1-11

© SAP AG 2006

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

Page 12: AC400 Programming in Financials

© SAP AG AC400 1-12

© SAP AG 2006

Overview Diagram: The ABAP Workbench

First Attempts at ProgrammingFirst Attempts at Programming

Customer EnhancementsCustomer Enhancements

Dialogs and ALV ReportsDialogs and ALV Reports

The ABAP WorkbenchThe ABAP Workbench

ExtractionExtraction

Template AllocationTemplate Allocation

Page 13: AC400 Programming in Financials

© SAP AG AC400 2-13

© SAP AG 2006

Overview Diagram: The ABAP Workbench

The ABAP WorkbenchThe ABAP Workbench

First Attempts at ProgrammingFirst Attempts at Programming

Dialogs and ALV ReportsDialogs and ALV Reports Template AllocationTemplate Allocation

ExtractionExtraction

Customer EnhancementsCustomer Enhancements

Page 14: AC400 Programming in Financials

© SAP AG AC400 2-14

© SAP AG 2006

The ABAP Workbench – Overview

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.

Contents:

Page 15: AC400 Programming in Financials

© SAP AG AC400 2-15

© SAP AG 2006

Describe the structure of the repository

Name and use the search tools in the repository

Use the Object Navigator for your development work

The ABAP Workbench: Objectives

At the conclusion of this unit, you will be able to:

Page 16: AC400 Programming in Financials

© SAP AG AC400 2-16

© SAP AG 2006

Presentationserver layer

Applicationserver layer

Database

ABAP Program

Client-independent Client-dependent

Repository Application tablesCustomizing tables

The Repository – Embedding

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.

Page 17: AC400 Programming in Financials

© SAP AG AC400 2-17

© SAP AG 2006

Function modules

ProgramsTable definitions

. . .Repository

FI

SD

CO

HR

CustomerCO

MMMM

CustomerFI

CustomerMM

MM

Package MM_CPackage MM_B

Package MM_A

Structure of the Repository

Repository objects

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.

Page 18: AC400 Programming in Financials

© SAP AG AC400 2-18

© SAP AG 2006

SAP

Cross-Application ComponentsAccounting - GeneralFinancial Accounting

. . .FBAS Financial Accounting "Basis". . .

FI-GL General Ledger AccountingFI-LC Consolidation...TreasuryControlling

++

Application componentPackageSelected subtree

+++

+++

CAACFI

TRCO...

+ Information System

SAP Application Hierarchy

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.

Page 19: AC400 Programming in Financials

© SAP AG AC400 2-19

© SAP AG 2006

Repository Information System Business EngineeringABAP Dictionary

Basic ObjectsDatabase TablesViewsData ElementsStructuresTable Types. . .

Other ObjectsFields

ProgrammingFunction LibraryProgram LibraryProgramming EnvironmentProgram Subobjects

ABAP ObjectsClass LibraryClass SubobjectsInterface Subobjects

Environment

Double-click

Selection Screen for

Delimiting the Search

The Repository Information System

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: 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".

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.

Page 20: AC400 Programming in Financials

© SAP AG AC400 2-20

© SAP AG 2006

Function Builder

Screen Painter

ABAP DictionaryABAP Editor

ObjectNavigator

Menu PainterDebugger

Class Builder

FI HR

MM

SD

MM

WM

Customer

ABAP Workbench Tools

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:

Call the object directly from the Easy Access menu. 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.

Double-click to navigate from one tool to another and back again.

Page 21: AC400 Programming in Financials

© SAP AG AC400 2-21

© SAP AG 2006

Adjustable border

Context menu

Full screen on/off

Context menuRight mouse button

Navigation areaTool area

. . .

. . .

Screen Layout in the Object Navigator

Right mouse button

The Object Navigator screen is divided into two areas: The navigation area to display an object list as a hierarchy tree, 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).

Page 22: AC400 Programming in Financials

© SAP AG AC400 2-22

© SAP AG 2006

DDIC objectsProgramsSAPBC400WBD_GETTING_STASAPBC400WBT_GETTING_STAFunction groupsBC400ClassesCL_BC400

BC400

Package

BC400

Previous/nextobject list

ApplicationhierarchyPackageProgramFunction groupClass/Interface...Inactive objectsLocal objects

Organize Favorites

Update objectlist

Higher-levelobject list

Navigation bydouble-click

The Navigation Area

Repository objects are organized hierarchically: An application component can contain various development classes. A development class in turn can contain different repository objects: Programs, function groups, ABAP Dictionary objects and so on.

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.

Page 23: AC400 Programming in Financials

© SAP AG AC400 2-23

© SAP AG 2006

Navigation stack

Functions of the current tool

Show navigationwindow

Navigation history

Previous/nextobject

Navigation in the Tool Area

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.

Page 24: AC400 Programming in Financials

© SAP AG AC400 2-24

© SAP AG 2006

Display object list

Double-clickor context

menu function

Modifying the Tool Area

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: 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.

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.

Page 25: AC400 Programming in Financials

© SAP AG AC400 2-25

© SAP AG 2006

Create package

PackageShort description

Application component

Software component

Transport layer

Package type

ZBC400_00Exercises group 00

CA

HOME

ZDEV

No main packageWhere should the

development objects be transported ?

To which application component does the

package belong ?

Comply withcustomernamespace !

Creating Packages

You can create a package from the Object Navigator: 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.

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: Transport layer: If you carry out your own development, a transport layer has to be set up for customer development.

Person responsible: The person responsible carries full responsibility for the objects in this package. Your user name is entered as the default value.

Software component: You usually enter customer developments under HOME. You will find more detailed information in the F1 help for the field.

Application component: Determine where the package should appear in the application hierarchy.

Page 26: AC400 Programming in Financials

© SAP AG AC400 2-26

© SAP AG 2006

Package

Enter transportable Workbench request

ZBC400_00

Enter transportable Workbench request

Change requests involving BC400-00Changeable

Transportable

IT3K900051 CARSON

IT3K900052 CARSON

IT3K900053 BC400-00

IT3K900054 BC400-01

Request IT3K90051

Participants' exercises for course BC400

Workbench request

Double-click on order number

Own requests. . .

Assignment to Change Requests

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.

Page 27: AC400 Programming in Financials

© SAP AG AC400 2-27

© SAP AG 2006

Additions and operands(keyword-specific)

ABAPkeyword

SELECT

ENDSELECT.

WRITE

.

.

.

Period to closethe statement

DATA .

NEW-LINE.

WRITE

WRITE .

General structure of an ABAP statement

X X X Y Y Y

Sample Program...

wa_scarr TYPE scarr

* FROM scarrINTO wa_scarr

wa_scarr-carrid

wa_scarr-carrname

wa_scarr-url

ABAP Syntax I

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.

Page 28: AC400 Programming in Financials

© SAP AG AC400 2-28

© SAP AG 2006

:: ,,

..Chained statement

******

""

Comments(complete lines)

comments ...comments ...comments ...

DATA wa_scarr TYPE scarr.

SELECT * FROM scarrINTO wa_scarr. ""

comments ...

comments ...

Command-relatedcomments

NEW-LINE.

WRITE wa_scarr-carrid

,,wa_scarr-carrname

wa_scarr-url

ENDSELECT.

"" comments ...

ABAP Syntax II

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: Close the identical start of the statement with a colon. Separate the chained parts of the statement that follow the colon with commas. Spaces and line breaks can come before and after the separators (colon, comma, period). Note that the individual components of a chained statement represent separate instructions for the ABAP runtime system, as before.

Page 29: AC400 Programming in Financials

© SAP AG AC400 2-29

© SAP AG 2006

REPORT ...

PARAMETERS pa_carr TYPE scarr-carrid.

DATA wa_scarr TYPE scarr.

SELECT SINGLE * FROM scarrINTO wa_scarrWHERE 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.

SY-SUBRC as Return Code

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.

Page 30: AC400 Programming in Financials

© SAP AG AC400 2-30

© SAP AG 2006

With TOP include

Create program

Program ZBC400_00_GS

Attributes

ABAP program properties ...

Header My 1st ABAP program

TypeStatusApplication

Fixed point arithmetic

Executable programTest program

Comply with customer namespace !

. . .

Save

. . .

Creating a Program

The following options are available for creating a program from the Object Navigator: 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.)

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.

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.

Page 31: AC400 Programming in Financials

© SAP AG AC400 2-31

© SAP AG 2006

START-OF-SELECTION.SELECT SINGLE * FROM scarr

INTO wa_scarrWHERE carrid = pa_car.

IF sy-subrc = 0.MOVE-CORRESPONDING wa_scarr

TO sbc400_carrier.CALL SCREEN 100.MOVE-CORRESPONDING sbc400_carrier

TO wa_scarr.

WRITE: wa_scarr-carrid,wa_scarr-carrname,wa_scarr-currcode.

ENDIF.

i

WRITEWRITE

ABAP overview ABAP term What's new in ABAPABAP glossaryABAP index. . .

Help

WRITE

F1

Keyworddocumentation

Documentation of ABAP Terms

There are a number of navigation options for displaying keyword documentation for an ABAP statement: The F1-button takes you directly to the documentation for the statement on which the cursor is currently positioned.

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.

Page 32: AC400 Programming in Financials

© SAP AG AC400 2-32

© SAP AG 2006

Program A( inactive version )

Saved programs(for further development/testing)

Activated programs(for using/transporting across all systems)

Program A( active version )

Activate

Program B( active version )

Program C( active version )

Program C( inactive version )

Inactive and Active Development Objects

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.

Page 33: AC400 Programming in Financials

© SAP AG AC400 2-33

© SAP AG 2006

Generating Runtime Objects

Saved programs(for further development/testing)

Activated programs(for using/transporting across all systems)

Program A( active version )

Program B( active version )

Program C( active version )

Program C( inactive version )

When executed (from the editor), the relevant runtime object is

always generated again.

When executed, the runtime object generated during activation

is used.

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".

Page 34: AC400 Programming in Financials

© SAP AG AC400 2-34

© SAP AG 2006

System System HelpHelp

ZBC400_00_GS

Create report transaction

Transaction code Z00GSPackage ZBC400_00

Transaction textProgram...

. . .ZBC400_00_GS

Classification

Professional User TransactionEasy Web Transaction

. . .

. . .

Creating a Transaction Code

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.

Page 35: AC400 Programming in Financials

© SAP AG AC400 2-35

© SAP AG 2006

Favorites

SAP Menu

SAP Easy Access

Object Navigator

Enter a transaction manually

Transaction code Z00GS

Insert Transaction. . .

. . .

Inserting Transaction Codes in Favorites

System System HelpHelp

To enter a transaction code in the Favorites for your role menu, proceed as follows: Navigate to the initial screen (SAP Easy Access menu). In the Favorites context menu, choose Insert Transaction. 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.

Page 36: AC400 Programming in Financials

© SAP AG AC400 2-36

© SAP AG 2006

ABAP program

SubroutineInterface

Interface

. . . Definition of input/output fields

. . . Definition of data objects

. . .

MethodInterface

. . .

. . . Typing interfaceparameters. . . Typing interfaceparameters. . . Typing interfaceparameters Functio

n module

Data Types

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.

Page 37: AC400 Programming in Financials

© SAP AG AC400 2-37

© SAP AG 2006

ABAPDictionary

Global data types(technical and semantic

properties)ABAP program

SubroutineInterface

Interface

. . .

MethodInterface

. . .

Function module

Data types local to programs(technical properties only)

Local vs. Global Data Types

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.

Page 38: AC400 Programming in Financials

© SAP AG AC400 2-38

© SAP AG 2006

Implemented ABAP types(Standard types in ABAP)

X

I

F

STRING

XSTRING

T

D

C

N

P

TYPES type_name TYPE ...

DATA myvar TYPE type_name .

DATA myvar2 LIKE myvar.

ABAP program

Global types ABAPDictionary

Declaration of local types

Elementary Data Types

You can use an implemented ABAP type, a local or a global type to type data objects. The following implemented ABAP types are complete:

d Date (Date, format: YYYYMMDD) t Time (Time, format: HHMMSS) i Integer (Integer) f Floating point number (Floating point) string String (String, variable length) xstring Byte sequence (HeXadecimal string, variable length)

The length must be specified for the following implemented types: c Character (Character) n Numerical character (Numerical character) x Byte (HeXadecimal) 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.

Page 39: AC400 Programming in Financials

© SAP AG AC400 2-39

You can use LIKE to refer to the type of a data object that has already been defined.

Page 40: AC400 Programming in Financials

© SAP AG AC400 2-40

© SAP AG 2006

S_CARR_ID (Data element)

...

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.

number1

percentage2

carrid

connid

SBC400FOCC (Structure)

percentage1 +00000

0000

+00000

number2 0

17

city

Declaration of Variables

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. 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.

Page 41: AC400 Programming in Financials

© SAP AG AC400 2-41

When you use global types, the syntax is the same as for user-defined types: DATA do_name TYPE global_type_name.

Page 42: AC400 Programming in Financials

© SAP AG AC400 2-42

© SAP AG 2006

Literals:

Constants :

Fixed data objects without identifier

Character string : 'Hallo'Decimal numbers : '123.45'Floating point numbers : '123.45E01'

Text literals

myconst TYPE type_name VALUE {literal | IS INITIAL } . CONSTANTS

positive integer : 123

negative integer : -123

Fixed data objects with identifier

Numeric literals

Fixed Data Objects

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. 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.

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.

Page 43: AC400 Programming in Financials

© SAP AG AC400 2-43

© SAP AG 2006

ABAP runtime system

MOVE c_qf TO carrid1.

carrid2 = carrid1.

ADD 1 TO counter.

CLEAR: carrid1, carrid2,counter.

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

Data declarations

c_qf QF carrid1 carrid2

LH

counter

0

QF LH 0

QF QF 0

QF QF 1

0

ABAP program

Value Assignments

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: MOVE source TO target. 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.

Page 44: AC400 Programming in Financials

© SAP AG AC400 2-44

© SAP AG 2006

DATA: max TYPE sbc400focc-seatsmax,

occ TYPE sbc400focc-seatsocc,

percentage TYPE sbc400focc-percentage.

Keyword COMPUTE is optional :

percentage = occ * 100 / max .

ABAP program

Data declarations

* /

Calculations

COMPUTE percentage = occ 100 max .

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: + Addition - Subtraction * Multiplication / Division ** Power DIV Integral division without remainder 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.

Page 45: AC400 Programming in Financials

© SAP AG AC400 2-45

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.

Page 46: AC400 Programming in Financials

© SAP AG AC400 2-46

© SAP AG 2006

Statements

Statements

Statements

Statements

Statements

Statements

Conditional Branches

IF var > 0 .

ELSEIF var = 0 .

ELSE .

ENDIF . CASE mycarrid.

WHEN 'AA'.

WHEN 'LH'.

WHEN OTHERS .

ENDCASE .

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 CASE-ENDCASE 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.

Page 47: AC400 Programming in Financials

© SAP AG AC400 2-47

© SAP AG 2006

DO.

IF <abort_condition>. EXIT. ENDIF.ENDDO.

DO n TIMES.

ENDDO.

WHILE <condition>.

ENDWHILE.

SELECT ... FROM <dbtab> ...

ENDSELECT.

LOOP AT <internal table> ...

ENDLOOP.

Loop countersy-index

Statements

Statements

Statements

Statements

Statements

Loop countersy-index

Loop countersy-index

Loops

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 so-called endless loop.

Precondition loops The statements between WHILE and ENDWHILE are only executed if the <logical_expression> 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.

Page 48: AC400 Programming in Financials

© SAP AG AC400 2-48

© SAP AG 2006

MESSAGE tnnn(message_class) [ WITH v1 [ v2 ] [ v3 ] [ v4 ] ] .

Type Dialog behavior Message appears in

i

s

w

e

a

x

Program continuesafter interruption

Program continueswithout interruption

Context-dependent

Context-dependent

Program is terminated

Runtime error MESSAGE_TYPE_Xis triggered

modal dialog box

Status bar of next screen

Status bar

Status bar

modal dialog box

Short dump

Meaning

Info message

Successmessage

Warning

Error

Abort

Short dump

Dialog Messages

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: a Abort The program is terminated after a dialog box. x Exit The program is terminated with a short dump. e Error The runtime behavior is context-dependent. w Warning The runtime behavior is context-dependent. i Information The program continues after a dialog box. 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.

Page 49: AC400 Programming in Financials

© SAP AG AC400 2-49

© SAP AG 2006

wa_focc TYPE sbc400focc.

wa_spfli TYPE spfli.

DATA

DATA

wa_focccarrid seatsmaxconnid fldate seatsocc percentage

wa_spflicarrid cityfromconnid countryfr airpfrommandt . . .countryto

Data DictionaryData element

Structure SBC400FOCC

Transparent table SPFLI

Table types

Field type

Structuretype

Type forinternaltables

Global Reference Structures

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: With DATA struc_name TYPE struc_type you can use local or global types struc_type. 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.

Page 50: AC400 Programming in Financials

© SAP AG AC400 2-50

© SAP AG 2006

wa_flightinfocarrid seatsmaxconnid fldate seatsocc percentage

TYPES: BEGIN OF st_flightinfo,carrid TYPE s_carr_id,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.

Declaration of alocal structure type

Definition of astructure variable

Structures Without Local Reference

You can also define structure types locally with the TYPE statement. The components are enclosed by BEGIN OF structure_type_name, ... , 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:

DATA: BEGIN OF structure_name, ... , END OF structure_name.

Page 51: AC400 Programming in Financials

© SAP AG AC400 2-51

© SAP AG 2006

DATA wa_scarr TYPE scarr.

wa_scarr carrid = 'LH'.

SELECT SINGLE * FROM scarrINTO wa_scarrWHERE carrid = wa_scarr carrid.

WRITE: / wa_scarr carrid,wa_scarr carrname,wa_scarr url.

-

-

---

wa_scarrmandt currcodecarrid carrname url

400 LH Lufthansa EUR www.lufthansa.com

Accessing Structure Components

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.

Page 52: AC400 Programming in Financials

© SAP AG AC400 2-52

© SAP AG 2006

DATA: wa_sflight TYPE sflight,

wa_focc TYPE sbc400focc.

MOVE-CORRESPONDING wa_sflight TO wa_focc.

wa_focccarrid seatsmaxconnid fldate seatsocc percentage

wa_sflight

carrid priceconnid fldate seatsmaxmandt . . .seatsocc

. . .

planetype

Value Assignments Between Structures

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.

Page 53: AC400 Programming in Financials

© SAP AG AC400 2-53

© SAP AG 2006

Dynamic increasein storage capacity

Print list

Screen display

Database tables

Files

internal 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: Retaining data from database tables for processing at a later stage, Structuring and staging data for output, Staging data for use by other services.

Page 54: AC400 Programming in Financials

© SAP AG AC400 2-54

© SAP AG 2006

AA 0017 2.572 LH 0400 6.162

QF 0005 10.000 LH 0402 7.273

CARRID CONNID DISTANCE

SQ 0866 1.625 UA 0007 2.572

• Components• Uniqueness• Sequence

IndexIndex

54321

6• Standard• Sorted• Hashed

Line type

Key

Table type

Properties of an Internal Table

1

2

3

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 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.

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.

Page 55: AC400 Programming in Financials

© SAP AG AC400 2-55

© SAP AG 2006

Index access

Keyaccess

Keyuniqueness

HASHED TABLESTANDARD TABLE SORTED TABLE

Index tables

Table type

n

NON-UNIQUE UNIQUEUNIQUE | NON-UNIQUE

Usage with predominantindex access

predominantkey access

exclusivekey access

Table Type and Access Type

Hashed table

Another property of an internal table is the table type. Internal tables can be divided into three table types using the possible access types: With Standard tables, line numbering is maintained internally. Both index and key access is possible.

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.

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: Standard tables are normally used for index access: Sorted tables are used for unique keys and fixed sorting. 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.

Page 56: AC400 Programming in Financials

© SAP AG AC400 2-56

© SAP AG 2006

itab_flightinfo TYPE sbc400_t_sbc400focc.DATA

itab_flightinfocarrid seatsmaxconnid fldate seatsocc percentage

Access

Key

Key typeKey components

Line type SBC400FOCC

non-uniqueCARRID, CONNID, FLDATE

SBC400_T_SBC400FOCCTable type

Standard table

Global Table Types

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.

Page 57: AC400 Programming in Financials

© SAP AG AC400 2-57

© SAP AG 2006

itab_flightinfocarrid seatsmaxconnid fldate seatsocc percentage

WITH NON-UNIQUE KEY

sbc400focc

Local table type

Internal tables

Local Table Types

TYPES tt_flightinfo

TYPE STANDARD TABLE OF

carrid connid fldate.

DATA itab_flightinfo TYPE tt_flightinfo.

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.

Page 58: AC400 Programming in Financials

© SAP AG AC400 2-58

© SAP AG 2006

DATA wa TYPE spfli.

SELECT ... FROM spfliINTO wa ...

DATA wa TYPE sbc400focc.

DATA itab TYPEsbc400_t_sbc400focc.

ABAP program ABAP Dictionary Database

SPFLI

Transparent table

(Description)

SBC400FOCC

Structure

SBC400_T_SBC400FOCC

Table type

AA 17 ...AA 64 ...... ... ...LH 400 ...LH 402 ...

SPFLI

wa

wa

itab

Overview of Complex Data Types

Page 59: AC400 Programming in Financials

© SAP AG AC400 2-59

© SAP AG 2006

Append

Insert

Read

Change

Delete

wa to itab.

wa INTO TABLE itab <condition>.

itab INTO wa <condition>.

TABLE itab FROM wa [ <condition> ].

itab <condition>.

APPEND

INSERT

READ TABLE

MODIFY

DELETE

Single Access Overview

Page 60: AC400 Programming in Financials

© SAP AG AC400 2-60

© SAP AG 2006

Single record processingover the whole(or part) ofthe internal table

Delete severalrecords

Insert severallines from another internal table

Append severallines from another internal table

Group Access Overview

LOOP AT itab INTO wa <condition> ....

ENDLOOP .

DELETE itab <condition> .

INSERT LINES OF itab1 <condition1>INTO itab2 <condition2> .

APPEND LINES OF itab1 <condition>TO itab2.

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: 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.

DELETE deletes the lines of an internal table that satisfy the <condition> requirement. INSERT copies the content of several lines of an internal table into another internal table. 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.

Page 61: AC400 Programming in Financials

© SAP AG AC400 2-61

© SAP AG 2006

* 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.

* define internal table and workarea

DATA: itab_flightinfo TYPE sbc400_t_sbc400focc,

wa_flightinfo LIKE LINE OF itab_flightinfo.

itab_flightinfo

wa_flightinfo

Inserting a Single Record

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.

Page 62: AC400 Programming in Financials

© SAP AG AC400 2-62

© SAP AG 2006

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

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

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.

Page 63: AC400 Programming in Financials

© SAP AG AC400 2-63

© SAP AG 2006

sy-tabix

Reading by Index

LOOP AT itab_flightinfo INTO wa_flightinfoFROM 1 TO 5 .

WRITE: / wa_flightinfo-carrid,wa_flightinfo-connid,wa_flightinfo-fldate,wa_flightinfo-seatsmax,wa_flightinfo-seatsocc,wa_flightinfo-percentage,'%'.

ENDLOOP.

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,'%'.

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.

Page 64: AC400 Programming in Financials

© SAP AG AC400 2-64

© SAP AG 2006

sy-tabix

Reading by Key

LOOP AT itab_flightinfo INTO wa_flightinfoWHERE carrid = 'LH' .

WRITE: / wa_flightinfo-carrid,wa_flightinfo-connid,wa_flightinfo-fldate,wa_flightinfo-seatsmax,wa_flightinfo-seatsocc,wa_flightinfo-percentage,'%'.

ENDLOOP.

READ TABLE itab_flightinfo INTO wa_flightinfoWITH 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

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.

Page 65: AC400 Programming in Financials

© SAP AG AC400 2-65

© SAP AG 2006

DESCENDING

ASCENDING

REFRESH itab_flightinfo.

FREE itab_flightinfo.

SORT itab_flightinfo.

Sorting a Standard Table

SORT itab_flightinfo BY carrid.

SORT itab_flightinfo BY percentage

carrid .

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 ].

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.

Page 66: AC400 Programming in Financials

© SAP AG AC400 2-66

© SAP AG 2006

Internal table itab

INSERT itab INDEX n.

DELETE TABLE itab.

READ TABLE itab INDEX n.

WRITE itab-carrid.

Implicit syntaxExplicit syntax

Internal table itab

DATA itabTYPE STANDARD TABLE OF scarrWITH NON-UNIQUE KEY carrid.

.DATA wa LIKE LINE of itab

Internal Tables with and Without Header Lines

DATA itabTYPE STANDARD TABLE OF scarrWITH NON-UNIQUE KEY carrid

WITH HEADER LINE .

Work area wa Header line itab

INSERT wa INTO itab INDEX n.

DELETE TABLE itab FROM wa .

READ TABLE itab INTO wa INDEX n.

WRITE wa-carrid.

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. 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

Page 67: AC400 Programming in Financials

© SAP AG AC400 2-67

© SAP AG 2006

Applicationserver

Native SQL

ABAPOpen SQL Native SQL

Tablebuffer

Database server

Database interface

Database Accesses

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.

Page 68: AC400 Programming in Financials

© SAP AG AC400 2-68

© SAP AG 2006

Application-related search

Search within a particular application component:Application hierarchy

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 subfunctionswitch to debugging mode ("/h") and set breakpoint at SELECTstatement

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"

Program-related search

Table Drilldown Report

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: Debugger: - Start this program in debugging mode and set a breakpoint at the SELECT statement.

Editor: - Search for the SELECT statement in the source text.

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.

Page 69: AC400 Programming in Financials

© SAP AG AC400 2-69

© SAP AG 2006

specific columns

single/multiple lines

SELECT <fields> FROM <table> INTO <target> WHERE <condition> .

Which columns ? Which table ? Where ? Which lines ?

Read Database Access

You program read database accesses with the open SQL statement SELECT. The SELECT statement is comprised of a number of clauses with different tasks:

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.

The FROM clause names the source (database table or view) from which the data is to be selected.

The INTO clause determines the internal data objects into which the selected data is to be placed.

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.

You will find other clauses in the keyword documentation for SELECT.

Page 70: AC400 Programming in Financials

© SAP AG AC400 2-70

© SAP AG 2006

pa_car

IF sy-subrc = 0....

ENDIF.

SINGLE

Databaseinterface

wa_scarr

INTO

WHERE

SCARR

Databasetable

SELECT *

FROM scarr

wa_scarr

carrid = pa_car .

Reading by Single Record Access

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.

Page 71: AC400 Programming in Financials

© SAP AG AC400 2-71

© SAP AG 2006

pa_car

wa_sbc400focc

Databaseinterface

ENDSELECT

SELECT

Statements for each read record

SFLIGHT

Databasetable

carrid connid fldateseatsocc seatsmax

FROM sflightINTO wa_sbc400focc

" INTO CORRESPONDING" FIELDS OF ...WHERE carrid = pa_car.

IF sy-subrc = 0.sy-dbcnt ...

ENDIF.

Reading Several Lines

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. sy-subrc 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.

Page 72: AC400 Programming in Financials

© SAP AG AC400 2-72

© SAP AG 2006

pa_car

itab_focc

Databaseinterface

SFLIGHT

Databasetable

Reading Several Lines in an Internal Table

SELECT carrid connid fldateseatsmax seatsoccFROM sflightINTO TABLE itab_focc

WHERE carrid = pa_car .

IF sy-subrc = 0.sy-dbcnt ...

ENDIF.

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.

Page 73: AC400 Programming in Financials

© SAP AG AC400 2-73

© SAP AG 2006

ABAP program

Same type asread fields

wa_sbc400focc

Transferring Structures

DATA wa_sbc400focc TYPE sbc400focc.

SELECT SINGLE carrid connid fldate seatsmax seatsocc

FROM sflight

INTO wa_sbc400focc

WHERE carrid = pa_carAND connid = pa_conAND fldate = pa_date.

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: 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.

Individual data objects: You can specify a number of data objects in the INTO clause. 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)

Page 74: AC400 Programming in Financials

© SAP AG AC400 2-74

WHERE ...

Page 75: AC400 Programming in Financials

© SAP AG AC400 2-75

© SAP AG 2006

ABAP program

Same name asread fields

INTO CORRESPONDING FIELDS OF wa_sdyn_conn

wa_sdyn_conn

Transferring Selected Structure Content

DATA wa_sdyn_conn TYPE sdyn_conn.

SELECT SINGLE carrid connid fldate seatsmax seatsocc

FROM sflight

WHERE carrid = pa_carAND connid = pa_conAND fldate = pa_date .

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: The target structure does not have to be structured with left alignment in the same way as the field list.

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.

Page 76: AC400 Programming in Financials

© SAP AG AC400 2-76

© SAP AG 2006

CARRID CITYFROM

AAAA......AAAA... ...AAAA

NEW YORKFRANKFURT......NEW YORKFRANKFURT......NEW YORKFRANKFURT

Database table SPFLI

CONNID

00170064......

00170064... ...

00170064

MANDT

400400......401401... ...402 402

SELECT * FROM spfliINTO ...WHERE carrid = 'AA'.

Logged on in client 400 :

Client-Dependent Selection

SELECT * FROM spfliCLIENT SPECIFIED

INTO ...WHERE mandt = 402AND carrid = 'AA'.

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.

Page 77: AC400 Programming in Financials

© SAP AG AC400 2-77

© SAP AG 2006

CARRID CITYFROM ...

AAAAJLLHLH... AAAALHUA...

NEW YORKFRANKFURTTOKYOFRANKFURTFRANKFURT...NEW YORKFRANKFURTBERLINFRANKFURT...

Database table SPFLI

CONNID

00170064040704000402...

0017 006424070941...

PARAMETERS pa_from TYPE spfli-cityfrom .

SELECT * FROM spfliINTO ...WHERE cityfrom = pa_from .

...

CITYFROM

Secondary index forfaster access with

CITYFROM selection

FRANKFURTFRANKFURTFRANKFURTNEW YORKTOKYO...BERLINFRANKFURTFRANKFURTNEW YORK...

...

...

...

...

...

...

...

...

...

...

...

MANDT

400400400400400... 401401401401 ...

MANDT

400400400400400... 401401401401 ...

Selection screen

Departure from

FRANKFURT

Selecting with Indices

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: 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.

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.

Page 78: AC400 Programming in Financials

© SAP AG AC400 2-78

© SAP AG 2006

MANDT CARRID CONNID CITYFROM...SPFLI

... MANDT CARRID CARRNAME

SCARR

...

Join tables

SPFLI-MANDT = SCARR-MANDT

SPFLI-CARRID = SCARR-CARRIDandJoin condition

MANDT CARRID CONNID CITYFROM

Table joinCARRNAME

Joincolumns

Reading Linked Tables

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: Which database tables should be accessed? 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.

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.

Page 79: AC400 Programming in Financials

© SAP AG AC400 2-79

© SAP AG 2006

Database view in Dictionary

Database view ZABC

SELECT ...

FROM zabc

WHERE ...

Program Program

SELECT ...

FROM

ON spfli~carrid = scarr~carrid

WHERE ...

View and Join

View definition in the Dictionary+ Selection in program

Direct joining inprogram (ABAP join)

spfli INNER JOIN scarr

The link conditions can be defined statically or dynamically. 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.

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.

Page 80: AC400 Programming in Financials

© SAP AG AC400 2-80

© SAP AG 2006

SELECT

INSERT

UPDATE

DELETE

MODIFY

Statements for Database Changes

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.

Page 81: AC400 Programming in Financials

© SAP AG AC400 2-81

© SAP AG 2006

...

...

...

.

.

.

...

...

...

.

.

.

...

...

...

.

.

.

.

.

.

.

.

.

...

...

...

Subroutine

Subroutine call...

Subroutine call...

Subroutine call...

More transparent+Easier to maintain

Same

sourcetext

blocks

Motivation Behind Subroutines

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.

Page 82: AC400 Programming in Financials

© SAP AG AC400 2-82

© SAP AG 2006

REPORT ...DATA: a TYPE ... ,

b TYPE ... ,c TYPE ... .

Subroutine

...

Formal parameter :

Call subroutine with ( a , b , c )...

...

...Call byValue

Call byReference

Call by Valueand Result

f1 f2 f3, ,

Copyof a

Copyof b

Data Copy when Calling the Subroutine

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 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 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 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.

Page 83: AC400 Programming in Financials

© SAP AG AC400 2-83

© SAP AG 2006

FORM xyzUSINGvalue(f1) ... " Call by Value

CHANGINGvalue(f2) ... " Call by Value and Result

f3 ... . " Call by Reference...

ENDFORM.

PERFORM xyzUSINGa

CHANGINGbc.

Definition

Call

Subroutine Call and Interface

REPORT ...DATA: a TYPE ... ,

b TYPE ... ,c TYPE ... .

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)

List this kind of parameter after USING and enclose it in brackets with value(f1) too. Call-by-reference (f2)

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) List this kind of parameter after CHANGING and enclose it in brackets with value(f3) too.

Page 84: AC400 Programming in Financials

© SAP AG AC400 2-84

© SAP AG 2006

TYPES t_perc TYPE p DECIMALS 2.

DATA: a TYPE i,b TYPE i ,c TYPE t_perc .

...

PERFORM calc_percUSING

ab

CHANGINGc.

FORM calc_percUSING

value(f_part) TYPE ANYvalue(f_all) TYPE ANY

CHANGINGvalue(f_pc) TYPE ANY .

CHECK f_all <> 0.f_pc = f_part * 100 / f_all .

ENDFORM.

Variable:Type inheritance +Risk of conflicting types

TYPES t_perc TYPE p DECIMALS 2.

DATA: a TYPE i,b TYPE i ,c TYPE t_perc .

...

PERFORM calc_percUSING

ab

CHANGINGc.

FORM calc_percUSING

value(f_part) TYPE ivalue(f_all) TYPE i

CHANGINGvalue(f_pc) TYPE t_perc .

CHECK f_all <> 0.f_pc = f_part * 100 / f_all .

ENDFORM.

Constant:Prescribedtype foractual parameter

Variable and Constant Typing

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.

Page 85: AC400 Programming in Financials

© SAP AG AC400 2-85

© SAP AG 2006

DATA wa_flightinfoTYPE sbc400focc.

...

PERFORM fill_waCHANGING wa_flightinfo .

...

FORM fill_waCHANGING

f_wa .

f_wa-carrid = ... .f_wa-connid = ... .

ENDFORM.

DATA it_flightinfoTYPE sbc400_t_sbc400focc.

...

PERFORM fill_itabCHANGING it_flightinfo.

...

TYPE sbc400focc

Structure type Table type

Structure componentsaddressable

Typing with Structures and Internal Tables

FORM fill_itabCHANGING

f_itab TYPE sbc400_t_sbc400focc .

LOOP AT f_itab ... ....

ENDLOOP.

ENDFORM.

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: With internal tables as the transfer parameter, you should generally select call-by-reference as the transfer type, as the effort required to copy data can otherwise be considerable.

Page 86: AC400 Programming in Financials

© SAP AG AC400 2-86

© SAP AG 2006

...

PERFORM fill_itab CHANGING it_flightinfo .

...

Global variables

Local variable

DATA: it_flightinfo TYPE sbc400_t_sbc400focc,wa_flightinfo LIKE LINE OF it_flightinfo .

Local and Global Internal Tables

FORM fill_itabCHANGING

f_itab TYPE sbc400_t_sbc400focc.

DATA l_wa LIKE LINE OF f_itab .

LOOP AT f_itab INTO l_wa....

ENDLOOP.

ENDFORM.

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: Address the global data objects in the main program and and transfer them to the subroutine via the interface.

Address only the formal parameters and the local data objects in the subroutine. 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.

Page 87: AC400 Programming in Financials

© SAP AG AC400 2-87

© SAP AG 2006

DATA: carrid TYPE sbc400focc-carrid,it_flightinfo TYPE sbc400_t_sbc400focc,lines TYPE i.

PERFORM count_linesUSING

carridit_flightinfo

CHANGINGlines.

FORM count_linesUSING

f_carr TYPE sbc400focc-carrid f_itab TYPE sbc400_t_sbc400focc

CHANGINGvalue(f_lines) TYPE i.

DATA l_wa LIKE LINE OF f_itab.

CLEAR f_lines.LOOP AT f_itab INTO l_wa WHERE carrid = f_carr.

ADD 1 TO f_lines.ENDLOOP.

ENDFORM.

Calling a Subroutine

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.

Page 88: AC400 Programming in Financials

© SAP AG AC400 2-88

© SAP AG 2006

System Help

Z00_FORM

ABAP Editor: Change Report Z00_FORM

SubroutinesCOUNT_LINES

FORM count_linesUSING

f_carr TYPE ...f_itab TYPE ...

CHANGINGvalue(f_lines) TYPE ... .

...ENDFORM.

...

PERFORM count_linesUSING

f_carrf_itab

CHANGINGf_lines .

...Use

actual parameter

+

Drag &

Dro

p

Editing a Subroutine

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.

Page 89: AC400 Programming in Financials

© SAP AG AC400 2-89

© SAP AG 2006

ABAP Workbench Overview: Summary

The ABAP Workbench contains a number of tools for developing a wide variety of program objects.

The ABAP Workbench is integrated with the Repository.

The ABAP Workbench provides a glossary of all ABAP statements.

Page 90: AC400 Programming in Financials

© SAP AG AC400 2-90

Page 91: AC400 Programming in Financials

© SAP AG AC400 3-91

© SAP AG 2006

First Attempts at Programming: Overview Diagram

First Attempts at ProgrammingFirst Attempts at Programming

The ABAP Workbench The ABAP Workbench

Dialogs and ALV ReportsDialogs and ALV Reports Template AllocationTemplate Allocation

ExtractionExtraction

Customer EnhancementsCustomer Enhancements

Page 92: AC400 Programming in Financials

© SAP AG AC400 3-92

© SAP AG 2006

Programming an Authorization Check

For the purpose of developing your first programthis unit deals with:

Authorization check architecture

The tools for developing function modules

Options for testing the program using the debugger

Contents:

Page 93: AC400 Programming in Financials

© SAP AG AC400 3-93

© SAP AG 2006

Explain the authorization concept

Analyze and write simple function modules

Use the debugger

The ABAP Workbench: Objectives

At the conclusion of this unit, you will be able to:

Page 94: AC400 Programming in Financials

© SAP AG AC400 3-94

© SAP AG 2006

Authorizationobject class

Authorizationobject

Authorization Authorization-profile

Role

User

1) := assigned2) := combined

1) 1) 2) 1) 1)

Elements of the SAP Authorization Concept

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) : 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.

Authorization object classes, objects and fields are development objects and must begin with Y or Z (customer namespace).

Page 95: AC400 Programming in Financials

© SAP AG AC400 3-95

© SAP AG 2006

BUKRS

ACTVT

WERKS

BEGRU

M_RECH_BUK

F_BKPF_BUK

F_KNA1_BUK

C_KAPA_PLA

C_ARPL_WRK

M_MSEG_WWA

V_KNA1_BRG

C_DRAW_BGR

MM_R

FI

PP

MM_B

SD

CV

Authorization Fields, Objects and Object Classes

Authorization fields Authorization objects Authorizationobject classes

Example: The authorization fields BUKRS (company code) and ACTVT (activity) are used, amongst others, in the following authorization objects: M_RECH_BUK: Authorization to release locked invoices for certain company codes. F_BKPF_BUK: Authorization to process documents for certain company codes. 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).

Page 96: AC400 Programming in Financials

© SAP AG AC400 3-96

© SAP AG 2006

BUKRS 1000, 2000ACTVT 01, 02, 031000 2000 3000

Authorization A

BUKRS

ACTVTCreateChangeDisplay

BUKRS 1000, 2000. 3000ACTVT 031000 2000 3000

Authorization B

BUKRS

ACTVT

CreateChangeDisplay

Authorizations as Attributes

Example: Authorization A allows you to execute the activities create, change and display in the company codes 1000 and 2000.

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.

Page 97: AC400 Programming in Financials

© SAP AG AC400 3-97

© SAP AG 2006

Change accountingdocumentT code "FB02"

System program

Authorization for the transaction (authorization object S_TCODE)?

Authorization for authorization object in table TSTCA?STOP

No

No

ABAP programAuthorization checks"AUTHORITY-CHECK"

Initial screen

Next screen

Start transaction

Yes

Events for Authorization Checks

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.

Page 98: AC400 Programming in Financials

© SAP AG AC400 3-98

© SAP AG 2006

Change accountingdocument

Transaction FB02Program SAPMF05L

....

AUTHORITY-CHECKOBJECT ´F_BKPF_BUK´ID ´ACTVT´ FIELD ´02´ID ´BUKRS´ FIELD BUK.

IF SY-SUBRC NE 0.MESSAGE E083 WITH BUK.

ENDIF......

Userauthorizations

Object F_BKPF_BUKAuthorization BUK

1000

Field ValueACTVT 02, 03BUKRS 1000

Authorization BUK 1000

The authorizations are read using the buffer

Programming Authorization Checks

Check

Result

Authorization checks are carried out in programs with the ABAP statement AUTHORITY-CHECK.

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: Authorization object F_BKPF_BUK Authorization field ACTVT (activity) for the value 02 (change). 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: 0: The user has authorization for the authorization object with the correct field values. 4: The user has authorization for the authorization object, however, the checked values are not assigned to the user

12: The user has no authorization for the authorization object.

Page 99: AC400 Programming in Financials

© SAP AG AC400 3-99

© SAP AG 2006

Func

tion

mod

ule

FB3

Inte

rface

Interface

Function moduleFB2

Interface

Function module

FB1

Functionm

odule

FB5

Interface

Function moduleFB4

Interface

Sub-routine

Interface

Logical View of a Function Group

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: Data declarations (global data objects) Subroutines Screens These elements can by used by all function modules in the function group.

Page 100: AC400 Programming in Financials

© SAP AG AC400 3-100

© SAP AG 2006

INCLUDE L<fgrp>TOP.

INCLUDE L<fgrp>UXX.

INCLUDE L<fgrp>F<xx>.

...

INCLUDE L<fgrp>O<xx>.

...

INCLUDE L<fgrp>I<xx>....

Framework program SAPL<fgrp>

INCLUDE L<fgrp>U01.

FUNCTION <name>....ENDFUNCTION.FUNCTION <name>....ENDFUNCTION.FUNCTION <name>....ENDFUNCTION.

FORM <form_1>

ENDFORM.

MODULE <mod_a> OUTPUT.

ENDMODULE.

MODULE <mod_b> INPUT.

ENDMODULE.

Subroutines

PBO module

PAI module

Function modules

Include programs

FUNCTION-POOL <fgrp>.TYPES: … DATA: …CONSTANTS: …

Global data for the function group

Technical Structure of a Function Group

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 (<fgrp>). This name can have up to 26 characters.

The framework program SAPL<fgrp> contains only INCLUDE statements for the following include programs: TOP include - The include program L<fgrp>TOP contains the FUNCTION-POOL statement and global

data declarations. U includes - The include program L<fgrp>UXX contains additional INCLUDE statements for the

include programs L<fgrp>U01, L<fgrp>U02, ... . The latter contain the actual function modules.

F includes - The include programs L<fgrp>F01, L<fgrp>F02, ... can be used to define subroutines to

which all the function modules in the group have access by internal call. O includes

Page 101: AC400 Programming in Financials

© SAP AG AC400 3-101

- The include programs L<fgrp>O01, L<fgrp>O02, ... can be used to define PBO modules (OUTPUT) for the function group screens.

Page 102: AC400 Programming in Financials

© SAP AG AC400 3-102

I includes - The include programs L<fgrp>I01, L<fgrp>I02, ... 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.

Page 103: AC400 Programming in Financials

© SAP AG AC400 3-103

© SAP AG 2006

-

-

-

+-

+

+

+

+

-

Function groups Global classes

Screens

Asynchronous execution

Update

Remote capability

Instantiability

Function Groups vs. Global Classes

Advantages. 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 In contrast to classes, function groups can contain screens. This allows you to encapsulate user dialogs in function modules too.

Remote capability Function modules can be called from external systems (Remote Function Call).

Update 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 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.

Page 104: AC400 Programming in Financials

© SAP AG AC400 3-104

© SAP AG 2006

Creating a Function Group

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)

Page 105: AC400 Programming in Financials

© SAP AG AC400 3-105

© SAP AG 2006

Creating Function Modules

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)

Page 106: AC400 Programming in Financials

© SAP AG AC400 3-106

© SAP AG 2006

Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_DIVIDE1_PACKED

Function module BC402_FMDD_DIVIDE1_PACKED Active

Source textExceptionsTablesChangingExportImportProperties

Process type

Normal function moduleRemote-enabled moduleUpdate function module

Function group BC402_FMDD_EXAMPLE Demonstration Function modules

Short text Divides two packed numbers

Package BC402

General data

Classification

Function module documentation

Function Module Properties

In the properties, as well as the general administrative data, you also determine the process type: Remote-enabled modules can also be called from other systems. Update function modules are used for bundled database changes and have additional functions for this purpose.

Page 107: AC400 Programming in Financials

© SAP AG AC400 3-107

© SAP AG 2006

Function module documentation

Function Builder: Display BC402_FMDD_GET_FREE_SEATS

Function module BC402_FMDD_GET_FREE_SEATS Active

Source textExceptionsTablesChangingImportProperties Export

Parameter name Typing Associated type Pass by value Short textE_RESULT TYPE DEC8_2 Results

Function module BC402_FMDD_DIVIDE1_PACKED Active

Source textExceptionsTablesChangingExportImportProperties

Parameter name Typing Associated type Default value Optional Pass by value Short textI_NUMBER1 TYPE DEC8_2 First numberI_NUMBER2 TYPE DEC8_2

1Second number

Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_DIVIDE1_PACKED Function module documentation

Defining Interface Parameters

Interface parameters are used to exchange data between calling programs and the function module.

Parameter types 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).

Page 108: AC400 Programming in Financials

© SAP AG AC400 3-108

© SAP AG 2006

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*" ... *"------------------------------------------------

Optional Parameters

IF i_number1 IS SUPPLIED. "optional parameter...ENDIF.

IF e_result IS SUPPLIED. "export parameter...ENDIF.

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 <name> IS SUPPLIED or <name> IS NOT SUPPLIED, where <name> stands for the name of the optional parameter. Note that EXPORT parameters are always optional parameters.

Page 109: AC400 Programming in Financials

© SAP AG AC400 3-109

© SAP AG 2006

Function module BC402_FMDD_DIVIDE2_GENERIC Active

TablesChangingExportImportProperties

Exception Short textDivision by zero

Source textExceptions

ZERO_DIVIDEOne of the transferred figures is too largeOVERFLOW

Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_DIVIDE2_GENERIC

Function module documentation

Exception classes

RAISE <exception>.

*** with default message:MESSAGE <type><num>(<id>)

RAISING <exception>.

Exceptions

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: RAISE <exception>. - If <exception> 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. MESSAGE <kind><num>(<id>) RAISING <exception>. - 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 <num> from the <id> message class is sent. The message type <kind> determines whether the program is terminated or continues to run. No runtime error is triggered.

Page 110: AC400 Programming in Financials

© SAP AG AC400 3-110

© SAP AG 2006

Function module BC402_FMDD_DIVIDE4_EXCP_CLASS Active

TablesChangingExportImportProperties

Exception Short text

System exception for conversion overflow

Source textExceptions

CX_SY_ZERODIVIDE System exception for division by zero.CX_SY_CONVERSION_OVERFLOW

Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_DIVIDE4_EXCP_CLASS

Function module documentation

Exception classes

RAISE EXCEPTION TYPE <exception class>[EXPORTING ... ].

Class-Based Exceptions

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: 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 RAISE EXCEPTION TYPE <exception class>. - If the constructor for the exception class has parameters, use the EXPORTING addition to

supply them with data.

Page 111: AC400 Programming in Financials

© SAP AG AC400 3-111

© SAP AG 2006

Function module

Parameter name Short textI_NUMBER1 First numberI_NUMBER2 Second number

Long textChange

Create Number to be divided

Function moduledocumentation

Division of two numbers …

This function module can only be used for training purposes.

- 10 000 000 000 000 < i_number1 < 10 000 000 000 000

1

Documentation

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.

Page 112: AC400 Programming in Financials

© SAP AG AC400 3-112

© SAP AG 2006

Function module BC402_FMDD_DIVIDE1_packed Active

ExceptionsTablesChangingExportImportProperties Source text

FUNCTION bc402_fmdd_divide1_packed.*"---------------------------------*"*"Local Interface:*" IMPORTING*" EXPORTING*" EXCEPTIONS*"---------------------------------...

ENDFUNCTION.

Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_DIVIDE1_PACKEDFunction module documentation

Source Text of a Function Module

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.

Page 113: AC400 Programming in Financials

© SAP AG AC400 3-113

© SAP AG 2006

Function module BC402_FMDD_DIVISION1_PACKED Active

Function module Edit Goto Utilities Environment System Help

Function Builder: Change BC402_FMDD_DIVISION1_PACKED

Testing Function Modules

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).

Page 114: AC400 Programming in Financials

© SAP AG AC400 3-114

© SAP AG 2006

Program

ZBC400_00_GS

ZBC400_00_GS

REPORT sapbc400wbt_getting_started.

TABLES sbc400_carrier.DATA wa_scarr TYPE scarr.PARAMETERS pa_car TYPE scarr-carrid.

SELECT SINGLE * FROM scarrINTO wa_scarrWHERE carrid = pa_car.

IF sy-subrc = 0.

MOVE-CORRESPONDING wa_scarr TO sbc4CALL SCREEN 100.MOVE-CORRESPONDING sbc400_carrier T ...

ExecuteDebugging

Debugging fromstart of program

Debugging from a specificline in a program

+

. . .

. . .

Running a Program in Debugging Mode

You have several options for starting a program from the Object Navigator in debugging mode without having to change the program: In the navigation area for the selected program, choose Execute Debugging. In the editing area, select the required program line and choose Set/Delete Breakpoint. Then start the program with Execute Direct or <F8>.

Page 115: AC400 Programming in Financials

© SAP AG AC400 3-115

© SAP AG 2006

/ h

System Help

Utilities Debugging screenDebugging ABAP"/ h" to the command field

+ Enter key

Alternative to "/ h"

Switch to debugging mode at runtime

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: Choose System Utilities Debug ABAP or Debug Screen. Enter /h in the command field in the toolbar and click on <Enter>.

Page 116: AC400 Programming in Financials

© SAP AG AC400 3-116

© SAP AG 2006

Field names

ZJJ_FORMS

1 4- Field contents

SELECT SINGLE * FROM scarrINTO CORRESPONDING FIELDS OF wa_scarrWHERE carrid = pa_carr.

IF sy-subrc = 0.MOVE-CORRESPONDING wa_scarr TO sbc400_carrier.CALL SCREEN 100.MOVE-CORRESPONDING sbc400_carrier TO wa_scarr.

Fixed point arithmetic15 30-

X SAPABAP debugger

r

SY-SUBRC SY-TABIX SY-DBCNT

Double-click ondata object

pa_carr LH

Current statement

SY-DYNNR0 0 1 1000

Watchpoint

Single-step

Single Step and Field Contents

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.

Page 117: AC400 Programming in Financials

© SAP AG AC400 3-117

© SAP AG 2006

SELECT SINGLE * FROM scarrINTO wa_scarrWHERE carrid = pa_carr.

IF sy-subrc = 0.

MOVE-CORRESPONDING wa_scarr TO sbc400_carrier.

CALL SCREEN 100.

MOVE-CORRESPONDING sbc400_carrier TO wa_scarr.

Fixed point arithmetic15 30-

ABAP Debugger

Field names 1 4- Field contents

SY-SUBRC SY-TABIX SY-DBCNT

pa_carr LH

SY-DYNNR0 0 1 1000

Watchpoint

Continue

Breakpoints

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.

Page 118: AC400 Programming in Financials

© SAP AG AC400 3-118

© SAP AG 2006

Watchpoint

Create/change watchpoint

Local watchpoint (only in specified program)

ProgramField name

Comparison operator

Comparison field/valueComparison field (if not selected: Comparison value)

pa_carr

=

LH

123...10

OR AND

pa_carr LH=No. Local Program Field name FieldOperator Comparison field/value

Logical operator between the watchpoints:

Watchpoints

Change Tracking

A watchpoint is a breakpoint that is dependent on field content: You can create the following types of watchpoints: Field name: - The program is run until the content of the field has changed.

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. 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.

Page 119: AC400 Programming in Financials

© SAP AG AC400 3-119

© SAP AG 2006

Field name

Main programSource text from

SELECT SINGLE * FROM scarrINTO CORRESPONDING FIELDS OF wa_scarrWHERE carrid = pa_carr.

IF sy-subrc = 0.MOVE-CORRESPONDING wa_scarr TO sbc400_carrier.CALL SCREEN 100.MOVE-CORRESPONDING sbc400_carrier TO wa_scarr.

Fixed point arithmetic

ABAP Debugger

Fields

SY-SUBRC

wa_sbc400

No. Component name Type Length Content

12345678

MANDTCARRIDCARRNAMECURRCODEMARKTRANSTIMEDATE

CCCCCCTD

3 3 20 5 1 12 68

800AAAmerican AirlinesUSDXSMITH14305920061224

Structured field

Length (in bytes)

wa_sbc400

58

Double-click

0

Watchpoint

Structure Contents

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.

Page 120: AC400 Programming in Financials

© SAP AG AC400 3-120

© SAP AG 2006

Field names

LOOP AT it_flightinfo INTO wa_flightinfo. WRITE: / wa_flightinfo-carrid,

wa_flightinfo-connid,

Fixed point arithmetic15 30-

ABAP Debugger

SY-SUBRC

it_flightinfo12345678

AAAAAAAALHLHLHLH

Internal table it_flightinfo Type STANDARD

CARRID

00170017001700170400040004000400

CONNID

2006051220060724200608282006122420060626200607152006111320061212

FLDATE

...

...

...

...

...

...

...

...

...

66120560470240123273280

PERCENTAGE

Table

Double-click ondata object

0

WatchpointAlternative

Internal Table Contents

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.

Page 121: AC400 Programming in Financials

© SAP AG AC400 3-121

© SAP AG 2006

Field names

Z00_FLIGHTINFOZ00_FLIGHTINFO

1 4- Field contents

...

FORM count_lines USINGf_carr TYPE ...f_itab TYPE ...

CHANGINGvalue(f_lines) TYPE ... .

DATA l_wa LIKE LINE OF f_itab.

CLEAR f_lines....

15

ABAP Debugger

SY-SUBRC SY-TABIX SY-DBCNT

f_carr LH

SY-DYNNR

FORM COUNT_LINES

Main programSource text from

0 0 1 1000

Watchpoint

Execute Return

Debugging Subroutines

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 (<F7>) to execute the remainder of the subroutine without stopping. The main program is then stopped again after the subroutine has been executed.

Page 122: AC400 Programming in Financials

© SAP AG AC400 3-122

© SAP AG 2006

You are familiar with the authorization concept and can apply it.

You can program function modules.

You can use the debugger.

First Attempts at Programming: Summary

Page 123: AC400 Programming in Financials

© SAP AG AC400 3-123

Page 124: AC400 Programming in Financials

© SAP AG AC400 3-124

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 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.

Page 125: AC400 Programming in Financials

© SAP AG AC400 3-125

1-2 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.

Page 126: AC400 Programming in Financials

© SAP AG AC400 3-126

Solutions

Unit : First Attempts at Programming

1-1 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”.

Page 127: AC400 Programming in Financials

© SAP AG AC400 3-127

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 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”

Page 128: AC400 Programming in Financials

© SAP AG AC400 3-128

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.

Page 129: AC400 Programming in Financials

© SAP AG AC400 3-129

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“

Page 130: AC400 Programming in Financials

© SAP AG AC400 3-130

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

Page 131: AC400 Programming in Financials

© SAP AG AC400 3-131

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 'Y##' FOR USER id_uname * for activity ID 'ACTVT' FIELD id_actvt * and for company code ID 'BUKRS' FIELD id_bukrs. ld_subrc = sy-subrc. * 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

Page 132: AC400 Programming in Financials

© SAP AG AC400 3-132

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.

Page 133: AC400 Programming in Financials

© SAP AG AC400 3-133

* 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.

Page 134: AC400 Programming in Financials

© SAP AG AC400 4-134

© SAP AG 2006

Dialogs and ALV Reports: Overview Diagram

Dialogs and ALV ReportsDialogs and ALV Reports

The ABAP WorkbenchThe ABAP Workbench

First Attempts at ProgrammingFirst Attempts at Programming

Template AllocationTemplate Allocation

ExtractionExtraction

Customer EnhancementsCustomer Enhancements

Page 135: AC400 Programming in Financials

© SAP AG AC400 4-135

© SAP AG 2006

Dialogs and ALV Reports – Overview

This unit provides an overview of dialog programming and ALV as a reporting tool.

Contents:

Page 136: AC400 Programming in Financials

© SAP AG AC400 4-136

© SAP AG 2006

Program dialogs

Program ALV reports

Dialogs and ALV Reports: Unit Objectives

At the conclusion of this unit, you will be able to:

Page 137: AC400 Programming in Financials

© SAP AG AC400 4-137

© SAP AG 2006

Selection screen

Airline

Global types

• Documentation• Field label• Search help

Data element

Structurefield

• Technical type

ABAP program

PARAMETERS pa_carr TYPE spfli-carrid .

pa_carr

* PARAMETERS pa_carr TYPE s_carr_id .

Semantic information

program-internalvariable

Parameter Definition

If an input field is typed with a data element, the following semantic information is also available: A field label can be adopted as the selection text. The input help (F1 help) from the data element is automatically available for the input field. 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: The field label and the input help (F1 help) are copied from the data element with which the Dictionary structure field is typed.

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.

Page 138: AC400 Programming in Financials

© SAP AG AC400 4-138

© SAP AG 2006

Text elements ( multilingual )

List header

ABAP program

Text symbols

PA_CITY

Selection texts

DE AbflugortEN

...

PARAMETERS pa_city TYPE ...

SELECT-OPTIONS so_carr FOR ...

Point of departureAirline LH to

DE FluggesellschaftEN

SO_CARR…

Dictionary reference

Dictionary reference

Selection screen

Selection Texts

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.

Page 139: AC400 Programming in Financials

© SAP AG AC400 4-139

© SAP AG 2006

Databasetable

ABAP program

pa_car

LH

Selection screen

PARAMETERS pa_car TYPE s_carr_id.

...

LH

SELECT * FROM spfli

DATA wa_spfli TYPE spfli.

INTO wa_spfli

WHERE carrid = pa_car .

WRITE: / ...

ENDSELECT.

Using Parameters

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.

Page 140: AC400 Programming in Financials

© SAP AG AC400 4-140

© SAP AG 2006

Databasetable

ABAP program

Selection screen

SELECT-OPTIONSso_car FOR wa_spfli-carrid .

...

DATA wa_spfli TYPE spfli.

SELECT * FROM spfli

INTO wa_spfli

WHERE carrid IN so_car .

WRITE: / ...

ENDSELECT.

AA DL

( Selection conditions )Internal table so_car

sign option low highIIE

EQ

EQBT

LHAA DLBA

Using Select Options

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: sign to indicate whether the value or the interval should be included (I) or excluded from the range (E),

option for the operator (BT, ...): You will find all the possible operators in the keyword documentation for SELECT-OPTIONS,

low for the lower limit of an interval or individual value, 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: A similar inclusion query is also define for the IF statement.

Page 141: AC400 Programming in Financials

© SAP AG AC400 4-141

© SAP AG 2006

...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_carID '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....

Example: Authorization Check for the Selection Screen

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: If the user has display authorization for the airline that was entered, the program is to continue processing.

If the user has no display authorization, the selection screen should be displayed again with an error message in the status bar.

Page 142: AC400 Programming in Financials

© SAP AG AC400 4-142

© SAP AG 2006

Consistency checkat data input

Flexibleprogram flow

200

120

140

100

300

Type checks

Possible values

Input help? Formattingoptions

Dynpro Properties

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.

Page 143: AC400 Programming in Financials

© SAP AG AC400 4-143

© SAP AG 2006

Dynpro sequence

100

200

300

120

140CALL SCREEN 100.

ABAP program

Next dynpro = 0

Dynpro calls

You start a dynpro sequence by specifying the first dynpro as the start dynpro for a transaction code belonging to the "dialog transaction" type, or

by calling a dynpro from any ABAP processing block in the program. In this unit we will limit ourselves to the latter option.

Page 144: AC400 Programming in Financials

© SAP AG AC400 4-144

© SAP AG 2006

Properties Element listFlow logic

(flow control)

Dynpro numberShort descriptionDynpro typeNext dynpro. . .

PROCESS BEFORE OUTPUT.MODULE clear_ok_code.

PROCESS AFTER INPUT.MODULE user_command.

Layout

Departure

Screen Painter

Arrival

Layout editor

Field ACHAR20RequiredEntry field

...Field B

.... . .. . .

Dynpro Components

The following components belong to a dynpro: 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). Layout: - You can place elements on your dynpro. Elements that appear on the dynpro are called

screen elements. Element list: - This contains the properties of the screen elements such as position, size and data type.

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).

Page 145: AC400 Programming in Financials

© SAP AG AC400 4-145

© SAP AG 2006

Propertiesof an element

Element list

Create fieldswith Dictionary

reference

Toolbar

Graphical Layout Editor

Layout area

The Graphical Layout Editor

You can start other functions from the graphical Layout Editor: 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.

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. Element list: - This shows all the elements displayed on the dynpro together with the relevant attributes.

Attributes can be changed directly here too.

Page 146: AC400 Programming in Financials

© SAP AG AC400 4-146

© SAP AG 2006

100

...

CALL SCREEN 100.

...

MODULE abc OUTPUT....

ENDMODULE.

PBOMODULE abc.

MODULE xyz INPUT....

ENDMODULE.

PAIMODULE xyz.

ABAP program

Dynpro 100

Calling Modules

The ABAP statement CALL SCREEN <nnnn> interrupts processing of the processing block and calls the dynpro.

Two event blocks are available for each dynpro: 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.

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: 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.

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.

Page 147: AC400 Programming in Financials

© SAP AG AC400 4-147

© SAP AG 2006

PROCESS BEFORE OUTPUT. ...

BackSave

MODULE user_command_0100 INPUT.

CASE ok_code.WHEN 'BACK'. ...WHEN 'SAVE'. ...

ENDCASE.

ENDMODULE.

PROCESS AFTER INPUT.

ABAP program

MODULE user_command_0100.

Dynpro 100...

CALL SCREEN 100.

...

Analyzing the Function Code for PAI

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: For historical reasons, modules have no interface and no local variables. In modules you can access all the global data in the ABAP program.

Page 148: AC400 Programming in Financials

© SAP AG AC400 4-148

© SAP AG 2006

PROCESS BEFORE OUTPUT....

PROCESS AFTER INPUT.MODULE user_command_100.

MODULE user_command_100 INPUT.

ENDMODULE.

CancelYes No

Create object

PAI module USER_COMMAND_100 does not exist.Do you want to create the object?

Double-click

USER_COMMAND_0100PAI module

New includeFramework program

Include election

ZBC400_00_DYNPRO

Create PAI module

Screenpainter Dynpro flow control

ABAPEditor

...

Creating Modules Using Forward Navigation

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: Forward navigation: From the Screen Painter you create a module by double-clicking on the module name in the flow logic.

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.

Page 149: AC400 Programming in Financials

© SAP AG AC400 4-149

© SAP AG 2006

100

...

CALL SCREEN 100.

...

MODULE abc OUTPUT....

ENDMODULE.

PBOMODULE abc.

MODULE xyz INPUT....

ENDMODULE.

PAIMODULE xyz.

Dynpro 100

Next dynpro: 100

Fixed Screen Sequences

Dynpro attributes:

ABAP program

If the next dynpro for dynpro 100 is set to 100, the dynpro is processed again after PAI has finished.

Page 150: AC400 Programming in Financials

© SAP AG AC400 4-150

© SAP AG 2006

100

...

CALL SCREEN 100.

...

MODULE abc OUTPUT....

ENDMODULE.

PBOMODULE abc.

MODULE xyz INPUT....

ENDMODULE.

PAIMODULE xyz.

Dynpro 100

Dynpro attributes: Next dynpro: 0

Ending Dynpro Sequences - Fixed Rule

ABAP program

By specifying the next dynpro here, you determine that after the dynpro has been completely processed, processing continues at the dynpro callpoint.

Page 151: AC400 Programming in Financials

© SAP AG AC400 4-151

© SAP AG 2006

100

...

CALL SCREEN 100.

...

MODULE abc OUTPUT....

ENDMODULE.

PBOMODULE abc.

MODULE xyz INPUT.SET SCREEN 0.

ENDMODULE.

PAIMODULE xyz.

Dynpro 100

Dynpro attributes:Next dynpro: 100

0

ABAP program

Ending Dynpro Sequences - Variable Rule

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.

Page 152: AC400 Programming in Financials

© SAP AG AC400 4-152

© SAP AG 2006

DATA ok_code LIKE sy-ucomm.

START-OF-SELECTION.

...

AT LINE-SELECTION....

CALL SCREEN 100....

MODULE user_command_0100 INPUT.

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.

Syntax Example: Analyzing the Function Code

For our scenario, two pushbuttons should be caught: 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.

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.

Page 153: AC400 Programming in Financials

© SAP AG AC400 4-153

© SAP AG 2006

Flight data Edit Goto System Help

Help F1Select F2Back F3

. . .

Function keysettings

Change flight times… …

GUI title

Menu barToolbarApplication toolbarFunction key settings

Terms for the User Interface

GUI status

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.

Page 154: AC400 Programming in Financials

© SAP AG AC400 4-154

© SAP AG 2006

F2F9...

Toolbar%EXBACK RW

PICK

%PRI %SC P--

Menu bar Menu bar flight dataiApplication toolbar iFunction keys Function keys flight datai

Application toolbar flight data

P- P+ P++

?%SC+

ChooseRecommended function key settings

User-determined function keysF5F6...

<...> Select

Status in the Menu Painter – Function Keys

The key assignment is divided into three areas: 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.

Recommended function key settings: Functions are proposed here that should normally be assigned to specific function keys.

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.

Page 155: AC400 Programming in Financials

© SAP AG AC400 4-155

© SAP AG 2006

Menu bar Menu bar flight datai

Application toolbar iFunction keys Function keys flight datai

Application toolbar flight data

Flight data

Code Text

Edit Goto

Code Text Code TextPICK

%SC

%SC+

RW

Select

Search

Extend search

Cancel

PRI

%EX

ReturnBACKPrint

Save /Send

Exit

>

Status in the Menu Painter – Menu Bar

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.

Page 156: AC400 Programming in Financials

© SAP AG AC400 4-156

© SAP AG 2006

Menu bar

SCREEN

SCREEN

SCREENiii

Selection and Integrationof subobjects of an

already defined status

Application toolbar

Function keys

Including Existing Status Elements

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.

Page 157: AC400 Programming in Financials

© SAP AG AC400 4-157

© SAP AG 2006

Function code

Flight data Edit Goto

Code TextSelect

function codeBackBACK

Application toolbar iFunction keys Function keys flight datai

Application toolbar flight data

Menu bar Menu bar flight datai

1

Set to active/inactive

2

Deactivating Status Functions

To set an active or inactive status for functions, proceed as follows: Switch to change mode status by double-clicking and the Display Change icons. 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.

Page 158: AC400 Programming in Financials

© SAP AG AC400 4-158

© SAP AG 2006

SET TITLEBAR 'T_ABC'.

Program

Title code

Title

Create title

xxxxx

T_ABC

Change flight times

GUI interface: Title T_ABC does not exist.Do you want to create the object?

Cancel

Create object

Yes No

Confirm

START-OF-SELECTION block ( for list )or

PBO module ( for dynpro )

Double-click

Defining GUI Titles

There are three options for creating or maintaining a title: From the object list of the repository browser, by forward navigation from the ABAP Editor, or 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.

Page 159: AC400 Programming in Financials

© SAP AG AC400 4-159

© SAP AG 2006

• attr1• attr2• ...

• meth1• meth2• ...

Class(Formal description of objects)

Object attribute

Object methods

attr1 8

ABC

Objects (instances) of the class

attr2meth1

meth2

attr1 3

XYZattr2meth1

meth2

attr1 5

SAPattr2meth1

meth2

Concept of Object-Oriented Programming

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.

Page 160: AC400 Programming in Financials

© SAP AG AC400 4-160

© SAP AG 2006

ABAP program

DATA ref1 TYPE REF TO myclass.DATA ref2 TYPE REF TO myclass.

CREATE OBJECT ref1 ...

...

CREATE OBJECT ref2 ...

CALL METHOD ref1->meth1EXPORTING ...IMPORTING ...EXCEPTIONS ...

CALL METHOD ref2->meth1EXPORTING ...IMPORTING ...EXCEPTIONS ...

ref1 ref2

meth1meth2

meth2

meth1

Instantiation of Objects and Method Calls

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 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 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.

Page 161: AC400 Programming in Financials

© SAP AG AC400 4-161

© SAP AG 2006

AA00170064

LH04000402

Airlines

Tree control

http://www.sap.com

HTML viewer control

Grid control Picture control

CL_GUI_ALV_GRID CL_GUI_PICTURE

CL_GUI_HTML_VIEWER CL_SIMPLE_TREE_MODEL

EnjoySAP Controls as Standard Classes

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.

Page 162: AC400 Programming in Financials

© SAP AG AC400 4-162

© SAP AG 2006

17

64

AAAAAAAALHLHLHLHLH

1717

400

402

400400

402

2000-01-172000-02-202000-03-112000-05-192000-01-132000-02-262000-03-212000-03-042000-05-28

USDUSDUSDUSDEUREUREUREUREUR

513,69

1234,561234,56

513,69513,69369,00

1234,561234,56

1234,56

A321

747-400

A310-300

A319A319

A310-300A310-300

A321

747-400

Details

Sort

Search

Filter

Total

Print

Download

Display variant

Toolbar

The SAP Grid Control

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.

Page 163: AC400 Programming in Financials

© SAP AG AC400 4-163

© SAP AG 2006

Area

Customcontainercontrol

SAP grid control

Dynpro 100 ProcessBeforeOutput

ProcessAfterInput

PBO module

Control area

...

...

Container instance

Grid instance

The Custom Container as a Dynpro Object

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.

Page 164: AC400 Programming in Financials

© SAP AG AC400 4-164

© SAP AG 2006

Area

Customcontainercontrol

SAP grid control

Container instance

Grid instance

CL_GUI_CUSTOM_CONTAINER

CL_GUI_ALV_GRID

CLASS BUILDER

The SAP Grid in the Custom Container

Global classes (object types) are available in the Class Builder for steering the custom container control and the ALV grid control : CL_GUI_CUSTOM_CONTAINER and CL_GUI_ALV_GRID.

Page 165: AC400 Programming in Financials

© SAP AG AC400 4-165

© SAP AG 2006

Int. typesEvents

SuperclassesMethodsCONSTRUCTOR

CL_GUI_CUSTOM_CONTAINER

Class CL_GUI_CUSTOM_CONTAINER

AttributesInterfacesProperties Methods

Parameter for method CONSTRUCTOR

ParameterPARENTCONTAINER_NAME...

Value Optional ... Associated type... Description

Mandatory parameterof the CONSTRUCTOR methodhave to be supplied with CREATEOBJECT.

Class Builder

Is called implicitly withCREATE OBJECT

The Constructor Method

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.

Page 166: AC400 Programming in Financials

© SAP AG AC400 4-166

© SAP AG 2006

SuperclassesInterfacesAttributesMethods. . .CONSTRUCTOR

. . .

SET_TABLE_FOR_FIRST_DISPLAY

. . .

REFRESH_TABLE_DISPLAY

. . .

RedefinitionsEvents

CL_GUI_ALV_GRID If an implicit call is made atCREATE OBJECT ;

Mandatory parameter :i_parent

Mandatory parameter :it_outtab (Display data)

Optional parameter :i_structure_name(global structure for describingthe table line type)

Important SAP Grid Control Methods

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: The pointer to the container control instance must be transferred to the constructor.

SET_TABLE_FOR_FIRST_DISPLAY: 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.

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.

Alternatively, you can also construct a so-called field catalog and transfer it to it_fieldcatalog.

REFRESH_TABLE_DISPLAY: You only need to execute this method if the contents of the internal table have changed since the first time they were displayed.

Page 167: AC400 Programming in Financials

© SAP AG AC400 4-167

© SAP AG 2006

Customcontrolarea

Type: Custom controlName: CONTAINER_1

ResizingVertical : Min. lines: 5Horizontal : Min. columns: 20

C

Screen Painter

Placing the Custom Control Container on the Dynpro

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: 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.

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.

Page 168: AC400 Programming in Financials

© SAP AG AC400 4-168

© SAP AG 2006

container_r

gdt_spfli

ok_code

grid_r

Custom Control Containers as Data Objects

DATA gdt_spfli TYPE sbc400_t_spfli.

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.

START-OF-SELECTION.

* fill internal table ...

CALL SCREEN 100.

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.

Page 169: AC400 Programming in Financials

© SAP AG AC400 4-169

© SAP AG 2006

container_r

grid_r

Instantiation of Custom Control Containers

MODULE create_control OUTPUT.

IF container_r IS INITIAL.

CREATE OBJECT container_rEXPORTING container_name = 'CONTAINER_1'

CREATE OBJECT grid_rEXPORTING i_parent = container_r.

...

ENDIF.

ENDMODULE.

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.

Page 170: AC400 Programming in Financials

© SAP AG AC400 4-170

© SAP AG 2006

MODULE create_control OUTPUT.

IF container_r IS INITIAL.

CREATE OBJECT container_rEXPORTING container_name = 'CONTAINER_1' .

CREATE OBJECT grid_rEXPORTING i_parent = container_r .

ENDIF.

ENDMODULE.

container_r

grid_r

CALL METHOD CALL METHOD grid_rgrid_r-->>set_table_for_first_displayset_table_for_first_display

EXPORTING EXPORTING i_structure_namei_structure_name = 'SPFLI'= 'SPFLI'CHANGING CHANGING it_outtabit_outtab = = gdt_spfligdt_spfli ..

Containing SAP Grids

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. 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.

Page 171: AC400 Programming in Financials

© SAP AG AC400 4-171

© SAP AG 2006

Dialogs are programmed with the help of dynprotechnology.

By using the custom container, ALV reports can be linked to dynpro technology.

Dialogs and ALV Reports: Summary

Page 172: AC400 Programming in Financials

© SAP AG AC400 4-172

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.

Page 173: AC400 Programming in Financials

© SAP AG AC400 4-173

Page 174: AC400 Programming in Financials

© SAP AG AC400 4-174

Solutions

Unit 1: Dialogs and ALV Reports

1-1 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”.

Page 175: AC400 Programming in Financials

© SAP AG AC400 4-175

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.

Page 176: AC400 Programming in Financials

© SAP AG AC400 4-176

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.

Page 177: AC400 Programming in Financials

© SAP AG AC400 4-177

Page 178: AC400 Programming in Financials

© SAP AG AC400 5-178

© SAP AG 2006

Course Overview Diagram: Customer Enhancements

Customer EnhancementsCustomer EnhancementsThe ABAP WorkbenchThe ABAP Workbench

First Attempts at ProgrammingFirst Attempts at Programming

Template AllocationTemplate Allocation

ExtractionExtraction

Dialogs and ALV ReportsDialogs and ALV Reports

Page 179: AC400 Programming in Financials

© SAP AG AC400 5-179

© SAP AG 2006

Customer Enhancements - Unit Overview

This unit presents customer modifications and enhancements. A Business Add-In is implemented.

Contents:

Page 180: AC400 Programming in Financials

© SAP AG AC400 5-180

© SAP AG 2006

Differentiate between modifications and enhancements

Implement BAdIs

Customer Enhancements: Unit Objectives

At the conclusion of this unit, you will be able to:

Page 181: AC400 Programming in Financials

© SAP AG AC400 5-181

© SAP AG 2006

R/3 Business Applications

(Standard SAP system)

Customerprograms

Customdevelop-

ment

Enhance-ment

ModificationCustomizing

Customizing ABAPWorkbench

Personalizing

Change Levels

You can adapt the R/3 system to your requirements in the following ways: Customizing: For configuring your business processes and functions using the Implementation Guide. Possible changes are thus planned and organized.

Personalizing: For changing the global display properties of fields (default settings, hidden/visible), user-specific menu navigation.

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.

Enhancement: For creating customer Repository objects that are integrated in SAP Repository objects.

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.

Page 182: AC400 Programming in Financials

© SAP AG AC400 5-182

© SAP AG 2006

Originals and Copies

Copy

Original

Copy

Copy

Original

SAP object SAP object SAP object

Customer object Customer object

Transport ofdevelopment

Development system Follow-on system

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.

Page 183: AC400 Programming in Financials

© SAP AG AC400 5-183

© SAP AG 2006

Corrections and Repairs

Modifiedcopy

Correctedoriginal

Copy

Copy

Correctedoriginal

SAP object

Transportof correction

SAP object SAP object

Customer object Customer object

Correction

RepairCorrectionTransport

of the repair

Follow-on systemDevelopment system

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.

Page 184: AC400 Programming in Financials

© SAP AG AC400 5-184

© SAP AG 2006

Modifications During an Upgrade

Modifiedcopy CopyCorrected

original

SAP object

Transportof adjustment

SAP object SAP object

UpgradeUpgrade

Modificationadjustment

Follow-on system

Correctedoriginal Copy

Customer objectCustomer object

Development system

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.

Page 185: AC400 Programming in Financials

© SAP AG AC400 5-185

© SAP AG 2006

Procedure for Functional Changes

ModificationCustom development withSAP program as template

No

No

Yes

Does the standard SAP systemcontain a similar function at all?

No

Does theSAP application support

the integration of additional functions withenhancements? Yes

Enhancement

Is there a standard functionthat can be adapted to the customer's requirements

in Customizing?Yes

CustomizingPersonalizing

No

Custom developmentCSP solution

Cus

tom

izin

gD

evel

opm

ent

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 The Customizing or personalizing options do not satisfy your requirements Suitable enhancements or user exits are not available or planned Copying the SAP object to the customer namespace is not practical.

Page 186: AC400 Programming in Financials

© SAP AG AC400 5-186

© SAP AG 2006

ABAP Workbench Change Levels

R/3 Business Applications

(Standard SAP system)

Customerprograms

With call of SAP objectsWithout call of SAP objects

Customdevelopment

Modification Assistant

Modification

User exits

ABAP DictionaryTablesData elements

Program enhancementsFunction module exitsBusiness TransactionEventsBusiness Add-Ins

Menu enhancementsMenu exitsBusiness Add-Ins

Screen enhancementsScreen exitsBusiness Add-Ins

Enhancement

Modifications are changes to SAP objects in customer systems. They are: Located at user exits (subroutines reserved for customers in objects within the SAP namespace)

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: In the ABAP program (function module exit) In the GUI (menu exit) In screens for displaying a subscreen in a screen area provided by SAP (screen exit) As runs of custom program sections based on a screen field (field exit) In tables or structures of the ABAP Dictionary (table enhancement).

Page 187: AC400 Programming in Financials

© SAP AG AC400 5-187

© SAP AG 2006

Program Enhancements: Functionality

*** SAP program ************************************

PROGRAM <name of SAP program>.

<<EnhancementEnhancement callcall>><Object in customer namespace>

Customer exit Exit function module

Business Transaction Event Function module

Business Add-In Method

The basic purpose of a program enhancement is to call an object in the customer namespace. There are various ways of doing this: 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. Business Transaction Events - A function module is called dynamically by the SAP application program in the customer

namespace. Business Add-Ins - The application program calls a method of a class or instance of a class. This class is in

the customer namespace.

Page 188: AC400 Programming in Financials

© SAP AG AC400 5-188

© SAP AG 2006

Program Enhancements: SAP and Customer

SAP Customer

Customer exit:Function module exit FM coding

Business Transaction EventsFunction module

in customernamespace

Business Add-Ins Method in customer class

CallAdmin.

InterfaceDocumentation

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.

Page 189: AC400 Programming in Financials

© SAP AG AC400 5-189

© SAP AG 2006

SAP Customer

PROGRAM ... ....

*Original Coding...........

...*Original Coding.....

SAP Program

Modifications

PROGRAM ... ....

*Original Coding...........

...*Original Coding.....

* Added/changed by customer* Coding

SAP Program

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.

Page 190: AC400 Programming in Financials

© SAP AG AC400 5-190

© SAP AG 2006

Business Add-Ins: Components

BAdI

FCodes

Program<prog> +ABC

Function Code

Properties.

Multiple Use

Filter Dependent

INTERFACE<badi-interface>.

DATA: a1 ...

ENDINTERFACE.

METHODS m2 ...

METHODS m1EXPORTING

e_par1e_par2

IMPORTINGi_par1.

Subscreens

Calling Program<prog> 0200

Screen No.ABCDSubscreen Area

Scr..Desc.

GeneratedBAdIClass

Business Add-Ins group the components of an enhancement. A Business Add-In can provide the following enhancement options: 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.

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.

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: Interface Generated class (BAdI class) that implements the interface

The generated class (BAdI class) has the following tasks: Filtering: If a BAdI is to be executed under certain conditions only, the BAdI class ensures that only the valid implementations are called.

Control: The BAdI class calls the active implementations.

Page 191: AC400 Programming in Financials

© SAP AG AC400 5-191

© SAP AG 2006

Business Add-Ins: Flowchart

Application prog.Service class

CL_EXITHANDLER

Instance ofBAdI class

<badi-class>BAdI: Instance ofimplement. class

Process activeimplementations

11

22

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.

Page 192: AC400 Programming in Financials

© SAP AG AC400 5-192

© SAP AG 2006

Business Add-Ins: Calling Program

REPORT <program_using_badi>.

START-OF-SELECTION.

END-OF-SELECTION.

DATA: r_varTYPE REF TO <badi-interface>.

CALL METHOD cl_exithandler=>get_instance

CHANGINGinstance = r_var.

CALL METHOD r_var->methodEXPORTING

<i_variables>IMPORTING

<e_variables>.

r_var

1

2

Instance of<badi-class>

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).

Page 193: AC400 Programming in Financials

© SAP AG AC400 5-193

© SAP AG 2006

Implementing BAdIs: Methods

FCodesInterfaceProperties

MethodBAdI methodDescription

<badi-interface>Interface Name <impl-class>Name of Implementing Class

<method>

Class Builder: Edit Method <badi-interface>~<m...>

METHOD <badi-interface>~<method>.

*...

ENDMETHOD.

You can choose any name for the implementing class. However, SAP recommends that you follow the proposed naming convention. The proposed name consists of Namespace prefix, Y or Z CL_ (stands for class) IM_ (stands for implementation) 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.

Page 194: AC400 Programming in Financials

© SAP AG AC400 5-194

© SAP AG 2006

Implementing BAdIs: Private Methods

Class Builder: Edit Method <badi-interface>~<m...>

METHOD <badi-interface>~<method>.

ENDMETHOD.

CALL METHOD <CALL METHOD <priv_methodpriv_method> EXPORTING ... .> EXPORTING ... .

Class Builder: Change Class <impl-class>

EventsMethodsProperties

MethodNew method in implementationDescription

<priv_method>Type

Parameters Exceptions

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.

Page 195: AC400 Programming in Financials

© SAP AG AC400 5-195

© SAP AG 2006

Implementing BAdIs: Activation

Business Add-Ins: Implem. Maintenance Initial Screen

<impl>Implementation Name

Activate

Undo activationDisplay CreateChange

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.

Page 196: AC400 Programming in Financials

© SAP AG AC400 5-196

© SAP AG 2006

Modifications must be maintained when SAP Notes and system upgrades are implemented.

SAP recommends that customer enhancements do not contain modifications.

BAdIs are used in particular to implement customer enhancements without the need for modifications.

Customer Enhancements – Unit Summary:

Page 197: AC400 Programming in Financials

© SAP AG AC400 5-197

Page 198: AC400 Programming in Financials

© SAP AG AC400 5-198

Exercises

Unit: Customer Enhancements

At the conclusion of this exercise, you will be able to: • Explain the concept of BAdIs • Implement BAdIs

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.

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.

Page 199: AC400 Programming in Financials

© SAP AG AC400 5-199

Page 200: AC400 Programming in Financials

© SAP AG AC400 5-200

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 "FI-GL". 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.

Page 201: AC400 Programming in Financials

© SAP AG AC400 5-201

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.

Page 202: AC400 Programming in Financials

© SAP AG AC400 6-202

© SAP AG 2006

Overview Diagram: Extraction

ExtractionExtraction

The ABAP WorkbenchThe ABAP Workbench

First Attempts at ProgrammingFirst Attempts at Programming

Template AllocationTemplate Allocation

Customer EnhancementsCustomer Enhancements

Dialogs and ALV ReportsDialogs and ALV Reports

Page 203: AC400 Programming in Financials

© SAP AG AC400 6-203

© SAP AG 2006

Extraction – Overview

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.

Contents:

Page 204: AC400 Programming in Financials

© SAP AG AC400 6-204

© SAP AG 2006

Describe how data is extracted to the BW system

Write your own extraction functions

Extraction: Unit Objectives

At the conclusion of this unit, you will be able to:

Page 205: AC400 Programming in Financials

© SAP AG AC400 6-205

© SAP AG 2006

The Administrator Workbench

Modeling

Monitoring

Scheduling

AdministratorWorkbench

BW creation

Maintenance

Administration

Schedule datatransfer

Load data

Monitor data transfer

Monitor update process

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: To create all the components of Business Information Warehouse, including Customizing settings.

To schedule data transfer from different data sources. To load data To monitor data transfer and data updates

Page 206: AC400 Programming in Financials

© SAP AG AC400 6-206

© SAP AG 2006

BW server

Transfer structure

SAP systemFile system

Communication structure

Transfer structure

Extractionstructure

Transfer structureTransfer structure

DataSource DataSource

Flat fileDataSource

DataSource(replicate)

DataSource(replicate)

InfoSource

Data targets

Transfer structure

Extractionstructure

– File

Mapping & transfer rules

Update rules

Data Flow from the Source to the Target System

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".

Page 207: AC400 Programming in Financials

© SAP AG AC400 6-207

© SAP AG 2006

BW server

SAP source system

DataSource

When the DataSource is replicated, fields in theextraction structure are used asa template for the transfer structure in BW.

1

2When the (local) transferrules are activated, the transfer structure is generated bothin the BW system and in theSAP source system.

Extractionstructure

Transfer structure

Transfer structure

21

DataSource (replicate)

Verification Between the Source and Target System

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.

Page 208: AC400 Programming in Financials

© SAP AG AC400 6-208

© SAP AG 2006

Transfer RulesTransfer structure

Communication Str./Transfer Rules

0COMP_CODE

InfoObject Tp Rule0CO_AREACOSTC##0CURRENCY0PROFIT_CTR

0CO_AREACOSTC##0CURRENCY0PROFIT_CTR0COMP_CODE

InfoObject – Field Assignment

InfoObject Field

0COMP_CODE0PROFIT_CTR0CURRENCYCOSTC##

KOKRS

WAERSPRCTRBUKRS

KOSTL0CO_AREA

IDOC

Transfer Method

PSA

InfoSource COSTC## GR## Cost Center 13 Communication Structure

InfoObject Description Status Type Length …

0CO_AREACOSTC##0CURRENCY0PROFIT_CTR

CHARCHAR

CHARCUKY

134

510

Controlling areaGR## Cost Center 13CurrencyProfit Center

Source System IDES R/3

DataSource ZGR##CC_ATTR

Defining Transfer Rules

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: The fields are copied from the transfer structure and are not modified. You can assign a fixed value to a field. 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.

Page 209: AC400 Programming in Financials

© SAP AG AC400 6-209

© SAP AG 2006

You can use function modules to select the data in the source system that you want to extract.

Extraction – Unit Summary:

Page 210: AC400 Programming in Financials

© SAP AG AC400 6-210

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 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.

Page 211: AC400 Programming in Financials

© SAP AG AC400 6-211

1-2 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.

Page 212: AC400 Programming in Financials

© SAP AG AC400 6-212

Solutions

Unit: Extraction

1-1 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.

Page 213: AC400 Programming in Financials

© SAP AG AC400 6-213

1-1-4 Log onto the BW system. Replicate the DataSource.

Page 214: AC400 Programming in Financials

© SAP AG AC400 6-214

1-2 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.

Page 215: AC400 Programming in Financials

© SAP AG AC400 7-215

© SAP AG 2006

Overview Diagram: Template Allocation

Template AllocationTemplate Allocation

The ABAP Workbench The ABAP Workbench

First Attempts at ProgrammingFirst Attempts at Programming

Customer EnhancementsCustomer Enhancements

ExtractionExtraction

Dialogs and ALV ReportsDialogs and ALV Reports

Page 216: AC400 Programming in Financials

© SAP AG AC400 7-216

© SAP AG 2006

Template Allocation – Unit Overview

This unit presents the concept of template allocation and describes interfaces that allow you to implement specific data access and cost calculations.

Contents:

Page 217: AC400 Programming in Financials

© SAP AG AC400 7-217

© SAP AG 2006

Use your own methods in template allocation.

Template Allocation: Unit Objectives

At the conclusion of this unit, you will be able to:

Page 218: AC400 Programming in Financials

© SAP AG AC400 7-218

© SAP AG 2006

The Template as a Costing Tool

Template

BOM

No. BOMItems

Standard cost estimate

Lot size

Material master dataWeight

External-systems

Meas. data

Routing

No. work centers

CO-PA

No. value fields

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.

Page 219: AC400 Programming in Financials

© SAP AG AC400 7-219

© SAP AG 2006

Product Costing with Templates

Rout -ing

Bill ofmaterials

Material Lot size

CO - valuesMaterialActivitiesOverheadProcesses:300000300100

Costelement:R-4000

Functions

Template Prod_1

Material:R-4000

Statisticalkey figures

Processes

OtherSAP sources

Process

quantities

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".

Page 220: AC400 Programming in Financials

© SAP AG AC400 7-220

© SAP AG 2006

Material:R 4000

Unit cost estimate/standard cost estimate

Derivation of Templates in the Cost Estimate

Template Prod_1

Template Prod_2

10

2010

20

QuantityValuation time

CleaningQ. insp.

Process3020

Order-startDelivery

Template Prod_3

Main template

Costing sheet

Overheadkey

Overhead group:SAP900

Valuationvariant 001

Costingvariant PPC1

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.

Page 221: AC400 Programming in Financials

© SAP AG AC400 7-221

© SAP AG 2006

Template for cost elementPl. Qty. Pl. Activ.Object Act. Qty. Act. Activ.. Act. Val. Ev.

Whichprocess?

Which process quantity?When?

Under what conditions?

Template Rows as Formula Vectors

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.

Page 222: AC400 Programming in Financials

© SAP AG AC400 7-222

© SAP AG 2006

"Functions" as Form Components

Template for cost elementPl. Qty. Pl. Activ.Object Act. Qty. Act. Activ.. Act. Val. Ev.

Whichprocess?

How much of the processquantity?

When?

Under what conditions?

Functions Functi

ons

Functions

Functions

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.

Page 223: AC400 Programming in Financials

© SAP AG AC400 7-223

© SAP AG 2006

Under what conditions?

Subenvironment 101: ProcessesFunctions: ......

......

Subenvironment 103: MaterialFunctions: Material_Characteristic_value

......

Subenvironment 107: General dataFunctions: ......

......

Which process?

When?

Whichprocess quantity?

PP productionorder

Subenvironments as Function Groups

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.

Page 224: AC400 Programming in Financials

© SAP AG AC400 7-224

© SAP AG 2006

Environments and Subenvironments

Subenvironment 105:Routing

Subenvironment 103:Material

New functions

Subenvironment 107:General data

Environment 001: mat. c. est./production orders

Environment 003: matl c. est.without quantity structure

Environment PAC:costing-based profitability analysis

Subenvironment 101:Sender process

StandardOptional

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.

Page 225: AC400 Programming in Financials

© SAP AG AC400 7-225

© SAP AG 2006

Function Modules as Functions

Functions

Table field ABAP-Functions

Storage location: 0001

Material Master View:MRP. 2

Procurement

K_ABC_ORDER_MAT_CONFIRMATION

Table name:MARC

Field name:LGPRO

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.

Page 226: AC400 Programming in Financials

© SAP AG AC400 7-226

© SAP AG 2006

You can create your own allocation methods in template allocation.

By doing so, you can implement your own access types and cost calculations.

The allocation methods are realized by function modules.

Template Allocation – Unit Summary:

Page 227: AC400 Programming in Financials

© SAP AG AC400 7-227

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 R-F100. 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.

Page 228: AC400 Programming in Financials

© SAP AG AC400 7-228

Page 229: AC400 Programming in Financials

© SAP AG AC400 7-229

Solutions

Unit: Function Modules in Template Allocation

1-1 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

Page 230: AC400 Programming in Financials

© SAP AG AC400 7-230

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: ls_mara TYPE mara. DATA: ld_temp_faktor TYPE i. DATA: ld_quantity TYPE tplic_rval-value. DATA: ld_wa_rval TYPE tplic_rval. * Clear output CLEAR rtable_val[]. * Get master data SELECT SINGLE * FROM mara INTO ls_mara

Page 231: AC400 Programming in Financials

© SAP AG AC400 7-231

WHERE matnr = id_matnr. * Master record found? CHECK sy-subrc = 0. * Evaluate temperature condition CASE ls_mara-tempb. WHEN '01'. ld_temp_faktor = 1. WHEN '02'. ld_temp_faktor = 2. WHEN '03'. ld_temp_faktor = 3. WHEN OTHERS. ENDCASE. * 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-1-4 Test your function module for material R-F100. 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 R-F100. 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

Page 232: AC400 Programming in Financials

© SAP AG AC400 7-232

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"

Page 233: AC400 Programming in Financials

© SAP AG AC400 7-233

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"

Page 234: AC400 Programming in Financials

© SAP AG AC400 7-234

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.

Page 235: AC400 Programming in Financials

© SAP AG AC400 8-235

© SAP AG 2006

Appendix

Optional exercise 1 –Write a program for maintaining customer address data

Optional Exercise 2 –Write a program for opening and closing FI periods

Optional exercise 3 –Program a report for master data groups in Cost Accounting

Page 236: AC400 Programming in Financials

© SAP AG AC400 8-236

Page 237: AC400 Programming in Financials

© SAP AG AC400 8-237

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

Page 238: AC400 Programming in Financials

© SAP AG AC400 8-238

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.

Page 239: AC400 Programming in Financials

© SAP AG AC400 8-239

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)

Page 240: AC400 Programming in Financials

© SAP AG AC400 8-240

(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" Database table ADRC Function "Copy" From Table ADRC To Table Y##ADRC Function “Local Object” Tools → ABAP Workbench → Development → ABAP Dictionary (SE11) Select "Database table" Database table Y##ADRC Function “Change” Tab page "Delivery and Maintenance" Date Browser… X Display/Maintenance Allowed Function "Activate" 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".

Tools → ABAP Workbench → Development → ABAP Dictionary (SE11) Select "Domain" Domain Y##ACTION Function "Create" Short description Action for program Y##Customer Tab page "Definition" Data Type "CHAR" No. Characters 10 Tab page "Value Range" Fixed Value INITI

Page 241: AC400 Programming in Financials

© SAP AG AC400 8-241

Short Text Initialize Fixed Value ACTIV Short Text Activate changes Fixed Value REACT Short Text Undo changes Function "Activate" Function “Local Object” F1-3 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" Data Type Y##ACTION Function "Create" Select "Data Element" Short Text Action for program Y##Customer Tab page "Data Type" Select "Elementary Type" Select "Domain" Domain Y##ACTION Tab page "Field Label" Short label Action Medium label Action Long label Action Heading Action Function "Activate" Function "Local Object" F1-4 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

Page 242: AC400 Programming in Financials

© SAP AG AC400 8-242

View Local objects Local objects AC400-## Select the rood node $TMP AC400-## Context menu Create → Program Program Y##CUSTOMER (without top include) Title Maintain future customer master data Type "1 Executable Program" Function "Save" Function "Local Object" 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 LIKE sy-datum VALUE '00010101'. CONSTANTS: gc_last_date LIKE sy-datum VALUE '99991231'.

Page 243: AC400 Programming in Financials

© SAP AG AC400 8-243

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

Page 244: AC400 Programming in Financials

© SAP AG AC400 8-244

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 = is_kna1-adrnr AND date_from = gc_first_date AND nation = 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. " initialize

Page 245: AC400 Programming in Financials

© SAP AG AC400 8-245

*&---------------------------------------------------------------------* *& 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: ls_adrc TYPE ys_adrc. DATA: ls_ac400adrc TYPE ys_ac400adrc. DATA: ls_adrc_old TYPE ys_adrc. DATA: ls_adrc_new TYPE ys_adrc. SELECT SINGLE * FROM adrc INTO ls_adrc WHERE addrnumber = is_kna1-adrnr AND date_from = gc_first_date AND nation = 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. " activate

Page 246: AC400 Programming in Financials

© SAP AG AC400 8-246

*&---------------------------------------------------------------------* *& Form react *&---------------------------------------------------------------------* FORM react USING id_date TYPE date_from is_kna1 TYPE ys_kna1. * data DATA: ls_adrc_r TYPE ys_adrc. DATA: ls_adrc_f TYPE ys_adrc. DATA: lt_adrc TYPE yt_adrc. DATA: ld_len LIKE sy-tabix. SELECT * FROM adrc INTO TABLE lt_adrc WHERE addrnumber = is_kna1-adrnr AND date_from <= id_date AND nation = gc_empty_nation. SORT lt_adrc ASCENDING BY date_from. DESCRIBE TABLE lt_adrc LINES ld_len. IF ld_len > 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. " react

Page 247: AC400 Programming in Financials

© SAP AG AC400 8-247

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.

Page 248: AC400 Programming in Financials

© SAP AG AC400 8-248

Page 249: AC400 Programming in Financials

© SAP AG AC400 8-249

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.

Page 250: AC400 Programming in Financials

© SAP AG AC400 8-250

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 TYPE t001b. TYPES: yt_t001b TYPE TABLE OF ys_t001b. TYPES: ys_ac400t001b TYPE ac400t001b. TYPES: yt_ac400t001b TYPE TABLE OF ys_ac400t001b. * Parameters PARAMETERS: p_opvar TYPE opvar OBLIGATORY. * Data DATA: ls_t001 TYPE t001. DATA: ls_t001b_old TYPE ys_t001b. DATA: ls_t001b_new TYPE ys_t001b. DATA: lt_t001b_old TYPE yt_t001b. DATA: lt_t001b_new TYPE yt_t001b. DATA: ls_ac400t001b TYPE ys_ac400t001b. DATA: lt_ac400t001b TYPE yt_ac400t001b. DATA: ld_result TYPE c. DATA: ld_day_found TYPE 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.

Page 251: AC400 Programming in Financials

© SAP AG AC400 8-251

* 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.

Page 252: AC400 Programming in Financials

© SAP AG AC400 8-252

* 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 t001b * INTO es_t001b INTO TABLE et_t001b WHERE rrcty = '0' AND bukrs = id_opvar. * AND mkoar = '+' * AND 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

Page 253: AC400 Programming in Financials

© SAP AG AC400 8-253

CLEAR et_ac400t001b[]. * Select SELECT * FROM ac400t001b INTO TABLE et_ac400t001b WHERE opvar = id_opvar AND 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.

Page 254: AC400 Programming in Financials

© SAP AG AC400 8-254

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: ld_systemday TYPE n LENGTH 2. DATA: ld_actbuper TYPE poper. DATA: ld_actgjahr TYPE bdatj. DATA: ld_check TYPE 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. " check_day

Page 255: AC400 Programming in Financials

© SAP AG AC400 8-255

*&---------------------------------------------------------------------* *& 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,

Page 256: AC400 Programming in Financials

© SAP AG AC400 8-256

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. " save

Page 257: AC400 Programming in Financials

© SAP AG AC400 8-257

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.

Page 258: AC400 Programming in Financials

© SAP AG AC400 8-258

Page 259: AC400 Programming in Financials

© SAP AG AC400 8-259

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.

Page 260: AC400 Programming in Financials

© SAP AG AC400 8-260

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"

Page 261: AC400 Programming in Financials

© SAP AG AC400 8-261

* 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 TYPE yt_setheader. DATA: gd_setclstext TYPE setclstext. DATA: go_container TYPE REF TO cl_gui_custom_container. DATA: go_alv TYPE 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.

Page 262: AC400 Programming in Financials

© SAP AG AC400 8-262

* 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.

Page 263: AC400 Programming in Financials

© SAP AG AC400 8-263

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 status PERFORM remind_status USING 'SET' CHANGING 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.

Page 264: AC400 Programming in Financials

© SAP AG AC400 8-264

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

Page 265: AC400 Programming in Financials

© SAP AG AC400 8-265

CHANGING cd_setclstext. * New other selection WHEN 'NEW'. CALL METHOD go_alv->refresh_table_display. * Maintain cd_setclstext PERFORM get_setclstext USING is_setheader CHANGING 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

Page 266: AC400 Programming in Financials

© SAP AG AC400 8-266

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. " get_setclstext