cookbook bol app crm2007

37
Business Object Layer (BOL) Application Programming Guide SAP ® CRM 2007 Target Audience System administrators Technology consultants Document version: 1.0 – July 2008

Upload: jacques-storme

Post on 09-Mar-2015

1.534 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Cookbook BOL App CRM2007

Business Object Layer (BOL)Application Programming Guide

SAP® CRM 2007

Target Audience

System administrators

Technology consultants

Document version: 1.0 – July 2008

Page 2: Cookbook BOL App CRM2007

© Copyright 2007 SAP AG. All rights reserved.

No part of this publication may be reproduced or transmitted in anyform or for any purpose without the express permission of SAP AG.The information contained herein may be changed without priornotice.

Some software products marketed by SAP AG and its distributorscontain proprietary software components of other software vendors.

Microsoft, Windows, Outlook, and PowerPoint are registeredtrademarks of 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, Informix, i5/OS, POWER, POWER5, OpenPower andPowerPC are trademarks or registered trademarks of IBM Corporation.

Adobe, the Adobe logo, Acrobat, PostScript, and Reader are eithertrademarks or registered trademarks of Adobe Systems Incorporated inthe United States and/or other countries.

Oracle is a registered trademark of Oracle Corporation.

UNIX, X/Open, OSF/1, and Motif are registered trademarks of theOpen Group.Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame,VideoFrame, and MultiWin are trademarks or registered trademarks ofCitrix Systems, Inc.

HTML, XML, XHTML and W3C are trademarks or registeredtrademarks of W3C®, World Wide Web Consortium, MassachusettsInstitute of Technology.

Java is a registered trademark of Sun Microsystems, Inc.

JavaScript is a registered trademark of Sun Microsystems, Inc., usedunder license for technology invented and implemented by Netscape.

MaxDB is a trademark of MySQL AB, Sweden.

SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, andother SAP products and services mentioned herein as well as theirrespective logos are trademarks or registered trademarks of SAP AGin Germany and in several other countries all over the world. All otherproduct and service names mentioned are the trademarks of theirrespective companies. Data contained in this document servesinformational purposes only. National product specifications mayvary.

These materials are subject to change without notice. These materialsare provided by SAP AG and its affiliated companies ("SAP Group")for informational purposes only, without representation or warranty ofany kind, and SAP Group shall not be liable for errors or omissionswith respect to the materials. The only warranties for SAP Groupproducts and services are those that are set forth in the expresswarranty statements accompanying such products and services, if any.Nothing herein should be construed as constituting an additionalwarranty.

SAP Library document classification: PUBLIC

DisclaimerSome components of this product are based on Java™. Anycode change in these components may cause unpredictableand severe malfunctions and is therefore expressivelyprohibited, as is any decompilation of these components.

Any Java™ Source Code delivered with this product isonly to be used by SAP’s Support Services and may not bemodified or altered in any way.

Documentation in the SAP Service MarketplaceYou can find this documentation at the following address:http://service.sap.com/

SAP AGDietmar-Hopp-Allee 1669190 WalldorfGermanyT +49/18 05/34 34 24F +49/18 05/34 34 20www.sap.com

Page 3: Cookbook BOL App CRM2007

Terms for Included OpenSource SoftwareThis SAP software contains also the third party opensource software products listed below. Please note that forthese third party products the following special terms andconditions shall apply.1. This software was developed using ANTLR.2. gSOAPPart of the software embedded in this product is gSOAPsoftware. Portions created by gSOAP are Copyright(C) 2001-2004 Robert A. van Engelen, Genivia inc. AllRights Reserved.THE SOFTWARE IN THIS PRODUCT WAS IN PARTPROVIDED BY GENIVIA INC AND ANY EXPRESSOR IMPLIED WARRANTIES, INCLUDING, BUTNOT LIMITED TO, THE IMPLIED WARRANTIESOF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE ARE DISCLAIMED. INNO EVENT SHALL THE AUTHOR BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; ORBUSINESS INTERRUPTION) HOWEVER CAUSEDAND ON ANY THEORY OF LIABILITY, WHETHERIN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITYOF SUCH DAMAGE.3. SAP License Agreement for STLportSAP License Agreement for STLPort betweenSAP AktiengesellschaftSystems, Applications, Products in Data ProcessingNeurottstrasse 1669190 Walldorf, Germany(hereinafter: SAP)andyou

(hereinafter: Customer)a) Subject Matter of the AgreementA) SAP grants Customer a non-exclusive,non-transferrable, royalty-free license to usethe STLport.org C++ library (STLport) and itsdocumentation without fee.B) By downloading, using, or copying STLport orany portion thereof Customer agrees to abideby the intellectual property laws, and to all ofthe terms and conditions of this Agreement.C) The Customer may distribute binaries compiledwith STLport (whether original or modified)without any royalties or restrictions.D) Customer shall maintain the followingcopyright and permissions notices on STLportsources and its documentation unchanged:Copyright 2001 SAP AGE) The Customer may distribute original ormodified STLport sources, provided that:o The conditions indicated in the abovepermissions notice are met;o The following copyright notices are retainedwhen present, and conditions provided inaccompanying permission notices are met:Copyright 1994 Hewlett-PackardCompanyCopyright 1996,97 Silicon GraphicsComputer Systems Inc.Copyright 1997 Moscow Center forSPARC Technology.Copyright 1999,2000 Boris FomitchevCopyright 2001 SAP AGPermission to use, copy, modify, distribute andsell this software and its documentation forany purposes is hereby granted without fee,provided that the above copyright notice appearin all copies and that both that copyright noticeand this permission notice appear in supportingdocumentation. Hewlett-Packard Companymakes no representations about the suitabilityof this software for any purpose. It is provided“as is” without express or implied warranty.

Page 4: Cookbook BOL App CRM2007

Permission to use, copy, modify, distribute andsell this software and its documentation for anypurpose is hereby granted without fee, providedthat the above copyright notice appear in allcopies and that both that copyright notice andthis permission notice appear in supportingdocumentation. Silicon Graphics makes norepresentations about the suitability of thissoftware for any purpose. It is provided “as is”without express or implied warranty.Permission to use, copy, modify, distribute andsell this software and its documentation forany purposes is hereby granted without fee,provided that the above copyright notice appearin all copies and that both that copyright noticeand this permission notice appear in supportingdocumentation. Moscow Center for SPARCmakes no representations about the suitabilityof this software for any purpose. It is provided“as is” without express or implied warranty.Boris Fomitchev makes no representationsabout the suitability of this software for anypurpose. This material is provided "as is", withabsolutely no warranty expressed or implied.Any use is at your own risk. Permission touse or copy this software for any purpose ishereby granted without fee, provided the abovenotices are retained on all copies. Permissionto modify the code and to distribute modifiedcode is granted, provided the above noticesare retained, and a notice that the code wasmodified is included with the above copyrightnotice.Permission to use, copy, modify, distributeand sell this software and its documentationfor any purposes is hereby granted withoutfee, provided that the above copyright noticeappear in all copies and that both that copyrightnotice and this permission notice appear insupporting documentation. SAP makes norepresentations about the suitability of thissoftware for any purpose. It is provided with a

limited warranty and liability as set forth in theLicense Agreement distributed with this copy.SAP offers this liability and warranty obligationsonly towards its customers and only referringto its modifications.b) Support and MaintenanceSAP does not provide software maintenance for theSTLport. Software maintenance of the STLporttherefore shall be not included.All other services shall be charged according to therates for services quoted in the SAP List of Pricesand Conditions and shall be subject to a separatecontract.c) Exclusion of warrantyAs the STLport is transferred to the Customer on aloan basis and free of charge, SAP cannot guaranteethat the STLport is error-free, without materialdefects or suitable for a specific application underthird-party rights. Technical data, sales brochures,advertising text and quality descriptions producedby SAP do not indicate any assurance of particularattributes.d) Limited LiabilityA) Irrespective of the legal reasons, SAP shall onlybe liable for damage, including unauthorizedoperation, if this (i) can be compensated underthe Product Liability Act or (ii) if caused due togross negligence or intent by SAP or (iii) if basedon the failure of a guaranteed attribute.B) If SAP is liable for gross negligence or intentcaused by employees who are neither agents ormanagerial employees of SAP, the total liabilityfor such damage and a maximum limit on thescope of any such damage shall depend onthe extent to which its occurrence ought tohave anticipated by SAP when concluding thecontract, due to the circumstances known toit at that point in time representing a typicaltransfer of the software.C) In the case of Art. 4.2 above, SAP shall notbe liable for indirect damage, consequentialdamage caused by a defect or lost profit.

Page 5: Cookbook BOL App CRM2007

D) SAP and the Customer agree that the typicalforeseeable extent of damage shall under nocircumstances exceed EUR 5,000.E) The Customer shall take adequate measuresfor the protection of data and programs, inparticular by making backup copies at theminimum intervals recommended by SAP. SAPshall not be liable for the loss of data and itsrecovery, notwithstanding the other limitationsof the present Art. 4 if this loss could have beenavoided by observing this obligation.

F) The exclusion or the limitation of claims inaccordance with the present Art. 4 includesclaims against employees or agents of SAP.4. Adobe Document ServicesAdobe, the Adobe logo, Acrobat, PostScript, and Readerare either registered trademarks or trademarks ofAdobe Systems Incorporated in the United States and/ or other countries. For information on Third Partysoftware delivered with Adobe document services andAdobe LiveCycle Designer, see SAP Note 854621.

Page 6: Cookbook BOL App CRM2007

Typographic Conventions

Type Style Description

Example Text Words or characters quotedfrom the screen. These includefield names, screen titles,pushbuttons labels, menunames, menu paths, and menuoptions.

Cross-references to otherdocumentation

Example text Emphasized words or phrasesin body text, graphic titles, andtable titles

EXAMPLE TEXT Technical names of systemobjects. These include reportnames, program names,transaction codes, tablenames, and key concepts of aprogramming language whenthey are surrounded by bodytext, for example, SELECT andINCLUDE.

Example text Output on the screen. Thisincludes file and directorynames and their paths,messages, names of variablesand parameters, source text,and names of installation,upgrade and database tools.

Example text Exact user entry. These arewords or characters that youenter in the system exactly asthey appear in thedocumentation.

<Exampletext>

Variable user entry. Anglebrackets indicate that youreplace these words andcharacters with appropriateentries to make entries in thesystem.

EXAMPLE TEXT Keys on the keyboard, forexample, F2 or ENTER.

Icons

Icon Meaning

Caution

Example

Note

Recommendation

Syntax

Additional icons are used in SAPLibrary documentation to help youidentify different types of information ata glance. For more information, seeHelp on Help General InformationClasses and Information Classes forBusiness Information Warehouse onthe first page of any version of SAPLibrary.

Page 7: Cookbook BOL App CRM2007

<July 2008> 7

Contents1 Business Object Layer .......................................................................8

1.1 Abstract................................................................................................... 81.1.2 Introduction .............................................................................................................. 81.1.3 Overview.................................................................................................................. 81.1.4 Basic Features of the BOL API ............................................................................... 101.1.4.1 Setting up a BOL Instance................................................................................... 101.1.5 Advanced Features of the BOL API ........................................................................ 181.1.6 Interface Classes.................................................................................................... 291.1.7 Checkpoint Groups................................................................................................. 29

1.2 Architecture Details and Context........................................................ 301.2.1 BOL Entities ........................................................................................................... 301.2.2 Collections ............................................................................................................. 311.2.3 Context Nodes ....................................................................................................... 321.2.4 Controller Context .................................................................................................. 341.2.5 Data Binding .......................................................................................................... 351.2.6 Mixed and Value Nodes of the Controller Context................................................... 35

Page 8: Cookbook BOL App CRM2007

1 Business Object Layer

8 <July 2008>

1 Business Object Layer1.1 AbstractThis document describes the runtime programming interface of the business object layer(BOL). After you have read this document, you can create, access, and modify business dataprovided by the BOL, such as business partners, products, or Human Resources data. TheBOL may be used within all ABAP based applications (for example, simple reports, dynpro,and business server page (BSP) applications).

1.1.2 IntroductionUsing the BOL and its uniform application programming interface (API) to access businessdata offers considerable advantages compared to the various APIs typically available forbusiness objects:

The object-oriented BOL API is simple, uniform, and easy to use.

The built-in buffer accelerates your applications.

You can isolate your programs from any interface changes in the underlying businessobject-specific APIs.

Development of SAP Customer Relationship Management (SAP CRM) applications iseasy since the BOL has been designed to work hand-in-hand with the UI parts of theCRM WebClient UI framework.

It is possible to enhance the BOL to cover business data not yet supported. After thecorresponding business objects and query services have been modeled and implemented,you can use them at runtime.

1.1.3 OverviewThe BOL API consists of various interfaces and classes that you can use to access businessdata:

CL_CRM_BOL_QUERY_SERVICE

You use this class to select business objects.

CL_CRM_BOL_ENTITY

You use this class for implementing business objects.

IF_BOL_TRANSACTION_CONTEXT

You use this interface to control transaction behavior.

IF_BOL_BO_COL

You use this interface to provide collections to hold business objects.

The lifetime of these objects lasts the entire session. The BOL API, however, provides youwith the ability to free used business objects and their memory.

Page 9: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 9

Important objects in the BOL Programming ABAP and their corresponding interfacesand classes:

Objects

Object Model

BOL Core

Entity Factory

Query Service

TransactionContext

Entity

Collectionfor Business

Objects

1

11

1..*

1

1..*

1..*

*

*

*

Interfaces and Classes

<<Interface>>IF_GENIL_OBJECT_MODEL

<<Interface>>IF_BOL_TRANSACTION_CONTEXT

CL_CRM_BOL_CORE

get_instance()

CL_CRM_BOL_ENTITY

CL_CRM_BOL_ENTITY_FACTORY

CL_CRM_BOL_QUERY_SERVICE

get_instance()

<<Interface>>IF_BOL_BO_COL

1

1

1

1

0..n

0..n

0..n

Page 10: Cookbook BOL App CRM2007

1 Business Object Layer

10 <July 2008>

1.1.4 Basic Features of the BOL APIWhen you use the BOL to work with business objects in an ABAP application, you typicallyuse code sequences similar to those indicated in the following sections.

1.1.4.1 Setting up a BOL InstanceYou create an instance of the BOL by calling a static method of its core class:

Syntax

* Start BOL Core module

DATA: lv_bol_core TYPE REF TO cl_crm_bol_core.

lv_bol_core = cl_crm_bol_core=>get_instance( ).

lv_bol_core->start_up( ‘MY_COMPONENT_SET’ ).

The BOL core CL_CRM_BOL_CORE follows the singleton design pattern, so you can onlyhave one instance of it. The START_UP() method takes the name of the component set thatyou want to start as input parameter and starts the BOL. Once this is completed, you canload all services of the BOL and the component set.

The START_UP() method takes another optional parameter, IV_DISPLAY_MODE_SUPPORT,which is set to ABAP_FALSE by default. This means that the BOL follows the optimisticlocking approach, making all of the objects appear changeable in the user interface evenwithout a lock. The lock is automatically requested on the first attempt to make a change toan object.

If the parameter IV_DISPLAY_MODE_SUPPORT is set to ABAP_TRUE, the BOL follows thestrict locking approach where only locked objects appear as changeable. For moreinformation, see Display Mode Support [page 18].

1.1.4.2 Component Sets and Components of the GenericInteraction LayerEach component set defines a set of Generic Interaction Layer (GenIL) components, eachproviding specific business objects with dependent objects and related queries. GenILcomponent sets and GenIL components are defined in Customizing for CustomerRelationship Management under CRM Cross-Application Components Generic InteractionLayer/Object Layer Basic Settings.

Components of the GenIL are implemented using ABAP classes. To determine whichbusiness objects, attributes, relations, dependent objects, queries, and further services areprovided by a component set, you can use the Model Browser (transactionGENIL_MODEL_BROWSER).

To check which components are loaded and to load additional components, you can use thefollowing code:

Syntax

* Load additional component

DATA: lv_component_name type crmt_component_name.

lv_component_name = 'ANOTHER_COMPONENT'.

lv_bol_core->load_component( lv_component_name ).

Page 11: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 11

* Get components loaded

DATA: lv_obj_model type ref to if_genil_obj_model,

lv_obj_model_ type ref to cl_crm_genil_obj_model,

lt_components_loaded type genil_component_tab.

lv_obj_model =cl_crm_genil_model_service=>get_runtime_model( ).

lv_obj_model_ ?= lv_obj_model.

lt_components_loaded = lv_obj_model_->get_components_loaded( ).

1.1.4.3 Issue QueriesBefore you can work with business objects or entities, you need to locate them using asearch. You use a query service object to receive a collection of business objects that matchthe search criteria given.

1.1.4.3.1 Regular QueriesIn a generic application, such as the BOL browser, you may use the BOL Object ModelService to determine the query services of the loaded component sets and components.Select a query service, set the query parameters, and launch a query.

You can receive a table with the names of all available query services by entering thefollowing code:

Syntax

* Determine query services available

DATA: lv_obj_model TYPE REF TO if_genil_obj_model.

lv_obj_model =cl_crm_genil_model_service=>get_runtime_model( ).

DATA: lt_query_names TYPE crmt_ext_obj_name_tab.

CALL METHOD lv_obj_model->get_object_list

EXPORTING iv_object_kind =if_genil_obj_model=>query_object

IMPORTING ev_object_list = lt_query_names.

To get a runtime instance of the query service CL_CRM_BOL_QUERY_SERVICE, use theGET_INSTANCE factory method. Use its SET_PROPERTY method to indicate the searchcriteria and its GET_QUERY_RESULT method to launch your query to retrieve a result list ofentities (represented by IF_BOL_ENTITY_COL):

Syntax

* Select a particular query

DATA: lv_query_name TYPE crmt_ext_obj_name.

READ TABLE lt_query_names INDEX 1 INTO lv_query_name.

* Create a query service

DATA: lv_query TYPE REF TO cl_crm_bol_query_service.

Page 12: Cookbook BOL App CRM2007

1 Business Object Layer

12 <July 2008>

lv_query = cl_crm_bol_query_service=>get_instance( lv_query_name).

* Set a search criterion

lv_query->set_property( iv_attr_name = ‘City’

iv_value = ‘Walldorf’ ).

* Read a search criterion

DATA: lv_city type string.

lv_city = lv_query->get_property_as_string( ‘City’ ).

* Execute query and receive result

DATA: lv_result TYPE REF TO if_bol_entity_col.

lv_result = lv_query->get_query_result( ).

If you already know the name of the query service to be used, there is no need to use themodel: you can directly access the query service by name.

As you can see in the above example, it is also possible to retrieve search criteria from thequery service.

You can perform queries and other methods of the BOL API using the BOL Browser(transaction GENIL_BOL_BROWSER):

1. Select the desired component set, for example, SAMPLE.

2. Select the query object and enter the parameters before you select Find.

3. Double click an object ID displayed in the List Browser to see a particular object with itsattributes.

1.1.4.3.2 Advanced QueriesAs of SAP CRM release 5.1, the CRM WebClient UI framework supports advanced queries,with the following enhanced features:

In addition to the EQUAL operator, you can use arbitrary operators, such asGREATER THAN, LESS THAN, CONTAINS, and IS EMPTY to define search criteria.

You can search for multiple values for one search criterion at the same time (logicalOR).

You can save and retrieve searches with predefined search criteria as templatesidentified with an arbitrary name.

Syntax

* Get advanced query

DATA: lv_advanced_query TYPE REF TO cl_crm_bol_dquery_service.

lv_advanced_query =

cl_crm_bol_dquery_service=>get_instance( 'AdvOrderQuery' ).

* Set general query parameter for maximum number of hits

DATA: lt_params type crmt_name_value_pair_tab,

Page 13: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 13

ls_params type crmt_name_value_pair.

ls_params-name = 'MAX_HITS' . ls_params-value = '5'.

APPEND ls_params TO lt_params.

lv_advanced_query->set_query_parameters( it_parameters = lt_params).

* Add selection criteria: Ordernumber > 5

lv_advanced_query->add_selection_param( iv_attr_name ='ORDER_NUMBER'

iv_sign = 'I'

iv_option = 'GT' “Greater than

iv_low = '5'

iv_high = '' ).

* Execute the query and receive result

DATA: lv_result type ref to if_bol_entity_col.

lv_result = lv_advanced_query->get_query_result( ).

To display advanced queries in the CRM WebClient UI, easy-to-use tags have beendeveloped.

Query templates are used to store and retrieve saved searches with predefined searchcriteria:

Syntax

* Save query as template

lv_advanced_query->save_query_as_template( iv_query_id = ‘MyQuery’

iv_overwrite = abap_true ).

* Load query from template

lv_advanced_query->load_query_template( iv_query_id = ‘My Query’).

1.1.4.4 Working with EntitiesAfter you receive a list of entities from the query, you can use them in your application by, forexample, displaying their attributes on the user interface, modifying them, or deleting them.

1.1.4.5 Access Properties and Related EntitiesThe following code shows how to access entities of the query result and how to read theirproperties. Note that the methods are the same for all types of business objects.

Syntax

* Use iterator to access entities in query result

DATA:lv_iterator TYPE REF TO if_bol_entity_col_iterator.

Page 14: Cookbook BOL App CRM2007

1 Business Object Layer

14 <July 2008>

lv_iterator = lv_result->get_iterator.

DATA: lv_entity TYPE REF TO cl_crm_bol_entity.

lv_entity = lv_iterator->get_first( ). “Entity is business partnerhere

WHILE lv_entity IS BOUND.

* Access attributes of business objects selected

DATA: lv_firstname TYPE string,

lv_lastname TYPE string.

lv_firstname = lv_entity->get_property_as_string( ‘FirstName’ ).

lv_lastname = lv_entity->get_property_as_string( ‘LastName’ ).

* Get a 1:1 related entity

DATA: lv_default_address TYPE REF TO cl_crm_bol_entity.

lv_default_address = lv_entity->get_related_entity(‘DefaultAddress’ ).

* Get a list of 1:N related entities

DATA: lv_addresses TYPE REF TO if_bol_entity_col.

lv_addresses = lv_entity->get_related_entities( ‘Addresses’ ).

*

lv_entity = lv_iterator->get_next( ).

ENDWHILE.

The last section of code shows how to navigate from one entity to a related entity. Use theBOL Object Model Service or the Model Browser to find out which relationships have beendefined in the model for a particular object type.

1.1.4.6 TransactionsOne of the most important aspects of BOL programming is to know how to modify data. Youcan create, modify, and delete entities in accordance with the BOL transaction model, whichsupports several kinds of transaction contexts to handle entity operations consistently.

The global transaction context holds all modified root entities, whereas the fine granulartransaction context exists for each root object instance. The custom transaction context canbe used to handle special situations, where more than one (but not all) modified object formsthe transaction. This section discusses only the global context. For more information aboutthe fine granular transaction context, see Fine Granular Transaction Handling [page 24].

1.1.4.7 Creating EntitiesThe following code shows how to create a root entity with two related entities:

Syntax

* 1. Build parameters to create an entity:

* here an order entity with technical name ‘BTOrder’

Page 15: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 15

DATA: lt_params TYPE crmt_name_value_pair_tab,

ls_params TYPE crmt_name_value_pair.

ls_params-name = ‘PROCESS_TYPE’.

ls_params-value = ‘TA’.

APPEND ls_params TO lt_params.

* 2. Get factory for business object

DATA: lv_order_factory TYPE REF TO cl_crm_bol_entity_factory.

lv_order_factory = lv_bol_core->get_entity_factory( ‘BTOrder’ ).

* 3. Create root entity

DATA: lv_order TYPE REF TO cl_crm_bol_entity.

lv_order = lv_order_factory->create( lt_params ).

* 4. Create child objects

DATA: lv_order_header TYPE REF TO cl_crm_bol_entity,

lv_activity_header TYPE REF TO cl_crm_bol_entity.

lv_order_header = lv_order->create_related_entity( ‘BTOrderHeader’).

lv_activity_header =

lv_order_header->create_related_entity(‘BTHeaderActivityExt’ ).

* 5. Submit child objects created

lv_bol_core->modify( ).

* 6. Save and commit changes using global transaction context

DATA: lv_transaction TYPE REF TO if_bol_transaction_context

lv_transaction = lv_bol_core->get_transaction( ).

lv_transaction->save( ).

lv_transaction->commit( ).

You can distinguish between the creation of root objects using the factory and the creation ofdependent or child objects using method CREATE_RELATED_ENTITY. The first casedirectly triggers a call to the underlying API, whereas in the second case it does not. In thesecond case, it is necessary to trigger the API call explicitly by calling the MODIFY method,which sends the changes to the underlying GenIL. Without this call, the created child objectsare not saved.

1.1.4.8 Locking EntitiesYou should lock an entity before you are going to modify it, as the setter only modifies entityproperties when the entity is locked. The set-methods of the entity perform a check to see ifthe entity is locked. If it is not, they try to lock it. This attempt can fail if another user is usingthe entity.

Page 16: Cookbook BOL App CRM2007

1 Business Object Layer

16 <July 2008>

The current locking granularity of the BOL is the root object instances, so the lock request foran entity is always delegated to the corresponding root instance.

The following code shows how to lock an entity:

Syntax

* Lock BOL entity

DATA: lv_success TYPE crmt_boolean.

lv_success = lv_entity->lock( ).

If the lock was set, the return value LV_SUCCESS is true (ABAP_TRUE orIF_GENIL_BOOLEAN => TRUE ).

1.1.4.9 Modifying Entity PropertiesYou can modify entity properties using the set-methods of the entity. If you have not started atransaction before modifying the properties, it is created automatically.

The following code shows how to modify the property of an order:

Syntax

* 1. Lock and modify a property

* here order header entity with technical name ‘BTOrderHeader’

lv_order_header = lv_order->get_related_entity( ‘BTOrderHeader’).

IF lv_order_header->lock( ) = if_genil_boolean=>true.

lv_order_header->set_property( iv_attr_name = ‘DESCRIPTION’

iv_value = ‘ChangedDescription’ ).

ENDIF.

* 2. send all changes to BO layer

lv_bol_core->modify( ).

* 3. get the implicitly created transaction

lv_transaction = lv_bol_core->get_transaction( ).

* 4. save and commit your changes

lv_transaction->save( ).

lv_transaction->commit( ).

The given example works with or without display mode support, since the lock is explicitly set.

1.1.4.10 Deleting EntitiesSimilar to when you create entities, you must distinguish between the deletion of root objectsand the deletion of dependent or child objects.

Page 17: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 17

For root object instances, the DELETE method call is sent directly to the API where thecomplete aggregation hierarchy is deleted. The deletion is written to the database with aninternal COMMIT WORK.

Syntax

* Delete root entity

lv_order->delete( ).

In the case of a child object, the deletion is not automatically sent to the API. You have totrigger this explicitly by calling the MODIFY method of the BOL core.

Syntax

* Delete child object

lv_order_header->delete( ).

lv_bol_core->modify( ).

DATA: lv_transaction TYPE REF TO if_bol_transaction_context.

lv_transaction = lv_bol_core->get_transaction( ).

lv_transaction->save( ).

lv_transaction->commit( ).

Note: You must save and commit the transaction to confirm the deletion.

Immediately after CL_CRM_BOL_CORE->MODIFY has been executed, the entity is deletedin the BOL buffer. This is published in the entity instance by creating a DELETED event. Afterthe deletion, any further access to the entity instance can lead to a CX_BOL_EXCEPTIONexception.

1.1.4.11 Execution of Entity MethodsTo perform special business functions, it is possible to call special methods on an entity thathave been modeled and implemented for a particular object type. These methods can havean arbitrary set of import parameters and may return an entity collection of result objects.

The following code shows how to execute an entity method for special business functionality:

Syntax

* Execute entity method

DATA: lv_items TYPE REF TO cl_crm_bol_entity.

lv_items->execute( iv_method_name = ‘RenumberItems’ ).

* ... with input parameters and a list of BOL entities returned

DATA: ls_param TYPE crmt_name_value_pair,

lt_param TYPE crmt_name_value_pair_tab,

lv_result TYPE REF TO if_bol_entity_col.

ls_param-name = ‘PROCESS_TYPE’.

ls_param-value = ‘TSRV’.

append ls_param to lt_param.

TRY.

Page 18: Cookbook BOL App CRM2007

1 Business Object Layer

18 <July 2008>

lv_result = lv_order_header->execute( iv_method_name =‘createFollowUp’

it_param = lt_param ).

* Error handling

CATCH CX_CRM_BOL_METH_EXEC_FAILED.

* An exception is received if method has indicated an error

* and has not returned more than one entity.

...

ENDTRY.

1.1.5 Advanced Features of the BOL APIThe following sections describe special features of the BOL API.

1.1.5.1 Display Mode SupportAs of SAP CRM 5.0, the BOL optionally supports DISPLAY mode for entities, which isactivated by default if the BOL core has been started with the parameterIV_DISPLAY_MODE_SUPPORT = ABAP_TRUE.

In display mode, any attempt to change properties, or to create or delete dependent objectsis ignored and a call of methodIF_BOL_BO_PROPERTY_ACCESS~IS_PROPERTY_READONLY on the entity returnsABAP_TRUE (‘X’).

To change entity properties, it is necessary to switch the entity explicitly to CHANGE mode.You can do this by calling method SWITCH_TO_CHANGE_MODE or method LOCK. If nolock is obtained, the entity remains in display mode. The current state of an entity can bechecked with method IS_CHANGEABLE.

Syntax* Start BOL core with display mode support

DATA: lv_bol_core TYPE REF TO cl_crm_bol_core.

lv_bol_core = cl_crm_bol_core=>get_instance( ).

lv_bol_core->start_up( iv_appl_name = ‘MY_COMPONENT_SET’

iv_display_mode_support = ABAP_TRUE ).

* Execute query and access entity

DATA: lv_entity type ref to cl_crm_bol_entity.

lv_entity = ... -“Entity is in now displaymode

* Switch to change mode and change entity

lv_entity->switch_to_change_mode( ). “Reread and lock entity

IF lv_entity->is_changeable( ) = abap_true.

lv_entity->set_property_as_string( iv_attr_name =‘PROPERTY_NAME’

Page 19: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 19

iv_value = ‘New Value’ ).

ENDIF.

When an entity is locked, its properties are re-read to ensure that the most current data isavailable.

1.1.5.2 Standard Interface to Access Properties of BusinessObjectsTo access the properties of BOL entities and query services, you must use theirIF_BOL_BO_PROPERTY_ACCESS interface methods.

<<interface>>IF_BOL_BO_PROPERTY_ACCESS

CL_CRM_BOL_QUERY_SERVICE CL_CRM_BOL_ENTITY

The interface offers a standard means to work with BOL objects. Note that it is possible tohave an instance of IF_BOL_BO_PROPERTY_ACCESS for any BOL object.

Syntax

* Get search criterion of BOL query

DATA: lv_query TYPE REF TO cl_crm_bol_query_service, lv_city_typestring.

lv_query = cl_crm_bol_query_service=>get_instance( ‘QUERY_NAME’ ).

lv_city =

lv_query->if_bol_bo_property_access~get_property_as_string(‘City’ ).

“Short form using alias

lv_city = lv_query->get_property_as_string( ‘City’ ).

* Set property of BOL entity

DATA: lv_entity TYPE REF TO cl_crm_bol_entity

lv_entity->if_bol_bo_property_access~set_property( iv_attr_name =‘CITY’

iv_value = ‘Walldorf’ ).

“Short form using alias

lv_entity->set_property( iv_attr_name = ‘CITY’ iv_value =‘Walldorf’ ).

Page 20: Cookbook BOL App CRM2007

1 Business Object Layer

20 <July 2008>

* Cast to property_access interface

DATA: lv_business_object TYPE REF TO if_bol_bo_property_access.

lv_business_object ?= lv_entity.

In addition to generic getter and setter methods to read and modify business objectproperties, the interface offers methods to receive the text for a key-code value.

Syntax

* Get key code

DATA: lv_person TYPE REF TO cl_crm_bol_entity,

lv_sex type bu_sexid. “Defines values 1 = Female, 2 = Male

...

lv_sex = lv_person->get_property( ‘SEX’ ). “Key code

* Get property text for key code:

* -> ‘Male’ or ‘Female’ translated in current language

DATA: lv_sex_text type string.

lv_sex_text = lv_person->get_property_text( ‘SEX’ ).

The text is taken from the domain values if available or is determined by the underlying GenILcomponent.

1.1.5.3 Collections to hold Business Objects and BOL EntitiesThe BOL API offers two collections for application use:

CL_CRM_BOL_COL, which can be used to hold all instances implementing thestandard property access interface IF_BOL_BO_PROPERTY_ACCESS

CL_CRM_BOL_ENTITY_COL, which can hold regular BOL entities only

IF_BOL_BO_COL

IF_BOL_ENTITY_COL

CL_CRM_BOL_BO_COL

CL_CRM_BOL_ENTITY_COL

The collection interfaces offer a number of methods to work with collections, such asINSERT, GET_FIRST, GET_NEXT, GET_CURRENT, SORT, CLEAR, MARK, andUNMARK.

1.1.5.3.1 Local and Global IterationsBoth collection types support global iteration and local iteration. Each collection has a well-defined focus object. Initially, the first object has the focus. Any global iteration moves thefocus, which is published by the event FOCUS_CHANGED of the collection.

Page 21: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 21

If you want to iterate on the collection without moving the focus (and without triggering time-consuming follow-up processes) you can use local iteration. To do so, request an iteratorobject from the collection and use this to iterate.

Syntax

* Create collection

DATA: lv_collection TYPE REF TO cl_crm_bol_bo_collection,

lv_property_access TYPE REF TO if_bol_bo_property_access,

lv_query TYPE REF TO cl_crm_bol_query_service.

CREATE OBJECT lv_collection.

...

* Add item and make it current

lv_collection->if_bol_bo_col~insert( iv_bo = lv_query

Iv_index = 1

Iv_set_focus = ABAP_BOOL ).

* Global iteration

lv_property_access = lv_collection->get_next( ). “Global iteration

“ moves focus

* Local iteration

DATA: lv_iterator TYPE REF TO if_bol_bo_col_iterator.

lv_iterator = lv_collection->get_iterator( ).

lv_property_access = lv_iterator->get_first( )

WHILE lv_query_is_bound.

lv_property_access = lv_collection->get_next(). “Local iterationdoes not

ENDWHILE. “ move focus

1.1.5.3.2 SearchingThe collections provide the method FIND to search for a given business object in thecollection. If the business object is found, it is returned and the focus is set to this collectionentry.

You can search by index, business object instance, or object name and ID, but only one ofthese parameters is used for the search at a time. The parameters are taken in the givensequence. For example, if you provide an index and an instance, only the index is used.

The local iterator interface supports the search for a single property. This is provided by themethod FIND_BY_PROPERTY. The first object, whose property has the given value, isreturned. Neither the global nor the local collection pointer is influenced by this operation.

Syntax

* Find by property

DATA: lv_persons TYPE REF TO cl_crm_bol_entity_collection,

lv_male TYPE REF TO cl_crm_bol_entity,

lv_iterator TYPE REF TO if_bol_bo_col_iterator.

Page 22: Cookbook BOL App CRM2007

1 Business Object Layer

22 <July 2008>

lv_iterator = lv_persons->get_iterator( ).

lv_male = lv_iterator->find_by_property( iv_attr_name = ‘SEX’

iv_value = 2 ).

* Set collection focus on the entity found

lv_persons->find( iv_bo = lv_male ).

1.1.5.3.3 SortingCollections can be sorted with the SORT method and stay in the resulting sort order.

Note

You can not undo the sorting process.

The mandatory parameter IV_ATTR_NAME specifies the property that the collection is sortedfor. If you do not specify IV_SORT_ORDER, the sort order defaults as ascending.

Syntax

* Sorting

DATA: lv_persons TYPE REF TO cl_crm_bol_entity_collection,

lv_male TYPE REF TO cl_crm_bol_entity,

lv_iterator TYPE REF TO if_bol_bo_col_iterator.

lv_persons->sort( iv_attr_name = ‘SEX’

iv_sort_order = IF_BOL_BO_COL=>SORT_DESCENDING ).

The sorting is alphabetical and based on the string representation of the property. Since thiscan lead to false results (for example, when working with dates) it is possible to control thesorting by providing an instance of IF_BOL_COL_SORTING. During the sort process, themethod IS_A_GREATER_B is called whenever two values are compared. To modify the sortorder as needed, implement this method and provide the interface.

1.1.5.3.4 Multi Select SupportBOL collections support two different modes for entry selection:

Single Selection Mode

In this mode, it is only possible to select a single entry at a time. When a secondentry is selected, the previous one is de-selected.

Multi Selection Mode

In this mode, it is possible to select more than one entry at a time.

The current selection mode can be checked with the public collection attributeIF_BOL_BO_COL~MULTI_SELECT and it can be set with methodIF_BOL_BO_COL~SET_MULTI_SELECT.

In single selection mode, the selected element is communicated with the following methods:

Method Result

IF_BOL_BO_COL~GET_CURRENT Returns the selected element

IF_BOL_BO_COL~GET_CURRENT_INDEX Returns the index of the selected element

IF_BOL_BO_COL~PUBLISH_CURRENT

IF_BOL_BO_COL~FOCUS_CHANGED

Publishes the selected element using theevent

Page 23: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 23

The selected element is implicitly set with the following methods:

Method Result

IF_BOL_BO_COL~GET_NEXT Moves focus to the next element andreturns it

IF_BOL_BO_COL~GET_PREVIOUS Moves focus to the previous element andreturns it

Note

In single selection mode, the current or focus element is always defined, exceptwhen the collection is empty. The methods of the interfaceIF_BOL_BO_COL_MULTI_SEL are deactivated.

When multi selection mode has been activated, you may use the methods of the interfaceIF_BOL_BO_COL_MULTI_SEL to mark and unmark entries, and to check which entries havebeen marked (IF_BOL_BO_COL_MULTI_SEL~MARK, UNMARK, GET_MARKED).

In multi selection mode, the collection methods behave differently than in single selectionmode:

Method Result

IF_BOL_BO_COL~GET_CURRENT Returns the last selected element

IF_BOL_BO_COL~GET_CURRENT_INDEX Returns the index of the last selectedelement

IF_BOL_BO_COL~PUBLISH_CURRENT Does nothing

IF_BOL_BO_COL~FIND Finds, eventually selects and returns anelement

IF_BOL_BO_COL~GET_NEXT Does nothing

IF_BOL_BO_COL~GET_PREVIOUS Does nothing

1.1.5.3.5 Auto Cleanup ModeAuto cleanup mode for a collection ensures that deleted entities are automatically removedfrom the collection. As a result, the (last) selected element changes automatically.

Entity removal is not always necessary and this feature can lead to serious problems withmemory, so by default it is inactive. To activate this function, call methodIF_BOL_BO_COL~ACTIVATE_AUTOCLEANUP. The current state of the collection isindicated by the public attribute IF_BOL_BO_COL~AUTOCLEANUP, which is ABAP_TRUE ifactive.

Caution

If auto cleanup mode is active, it is necessary to clear a collection (call methodIF_BOL_BO_COL~CLEAR) when it is no longer needed. The garbage collectorcannot delete the collection if it is referenced in the event handler table of itsentities. If you do not clear unneeded collections, the affected collections remainin memory until the next BOL reset operation or session end. This can lead toserious memory issues.

1.1.5.3.6 BOL Reset Survival ModeTo free unused memory, the SAP CRM application periodically triggers a BOL reset thatdeletes all BOL entities, and as a result clears all collections that have auto cleanupactivated.

Page 24: Cookbook BOL App CRM2007

1 Business Object Layer

24 <July 2008>

Some collections need to protect their content, especially if they are essential for the furtheroperation of the application. You can use methodIF_BOL_BO_COL~SET_RESET_SURVIVAL_MODE to indicate that the root and accessentities are to be recreated after the BOL reset.

To receive notice at runtime of any collections that are not reset-compliant because theycontain dependent entities, you can activate the assertion group BOL_ASSERTS usingtransaction SAAB (assertions, breakpoints and logpoints).

1.1.5.4 Fine Granular Transaction HandlingA transaction context is established for each root object instance that you use. It can beaccessed using method GET_TRANSACTION on an entity instance. Its SAVE method savesthe underlying root object instance and its aggregation hierarchy. However the COMMIT isglobal and if the implementation in transaction handling contains any unwanted data, thisunwanted data may be saved.

Note

There is no monitoring of dependencies between root objects. For example, youhave a newly created root object that refers to another newly generated object. Ifthe first object is saved but the second one is not, the database is in aninconsistent state.

You can use the CL_CRM_BOL_CUSTOM_TX_CTXT transaction context to create a singletransaction that contains more than one root object transaction:

Syntax

* 1. Create custom tx context

DATA: my_tx_context TYPE REF TO cl_crm_bol_custom_tx_context.

CREATE OBJECT my_tx_context.

* 2. Add some single object transactions

DATA: lv_entity1 TYPE REF TO cl_crm_bol_entity,

lv_entity2 TYPE REF TO cl_crm_bol_entity,

lv_tx_ctxt TYPE REF TO if_bol_transaction_context.

...

lv_tx_ctxt = lv_entity1->get_transaction( ).

my_tx_context->add_tx_context( lv_tx_ctxt ).

lv_tx_ctxt = lv_entity2->get_transaction( ).

my_tx_context->add_tx_context( lv_tx_ctxt ).

* 3. Save and commit both single object transactions together

my_tx_context->save( ).

my_tx_context->commit( ).

Transaction contexts can be requested at any time by using methodIF_BOL_TRANSACTION_CONTEXT~CHECK_SAVE_NEEDED. This allows you to see ifdata has been changed or if a save is necessary.

1.1.5.5 Input Readiness and Entity Property Modifiers

Page 25: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 25

To check if an entity property is read only, you can use methodIF_BOL_BO_PROPERTY_ACCESS~IS_PROPERTY_READONLY. It returns ABAP_TRUEif the property is not changeable and not mandatory.

The property modifier is defined for each entity property and calculates input readiness. Ittakes one of the following public constants defined in the interfaceIF_GENIL_OBJ_ATTR_PROPERTIES:

READ_ONLY

CHANGEABLE

NOT DEFINED

HIDDEN

MANDATORY

TECHNICAL

To access the property modifier, use the entity method GET_PROPERTY_MODIFIER.

By default, it is possible to change properties of query services.

1.1.5.6 Excluding Entities from the Central ModifyNew, changed, or deleted dependent objects are sent to the underlying APIs with one centralcall of the BOL core’s MODIFY method. Depending on the application, this call may appearautomatically at certain sync points. If entities are not ready to be sent, sending them cancause errors. In this case, you can exclude such entities to prevent them from being sent.

An entity is excluded in the following cases:

A dependent entity was created but its properties were not set

An entity was sent with MODIFY, but the changes have not been accepted by theunderlying API

An entity was deactivated for sending

The current status of an entity can be checked with method IS_SEND_ACTIVE on the entityinstance. You can make an explicit change to the status with the methodsACTIVATE_SENDING and DEACTIVATE_SENDING. If you deactivate sending, this alsoaffects any child objects.

1.1.5.7 Business Error HandlingThe BOL offers a message protocol to support communication of information messages,warning messages, and error messages. Messages are collected in message containers,which are handled by the message container manager. There is one message container foreach root object instance and a global one for all general messages.

Page 26: Cookbook BOL App CRM2007

1 Business Object Layer

26 <July 2008>

Message Handling Model

CL_CRM_COL_CORE

CL_CRM_GENIL_MESS_CONT_MANAGER

IF_GENIL_MESSAGE_CONTAINER

1

1

1

*

The message container manager can be reached using the core. The following code showshow to access a particular message container:

Syntax* Access messages of a business object

* 1) Use the message container manager

DATA: lv_mcm TYPE REF TO cl_crm_genil_mess_cont_manager.

lv_mcm = lv_bol_core->get_message_cont_manager( ).

* 2) ... to obtain the message container

DATA: lv_object_name TYPE crmt_ext_obj_name,

Lv_object_id TYPE crmt_gnil_object_id.

lv_object_name = lv_order->get_name( ).

lv_object_id = lv_order->get_key( ).

DATA: lv_mc TYPE REF TO if_genil_message_container.

lv_mc = lv_mcm->get_message_cont( iv_object_name = lv_object_name

Iv_object_id = lv_object_id ).

The message container interface provides the methodIF_GENIL_MESSAGE_CONTAINER~GET_MESSAGES for access. Since it takes themessage type as parameter, it is possible to filter for errors, warnings, and information.Possible values for the message types are defined as constants MT_ALL, MT_ERROR,MT_WARNING, MT_INFO, and MT_SUCCESS in the IF_GENIL_MESSAGE_CONTAINERinterface.

Page 27: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 27

The method GET_NUMBER_OF_MESSAGES returns the number of messages of thespecified type. This can be used to notify a user of new messages.

Syntax

* 3) Access messages

DATA: lv_number_of_errors TYPE int4,

lt_error_messages TYPE crmt_genil_message_tab.

lv_number_of_errors = lv_mc->get_number_of_messages( lv_mc->mt_error).

IF lv_number_of_errors <> 0.

lt_error_messages = lv_mc->get_messages( lv_mc->mt_error ).

ENDIF.

1.1.5.8 Buffering IssuesThe BOL operates on its own entity buffer, and so each of the following is buffered:

Every entity found by a query

Every entity read by navigation over a relationship

Each entity modification, as well as the creation or deletion of dependent entities

The underlying buffers of the GenIL components (for the various business object types) aresynchronized with BOL modifications when CL_CRM_BOL_CORE->MODIFY()is called. Inthe SAP CRM application, this happens automatically with each round trip. The BOL buffer isalso informed automatically about data changes in the GenIL component.

In special situations, an explicit synchronization between the BOL buffer and GenILcomponent is necessary. These situations are described in the sections below.

1.1.5.8.1 Entity PropertiesThe entity method CL_CRM_BOL_ENTITY->REREAD() can be used to synchronize thebuffer state of the properties and property modifiers of a single entity. Since this method callsthe underlying API directly, it should be used with caution to avoid performance problems.

1.1.5.8.2 Entity RelationshipsThe system also buffers the relationships between entities. Unlike with buffered properties,this may make the relationships invalid and cannot be synchronized automatically. This maycause inconsistencies in some cases.

You can distinguish between cacheable relations and those which are not subject tobuffering.

For the cacheable relations, you can apecify a mode for navigation. Therefore the navigationmethods GET_RELATED_ENTITY() and GET_RELATED_ENTITIES() take an optionalparameter IV_MODE, which may be set to one of the following constants (defined in classCL_CRM_BOL_ENTITY):

NORMAL

This is the default constant. It reads a relationship from the underlying API if the BOLbuffer is empty.

BUFFER_ONLY

Page 28: Cookbook BOL App CRM2007

1 Business Object Layer

28 <July 2008>

This only reads the relationship from the BOL buffer.

BYPASSING_BUFFER

This only reads the relationship from the underlying API, ignoring the BOL buffer.

Non-cacheable relations are read from the underlying API for each navigation, ignoring thegiven mode. Being non-cacheable is an unchangeable model property of a relationship(IF_GENIL_OBJ_MODEL~ RELATION_IS_CACHEABLE).

1.1.5.8.3 Preloading BOL ViewsIf you need to synchronize a larger set of entities with relationships, the above methods areineffective. You can load a well-defined part of the object model with a given start entity or setof entities at one time. This model part must be defined as a BOL View in Customizing forCustomer Relationship Management under CRM Cross-Application Components GenericInteraction Layer/Object Layer Define Views.

Select an existing view or create a new entry, and choose Maintain Views. Each BOL view isassigned to a specific component set and has a unique view root, which is either a BOL rootobject or access object. You also define the related object types and their relationships.

Once you have completed this customizing, the method PREFETCH_VIEW can be called onthe BOL core. It takes the view name and a collection of view root entities as input. Themodel part defined by the view is read for each entity in the collection and stored in thebuffer.

1.1.5.8.4 Locking with SynchronizationAfter setting a lock it is sometimes necessary to synchronize the BOL buffer for the lockedentity with the current database state. Synchronization is necessary in the following cases:

If the entity has been changed by another user since the last read operation

If the last lock attempt failed because the entity was already locked

When a lock attempt fails, the entity is set to read-only mode and the propertymodifiers must be refreshed.

Therefore the CL_CRM_BOL_ENTITY->LOCK method takes an optional parameterIV_REREAD. The default setting is ABAP_FALSE. If it is set to ABAP_TRUE, the fullaggregation hierarchy of the locked root entity is invalidated in the buffer and synchronizedon the next access.

1.1.5.9 BOL ResetThe BOL buffer and the message services permanently collect information, but do notrelease it. Therefore, the amount of data constantly grows over time. A mechanism isnecessary to remove this buffered or collected data.

To reset the BOL core, you can use the method CL_CRM_BOL_CORE->RESET(). Thismethod clears all known buffers and messages. After the method has run, you can call theABAP garbage collector to remove all of the freed objects.

In the SAP CRM application, a BOL reset is triggered automatically from the frameworkwhenever the user switches the work center with a click in the CRM WebClient UI Navigationbar.

You can not use entity instances after the BOL reset. Further operations using them causeruntime exceptions unless the entity is a root or access entity and contained in a collectionthat has reset survival mode activated. For more information, see BOL Reset Survival Mode[page 23].

Page 29: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 29

1.1.6 Interface ClassesThe following sections include a summary of important classes and interfaces of the BusinessObject Layer (BOL).

1.1.6.1 BOL CoreCL_CRM_BOL_CORE is the most important class of the BOL Application ProgrammingInterface (API). There is only one instance of it within each session and it cannot be lost ordeleted. The BOL core is the central service provider for API classes and it communicateswith the underlying business object implementation. You can use the core services directly,but it is strongly recommended to use the API classes, such as query services or entities.

1.1.6.2 Query ServicesGeneric query services are provided by the classes CL_CRM_BOL_QUERY_SERVICE andCL_CRM_BOL_DQUERY_SERVICE. Each instance corresponds to a distinct query object. Itstores query parameters but does not aggregate the query result.

1.1.6.3 EntitiesThe class CL_CRM_BOL_ENTITY is a generic representation for business objects in theBOL. Each instance is a unique representation for a specific business object. You can accessdata using the IF_BOL_BO_PROPERTY_ACCESS interface. Entities are centrally managedand cached.

1.1.6.4 Entity CollectionA collection or list of generic entities is represented by the interfaces IF_BOL_BO_COL andIF_BOL_ENTITY_COL, and the underlying classes CL_CRM_BOL_BO_COL andCL_CRM_BOL_ENTITY_COL (among others). An entity collection provides globalnavigation, which changes the global focus. Using the local iterator does not change theglobal focus. It is possible to add and remove entities that are referenced, but not owned bythe collection.

1.1.6.5 Transaction ContextThe transaction context is represented by the interface IF_BOL_TRANSACTION_CONTEXT.Depending on the actual instance of the interface, the scope of the represented transaction isa single root object instance, all modified root object instances, or any explicitly built subsetsin between.

The BOL core aggregates the global transaction context, which includes all modified rootobjects. The global transaction context logs all modifications automatically. A single objecttransaction context can be accessed using the entity it belongs to.

1.1.7 Checkpoint GroupsTo highlight important places for debugging and to introduce expensive consistency checks,some checkpoint groups have been introduced. Checkpoint groups are activated withtransaction SAAB (assertions, breakpoints, and logpoints) in the development environment.

1.1.7.1 BOL Checkpoint GroupsThe following BOL checkpoint groups are available:

BOL_ASSERTS

This checkpoint group includes expensive checks for inner consistency and for thecorrect use of the display mode. If the checkpoint group is activated, any attempt to

Page 30: Cookbook BOL App CRM2007

1 Business Object Layer

30 <July 2008>

change entities in display mode is detected. You can activate this checkpoint groupin development and test systems to get early notice of problems related to the BOLusage.

BOL_MODIFY_WATCH

This checkpoint group defines important break points, which can be used to track thedata transport from the business object to the Generic Interaction Layer (GenIL), themerge back of data returned into the BOL buffer, ID adjustments for new entities, andbuffer invalidation of changed entities.

BOL_COLL_AUTOCLEAN

This checkpoint group activates the auto cleanup mode for collections as default.This may lead to memory problems, so it should only be used for testing purposes orcompatiblility purposes with framework versions SAP CRM 5.0 and older.

1.1.7.2 Related Checkpoint GroupsFor detailed investigations and debugging, it is required to break-in the GenIL, which givesaccess to data persistency.

The following related checkpoint groups are available:

GENIL_DC_CHECKS

This checkpoint group activates consistency checks for the data containers.

GENIL_LOCK

This checkpoint group stops the ABAP debugger if an entity is to be locked.

GENIL_SAVE

This checkpoint group allows investigations of the save process.

GENIL_READ

This checkpoint group breaks-in the read method of the GenIL coreCL_CRM_GENERIC_IL_NEW. It allows detailed investigations of the communicationwith the underlying GenIL component responsible for a specific business object.

GENIL_MODIFY

This checkpoint group breaks in the modify method of the GenIL core

1.2 Architecture Details and ContextThis section presents further aspects of the business object layer (BOL) and its use by theCRM WebClient UI framework. The Unified Modeling Language (UML) diagrams below showthe connection between the classes involved and their main attributes.

1.2.1 BOL EntitiesBOL entities are managed by the BOL entity manager and use classes of the GenericInteraction Layer (GenIL) to hold their data.

Page 31: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 31

CL_CRM_BOL_ENTITY_MANAGER

entity_tab

CL_CRM_BOL_ENTITY

my_manager_entryparent

CL_CRM_GENIL_CONTAINER_OBJECT

data_ref

1

1

1

0..n

#container_proxy

In the diagram above:

All entities are managed by the entity manager. It assures the uniqueness of entitiesand buffer access.

Each entity holds a reference to its manager entry. The manager entry includesvalues such as the invalid and delta flags. Holding these values in the ENTITY_TABof the entity manager enables efficient BOL table operations for all entities, forexample, CL_CRM_BOL_CORE->MODIFY().

An entity is a wrapper for a GenIL container objectCL_CRM_GENIL_CONTAINER_OBJECT belonging to a data container. This objectis referred to as CONTAINER_PROXY and holds the attributes, properties, andrelationships of the entity.

1.2.2 CollectionsVarious collections reference a set of BOL entities and offer convenient access to theirproperties.

Page 32: Cookbook BOL App CRM2007

1 Business Object Layer

32 <July 2008>

<<Interface>>IF_BOL_BO_COL

CL_CRM_BOL_BO_COL

entity_list

CL_CRM_ENTITY_COL

entity_list

<<Interface>>IF_BOL_BO_PROPERTY_ACCESS

CL_CRM_BOL_QUERY_SERVICE CL_CRM_BOL_ENTITY

11

0..n

0..n

In the diagram above:

A collection is represented by the IF_BOL_BO_COL interface and can either be anentity collection CL_CRM_ENTITY_COL or the generalized business object collectionCL_CRM_BOL_BO_COL.

A business object collection can hold entities (for example, CL_CRM_BOL_ENTITY)and query services (for example, CL_CRM_BOL_QUERY_SERVICE).

Access to properties of BOL objects is offered by the interfaceIF_BOL_BO_PROPERTY_ACCESS with its standard access methods, such asIF_BOL_BO_PROPERTY_ACCESS~GET_PROPERTY,GET_PROPERTY_AS_STRING(), or SET_PROPERTY().

1.2.3 Context NodesContext nodes belong to the model part of the CRM WebClient UI framework, which supportsthe model view controller pattern. The model holds business object data, therefore it isrelated to the business object layer through collection wrappers (as shown in the followingdiagram).

Page 33: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 33

CL_BSP_WD_CONTEXT_NODE

get_collection_wrapper()set_collection_wrapper()set_collection()clear_collection()

CL_BSP_WD_COLLECTION_WRAPPER

set_collection()clear_collection()<<event>>new_focus()

<<Interface>>IF_BOL_BO_COL

<<Interface>>IF_BOL_BO_COL

1

1

1..n

-collection

-collection_wrapper

In the above diagram:

Each context node represented by an instance derived from classCL_BSP_WD_CONTEXT_NODE has a collection wrapper. Wrappers implemented byclass CL_BSP_WD_COLLECTION_WRAPPER can be shared among differentcontext nodes.

The collection wrapper wraps a business object collection, IF_BOL_BO_COL, whichcan be set (CL_BSP_WD_COLLECTION_WRAPPER->SET_COLLECTION) andcleared (SET_COLLECTION) but not directly accessed.

The collection wrapper implements the business object collection interface to provideindirect access to the wrapped collection.

The attributes of the current entity in the collection (wrapper) are displayed on the UI.

Page 34: Cookbook BOL App CRM2007

1 Business Object Layer

34 <July 2008>

The IF_BOL_ENTITY_COL~FOCUS_CHANGED event of the collection is publishedby the wrapper as a NEW_FOCUS event. This allows implementing dependenciesbetween model nodes, for example, when the user selects another order entity on thescreen and the list of order items displayed is adjusted accordingly.

A context node is called Model Node if it holds BOL entities defined in a GenILcomponent.

1.2.4 Controller ContextThe model and its nodes can be accessed from the underlying controller.

CL_BSP_WD_CONTROLLER

CL_BSP_WD_CONTEXT

CL_BSP_WD_CONTEXT_NODE

1

1

1

1..n

+owner

+typed_context

+<name>

In the above diagram:

Each view, custom, or component controller owns a context that it inherits fromCL_BSP_WD_CONTEXT, which holds a set of context nodes derived fromCL_BSP_WD_CONTEXT_NODE.

You can create the context within the WD_CREATE_CONTEXT method of thespecific controller, which overrides the base class method provided byCL_BSP_WD_CONTROLLER. In the construction of the context, all of its nodes arecreated. By overriding the WD_INIT_CONTEXT method (also provided byCL_BSP_WD_CONTROLLER) a specific controller can explicitly initialize its contextnodes.

Page 35: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 35

Neither context nor context nodes are expected to be shared between controllers. Theunderlying collections can be shared using the collection wrapper class by contextnode binding.

1.2.5 Data BindingThe following graphic illustrates the relationship between the controller, the model, and theview, which pulls business data from the model’s context nodes on the user interface of theCRM WebClient UI Framework.

<VIEW>

CL_BSP_WD_CONTROLLER

m_modelsCL_BSP_WD_CONTEXT_NODE

CL_BSP_WD_CONTEXT1 1

1

1

1

11

1..n

1..n

0..n

+<name>

+<name>

+view

+controller

+owner

+typed_context

In the above diagram:

The view (derived from CL_BSP_PAGE) is created and owned by the controller.

Context nodes can be set as page attributes to a view (done in the controller’simplementation of the CL_BSP_WD_VIEW_CONTROLLER->SET_MODELS()method). These page attributes are used for data binding to show model attributes onthe view or page.

The context nodes belonging to a controller are also kept in the controller’s tableM_MODELS, inherited from base class CL_BSP_CONTROLLER2. This information isused for data binding in the DO_HANDLE_DATA() method.

1.2.6 Mixed and Value Nodes of the Controller ContextA user interface view displays properties of BOL entities defined in the GenIL model. Thecontext node holding these entities is then called a model node.

Page 36: Cookbook BOL App CRM2007

1 Business Object Layer

36 <July 2008>

Sometimes it is necessary to display further entity-related attributes that are not part of theunderlying GenIL model and that are calculated at runtime. This is possible using mixed nodeelements, which contain a regular BOL entity plus a value part with application-definedattributes. The corresponding context node is referred to as a mixed node.

A mixed node element (represented by class CL_BSP_WD_MIXED_NODE) consistsof a model part referencing a regular BOL entity and a value part holding additionalapplication-defined data.

CL_BSP_WD_MIXED_NODE implements the IF_BOL_BO_PROPERTY_ACCESSinterface and does not inherit from CL_BSP_WD_CONTEXT_NODE.

When creating the element you hand over the BOL entity reference and a structurewith application-defined data.

You use the IF_BOL_BO_PROPERTY_ACCESS interface to access the element’sproperties. The mixed node automatically dispatches the request to either the modelor the value part.

You may also use<IF_BSP_WD_EXT_PROPERTY_ACCESS>~GET_MODEL_NODE() to access theunderlying BOL entity.

Mixed node elements can be added to IF_BOL_BO_COL collections, which acceptobjects implementing the IF_BOL_BO_PROPERTY_ACCESS interface.

It is easy to display mixed nodes on the UI, as context node binding proceeds asnormal.

To facilitate the application of mixed node elements, a specialization of the collection wrapperCL_BSP WD_2COLLECTION_WRAPPER is available.

Assign CL_BSP_WD_2COLLECTION_WRAPPER to your mixed context node anduse its SET_VALUE_STRUCT method to declare the data structure with additionalapplication-defined attributes.

Add BOL entities to the node’s collection wrapper as usual. When its items areaccessed (for example, for UI display) a mixed node element with application-definedattributes is automatically created and returned.

This technique saves memory because you only create the value part if it is needed.

The collection wrapper supports sorting by both model and value attributes.

CL_BSP WD_2COLLECTION_WRAPPER uses the built-in unifier manager, as shown in thediagram below:

Page 37: Cookbook BOL App CRM2007

1 Business Object Layer

<July 2008> 37

CL_BSP_WD_COLLECTION_WRAPPER

CL_BSP_WD_2COLLECTION_WRAPPER LCL_UNIFIER_MANAGER(from CL_BSP_WD_2COLLECTION_WRAPPER)

<<Interface>>IF_BOL_BO_COL

<<Interface>>IF_BOL_BO_PROPERTY_ACCESS

<<Interface>>IF_BOL_BO_EXT_PROPERTY_ACCESS

CL_BSP_WD_MIXED_NODE

<<Interface>>IF_BOL_BO_PROPERTY_ACCESS

CL_BSP_WD_VALUE_NODE

CL_CRM_BOL_BO_COL

<<Interface>>IF_BOL_BO_PROPERTY_ACCESS

1

1

1

1

11

1

1

1..n

0..n#collection

-model_node -value_node

11

The CRM WebClient UI framework also supports value nodes, which contain value nodeelements having an application-defined value part only.

A value node element is represented by class CL_BSP_WD_VALUE_NODE, whichaccepts application-defined attributes in its constructor method.

You can use the IF_BOL_BO_PROPERTY_ACCESS interface to access itsattributes.

Value node elements can be added to IF_BOL_BO_COL collections.

Context node binding and the UI display work as normal.