• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Ja450 en col73_fv_part_a4
 

Ja450 en col73_fv_part_a4

on

  • 918 views

Sap training

Sap training

Statistics

Views

Total Views
918
Views on SlideShare
918
Embed Views
0

Actions

Likes
0
Downloads
26
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Ja450 en col73_fv_part_a4 Ja450 en col73_fv_part_a4 Document Transcript

    • JA450 Web Dynpro Java on SAP NetWeaver 7.1 SAP NetWeaver Date Training Center Instructors Education Website Participant Handbook Course Version: 73 Course Duration: 5 Day(s) Material Number: 50089420 An SAP course - use it to learn, reference it for work
    • Copyright Copyright © 2008 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. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Trademarks • Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are registered trademarks of Microsoft Corporation. • IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®, S/390®, AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation. • ORACLE® is a registered trademark of ORACLE Corporation. • INFORMIX®-OnLine for SAP and INFORMIX® Dynamic ServerTM are registered trademarks of Informix Software Incorporated. • UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group. • Citrix®, the Citrix logo, ICA®, Program Neighborhood®, MetaFrame®, WinFrame®, VideoFrame®, MultiWin® and other Citrix product names referenced herein are trademarks of Citrix Systems, Inc. • HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. • JAVA® is a registered trademark of Sun Microsystems, Inc. • JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. • SAP, SAP Logo, R/2, RIVA, R/3, SAP ArchiveLink, SAP Business Workflow, WebFlow, SAP EarlyWatch, BAPI, SAPPHIRE, Management Cockpit, mySAP.com Logo and mySAP.com are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other products mentioned are trademarks or registered trademarks of their respective companies. Disclaimer THESE MATERIALS ARE PROVIDED BY SAP ON AN "AS IS" BASIS, AND SAP EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR APPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THESE MATERIALS AND THE SERVICE, INFORMATION, TEXT, GRAPHICS, LINKS, OR ANY OTHER MATERIALS AND PRODUCTS CONTAINED HEREIN. IN NO EVENT SHALL SAP BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES OF ANY KIND WHATSOEVER, INCLUDING WITHOUT LIMITATION LOST REVENUES OR LOST PROFITS, WHICH MAY RESULT FROM THE USE OF THESE MATERIALS OR INCLUDED SOFTWARE COMPONENTS. g2008111543239
    • About This Handbook This handbook is intended to complement the instructor-led presentation of this course, and serve as a source of reference. It is not suitable for self-study. Typographic Conventions American English is the standard used in this handbook. The following typographic conventions are also used. Type Style Description Example text Words or characters that appear on the screen. These include field names, screen titles, pushbuttons as well as menu names, paths, and options. Also used for cross-references to other documentation both internal (in this documentation) and external (in other locations, such as SAPNet). Example text Emphasized words or phrases in body text, titles of graphics, and tables EXAMPLE TEXT Names of elements in the system. These include report names, program names, transaction codes, table names, and individual key words of a programming language, when surrounded by body text, for example SELECT and INCLUDE. Example text Screen output. This includes file and directory names and their paths, messages, names of variables and parameters, and passages of the source text of a program. Example text Exact user entry. These are words and characters that you enter in the system exactly as they appear in the documentation. <Example text> Variable user entry. Pointed brackets indicate that you replace these words and characters with appropriate entries. Icons in Body Text The following icons are used in this handbook. 2008 © 2008 SAP AG. All rights reserved. iii
    • About This Handbook Icon JA450 Meaning For more information, tips, or background Note or further explanation of previous point Exception or caution Procedures Indicates that the item is displayed in the instructor's presentation. iv © 2008 SAP AG. All rights reserved. 2008
    • Contents Course Overview ......... ............... ............... ............... ... vii Course Goals ...........................................................vii Course Objectives .....................................................vii Unit 1: SAP Java Development Environment ... ............... ..... 1 SAP NetWeaver Application Server Java ...........................2 SAP NetWeaver Developer Studio ................................. 10 Unit 2: Web Dynpro Introduction.... ............... ............... ... 19 Overview ............................................................... 20 Architecture ............................................................ 27 Unit 3: Web Dynpro Navigation...... ............... ............... ... 41 Simple Navigation..................................................... 42 View Set................................................................ 58 View Container ........................................................ 69 Unit 4: Web Dynpro Context Usage ............... ............... ... 77 Context Definition ..................................................... 78 UI Manipulation........................................................ 96 Java Dictionary .......................................................108 Unit 5: Web Dynpro Context Manipulation....... ............... .. 125 Context Access.......................................................127 Multiple Context Elements ..........................................150 Selecting Context Elements ........................................168 Calculated Attributes ................................................181 Dependent Nodes....................................................192 Unit 6: Web Dynpro Models .......... ............... ............... .. 211 Models.................................................................212 Web Service Model ..................................................217 Model Component ...................................................247 Unit 7: Web Dynpro UI Services ..... ............... ............... .. 267 Internationalization...................................................268 Messages .............................................................276 Pop-ups ...............................................................295 Dictionary Based Value Selectors .................................320 2008 © 2008 SAP AG. All rights reserved. v
    • Contents JA450 Appendix 1: Tools and Classes ........... ............... ......... 335 Index .. ............... ............... ............... ............... ......... 339 vi © 2008 SAP AG. All rights reserved. 2008
    • Course Overview This course introduces the Web Dynpro for Java technology on SAP NetWeaver 7.1 technology. Target Audience This course is intended for the following audiences: • • Developers and consultants who want to create applications based on the Web Dynpro for Java programming model Project managers with technical experience who want to learn about the capabilities of Web Dynpro for Java Course Prerequisites Required Knowledge • JA100 (SAP J2SE Fundamentals) or similar knowledge Course Goals This course will prepare you to: • develop graphical user interfaces with Web Dynpro for Java on SAP NetWeaver 7.1 technology Course Objectives After completing this course, you will be able to: • • • • • 2008 develop a basic Web Dynpro application create and implement a UI using Views and Windows. create and implement programming logic using Web Dynpro Controllers. interact with a business backend system via Web Service. use and implement Web Dynpro UI Services. © 2008 SAP AG. All rights reserved. vii
    • Course Overview viii JA450 © 2008 SAP AG. All rights reserved. 2008
    • Unit 1 SAP Java Development Environment Unit Overview This chapter introduces the development environment for Web Dynpro for Java. It consist of two lessons, one about the NetWeaver Application Server Java running Web Dynpro applications and one about the NetWeaver Developer Studio offering tools for developing. There will be one exercise for initializing the course environment. Unit Objectives After completing this unit, you will be able to: • • • • outline the different SAP NetWeaver releases in respect of supported Java standards describe the cluster architecture of Application Server Java list the basic features of the SAP NetWeaver Developer Studio explain the SAP Component Model Unit Contents Lesson: SAP NetWeaver Application Server Java ............................2 Lesson: SAP NetWeaver Developer Studio .................................. 10 Exercise 1: Course Initialization ........................................... 15 2008 © 2008 SAP AG. All rights reserved. 1
    • Unit 1: SAP Java Development Environment JA450 Lesson: SAP NetWeaver Application Server Java Lesson Overview This lesson outlines the different SAP NetWeaver releases particularly with regard to Java application development. In addition it provides an overview of the cluster architecture of the Application Server Java (AS Java). Lesson Objectives After completing this lesson, you will be able to: • • outline the different SAP NetWeaver releases in respect of supported Java standards describe the cluster architecture of Application Server Java Business Example You are an experienced software developer and you want to develop distributed Java applications on the SAP NetWeaver platform. For this reason, you need an overview of the different SAP NetWeaver releases in respect of supported Java standards and an overview of the cluster architecture of AS Java. SAP NetWeaver Platform The SAP NetWeaver Composition Environment is fully compliant with the Java EE 5 standards. You can develop enterprise applications as Java EE 5 modules, and thus benefit from the numerous advantages this standard introduces. Besides the runtime support, the SAP NetWeaver Composition Environment provides development support for Java EE 5. The SAP NetWeaver Developer Studio provides convenient tools for developing, deploying, and debugging Java EE 5 applications. 2 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: SAP NetWeaver Application Server Java Figure 1: Java Development on SAP NetWeaver Platform The Java Platform, Enterprise Edition uses a multiple-tier distributed software architecture in which each tier only communicates with the tier immediately adjacent to it using clearly defined interfaces. 2008 © 2008 SAP AG. All rights reserved. 3
    • Unit 1: SAP Java Development Environment JA450 Figure 2: Java EE 5 Architecture The architecture is based on the following tiers: Client Tier This tier displays information and is responsible for interaction with the user. HTML pages, applets, J2SE applications, and non-Java programs (such as CORBA clients) can all appear as a client. Web Tier Web tier components run on the Application Server. Beside SAP's Web Dynpro technology the Java EE web components are servlets or pages created using Java Server Pages technology (JSP pages). Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. Business Tier Business code is handled by enterprise beans running in the business tier on the Java EE server. An enterprise bean receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. 4 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: SAP NetWeaver Application Server Java Enterprise Information System Tier This tier includes enterprise infrastructure systems such as Enterprise Resource Planning (ERP), mainframe transaction processing, database systems and other legacy information systems. For example, Java EE application components might need access to enterprise information systems for database connectivity. Each application component is executed in a container. These containers provide the application components with services in accordance with the Java EE specification. Examples of these services are transaction management, security, client connection, and database access. This means that the developer can concentrate purely on the application logic and does not need to deal with these system functions. Java EE 5 offers many improvements to previous releases. J2EE is traditionally recognized for being very powerful but complex to use. Java EE 5 maintains the powerful features of previous releases and offers more flexibility to the application developer. The main focus of the Java EE 5 specification is ease of development. With Java EE 5, the application developer benefits from a simplified application architecture. Most boilerplate code from previous releases is now obsolete. Java EE 5 lets the developer focus on implementing the business scenario of the application and shifts more work to the containers providing a set of intelligent defaults for the most common cases. Note: Web Dynpro is fully compliant with Java EE 5 and benefits from all its improvements. But Web Dynpro applications also make use of services only offered by a SAP NetWeaver Application Server Java. Therefore other Java server vendors are not supported. Architecture of Application Server Java The Application Server (AS) Java is part of the SAP NetWeaver Application Platform. It provides the complete infrastructure for deploying and running Java applications. 2008 © 2008 SAP AG. All rights reserved. 5
    • Unit 1: SAP Java Development Environment JA450 Figure 3: SAP NetWeaver Application Server Java AS Java is optimized to run mission-critical business applications and provides a number of new concepts and enhanced features, such as: • • • • • • Increased robustness and stability of the server infrastructure and applications Simplification of server infrastructure and improved supportability Advanced administration capabilities provided by the Zero Administration concept – a dynamic and template-based configuration that simplifies the technical configuration within the AS Java Enhanced monitoring and easy access to all monitoring data Integration of SAP Java Virtual Machine (JVM) with additional capabilities Central cache management and session management Cluster Architecture The AS Java cluster is a set of processes that work together to build a scalable and reliable system. The cluster architecture is transparent to the client and appears to it as a single server unit. An AS Java cluster consists of several types of instances, all of which have an instance number and can be started, stopped and monitored separately. They are: Central Services Instance The central services instance consists of a Message Service and Enqueue Service. They are responsible for lock administration, message exchange and load balancing within the Java cluster. 6 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: SAP NetWeaver Application Server Java One or more Java Instances A Java instance consists of an Internet Communication Manager (ICM) and one or several server processes. The ICM handles requests coming from clients and dispatches them to the available server processes which actually process the requests. One or several Databases The database stores system and application data. An appropriate cluster setup is one of the main prerequisites for the efficient performance of your system. You can scale the Java cluster by installing additional Java instances to your system, or by adding server processes to an already existing Java instance. For high availability reasons, the different instances can be split up among different physical machines. Figure 4: Minimum AS Java Cluster Installation A minimum AS Java cluster installation consists of a central services instance, one Java instance with one server process, and a database. 2008 © 2008 SAP AG. All rights reserved. 7
    • Unit 1: SAP Java Development Environment JA450 Figure 5: Large AS Java Cluster Installation A larger AS Java installation can have several Java instances with more than one server process each, a central services instance, and one or several databases. Hint: If you want to learn more about administrating the AS Java visit the course JA410 for the developer or the ADM800 for the administrator point of view. Instead or in addition you can also access the SAP Developer Network on http://sdn.sap.com. 8 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: SAP NetWeaver Application Server Java Lesson Summary You should now be able to: • outline the different SAP NetWeaver releases in respect of supported Java standards • describe the cluster architecture of Application Server Java 2008 © 2008 SAP AG. All rights reserved. 9
    • Unit 1: SAP Java Development Environment JA450 Lesson: SAP NetWeaver Developer Studio Lesson Overview This lesson provides an introduction to the SAP NetWeaver Developer Studio, SAP’s own environment for developing Java-based, multiple-layered business applications. Lesson Objectives After completing this lesson, you will be able to: • • list the basic features of the SAP NetWeaver Developer Studio explain the SAP Component Model Business Example You are an experienced software developer and you want to develop Java applications which are to run on the Application Server Java. For that reason, you need an introduction to the SAP NetWeaver Developer Studio. Overview By offering a single point of entry for all Java development tools and an integration point for all SAP infrastructure components, the SAP NetWeaver Developer Studio (subsequently abbreviated to Developer Studio) supports you in composing and developing applications. Moreover, it is based on a defined software logistics process. Application developers do not need to switch between different development environments for the presentation and business logic. Instead they can develop, build, deploy, and execute applications centrally from the Developer Studio. The SAP NetWeaver Developer Studio offers full support when you develop large-scale Java projects, irrespective of whether you use SAP technologies, like Web Dynpro and Java Dictionary, or standard technologies, like Java EE 5 and XML. 10 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: SAP NetWeaver Developer Studio Figure 6: SAP NetWeaver Developer Studio Overview The Developer Studio is based on Eclipse 3.3, an open source product, whose open architecture provides a suitable platform for incorporating specific functions. The Developer Studio integrates a wider range of functions, available using the plug-ins in the existing platform. The Developer Studio implicitly includes all the standard components and features of the Eclipse Workbench. It extends them with a range of tools and utilities bundled in the appropriate SAP perspectives for the task at hand. The SAP tools in the Developer Studio are organized. This enables application developers to focus on specific tasks. The following SAP perspectives are available in the current release of the Developer Studio: SAP Management Console Tools to administer the SAP NetWeaver Application Server. Composite Application Perspective to develop with the Composite Application Framework (CAF). Web Dynpro Perspective to develop Web Dynpro for Java applications. Java EE Perspective to develop Java EE applications. 2008 © 2008 SAP AG. All rights reserved. 11
    • Unit 1: SAP Java Development Environment JA450 Dictionary Perspective to create and modify data types, structures and tables. Development Infrastructure Tools to work with SAP’s Component Model. Design Time Repository Tools to work with the Design Time Repository. → Open Perspective. You To open a perspective choose the command Window then can select the perspective from the menu. If the required perspective is not in the list, choose Other… and then select the required perspective. In order to work with the SAP tools in the Developer Studio you have to set some preferences before you can start with the development. Figure 7: SAP NetWeaver Developer Studio Preferences SAP AS Java Defines the server you are developing with. To change the settings SAP AS Java. or add a new server, choose Window Preferences… → → Component Model In the component model there are two main elements: 12 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: SAP NetWeaver Developer Studio Software components (SCs) These are delivery and installation units, which group the different development components. Development components (DCs) These are the development and build units you use in your daily work. They group the development objects without overlapping. A development component represents a software unit that you develop. A DC is always assigned to a certain software component. Figure 8: Main Elements of the Component Model A development object is the part of the DC that you change or develop. It provides the DC with a certain part of its functionality. For example a development object can be a Java class, a JSP page and so on. Besides development objects, a DC can contain other DCs, that is, DCs can be nested. An inner or child DC is invisible to the outside world and protected by the outer or parent DC. A DC can contain any number of inner DCs, and inner DCs can themselves contain inner DCs. Hint: In this course you will always use DC projects instead of normal Eclipse projects. They offer several features in organizing the development, which will not be shown in detail in this course. If you want to learn more about SAP's NetWeaver Development Infrastructure visit the course JA410 or access the SAP Developer Network on http://sdn.sap.com. 2008 © 2008 SAP AG. All rights reserved. 13
    • Unit 1: SAP Java Development Environment 14 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: SAP NetWeaver Developer Studio Exercise 1: Course Initialization Exercise Objectives After completing this exercise, you will be able to: • initialize the training environment. • prepare the NWDS for developing Web Dynpro. Business Example Before you can start developing Web Dynpro, you must prepare your development environment. Task: Import the template solutions of this course into your workspace and register the SAP NetWeaver Application Server assigned to you in your SAP NetWeaver Developer Studio. 1. 2. Start the NWDS on the WTS. Go to Window -> Preferences and click on the entry SAP AS Java on the left. Register your SAP instance by entering your Instance host and Instance number in the input fields on the bottom right. 3. 2008 Copy the archive containing all template solutions from a central share to a personal folder on the WTS. In order to do this, start a batch file on the WTS. Create a project for the DC training.sap.com~hello. © 2008 SAP AG. All rights reserved. 15
    • Unit 1: SAP Java Development Environment JA450 Solution 1: Course Initialization Task: Import the template solutions of this course into your workspace and register the SAP NetWeaver Application Server assigned to you in your SAP NetWeaver Developer Studio. 1. Copy the archive containing all template solutions from a central share to a personal folder on the WTS. In order to do this, start a batch file on the WTS. a) 2. The menu path to this batch file is provided by the trainer. Start the NWDS on the WTS. Go to Window -> Preferences and click on the entry SAP AS Java on the left. Register your SAP instance by entering your Instance host and Instance number in the input fields on the bottom right. a) b) 3. The menu path to the batch file starting the NWDS is provided by the trainer The settings of the SAP instance is provided by the trainer. Create a project for the DC training.sap.com~hello. a) b) Expand the tree in the Component Browser to My Components. c) Right click on hello [training.sap.com] and select Create Project. d) 16 Open the Development Infrastructure perspective in the NWDS. Confirm the following pop-ups. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: SAP NetWeaver Developer Studio Lesson Summary You should now be able to: • list the basic features of the SAP NetWeaver Developer Studio • explain the SAP Component Model 2008 © 2008 SAP AG. All rights reserved. 17
    • Unit Summary JA450 Unit Summary You should now be able to: • outline the different SAP NetWeaver releases in respect of supported Java standards • describe the cluster architecture of Application Server Java • list the basic features of the SAP NetWeaver Developer Studio • explain the SAP Component Model 18 © 2008 SAP AG. All rights reserved. 2008
    • Unit 2 Web Dynpro Introduction Unit Overview This chapter shows the key features of Web Dynpro and explains the Model View Controller concept used for designing Web Dynpro application. It consists of two lessons and one exercise covering the well-known hello world example. Unit Objectives After completing this unit, you will be able to: • • • • • explain the basic principle of Web Dynpro. explain the Web Dynpro metamodel. explain the Model View Controller design paradigm. explain the architecture of a Web Dynpro Component. describe the tasks of the different Web Dynpro controllers. Unit Contents Lesson: Overview................................................................ 20 Lesson: Architecture............................................................. 27 Exercise 2: Hello World..................................................... 35 2008 © 2008 SAP AG. All rights reserved. 19
    • Unit 2: Web Dynpro Introduction JA450 Lesson: Overview Lesson Overview This lesson provides an introduction to the Web Dynpro world talking about the main benefits, metamodel and application scenarios. Lesson Objectives After completing this lesson, you will be able to: • • explain the basic principle of Web Dynpro. explain the Web Dynpro metamodel. Business Example You want to develop a web-based UI using SAP’s Web Dynpro technology and therefore get an insight of the architecture of Web Dynpro. Introduction What is Web Dynpro? From a technological point of view, SAP’s Web Dynpro for Java is a revolutionary step in the development of web-based user interfaces. It is completely unlike any design paradigm ever used by SAP before and represents a quantum leap in the development of web-based ERP applications. 20 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Overview Figure 9: What is Web Dynpro Web Dynpro applications are built using declarative programming techniques based on the Model View Controller (MVC) design paradigm. That is, you specify what user interface elements you wish to have on the client and where those elements will get their data from. All the code to create the user interface is then generated automatically within a standard runtime framework. This relieves you from the repetitive coding tasks involved in writing HTML and then making it interactive with JavaScript. So talking about Web Dynpro you can distinguish four aspects: Technology for software modularization The Web Dynpro components structure projects and support pattern-based UIs. Runtime environment for applications The framework running on SAP’s NetWeaver Application Server (NWAS) offers common services. Programming model for user interfaces Defines a standard structure for user interface applications derived from the MVC. Set of tools for user interface design SAP’s Netweaver Developer Studio (NWDS) offers tools focused on graphical modelling where code is generated from meta-model declarations. 2008 © 2008 SAP AG. All rights reserved. 21
    • Unit 2: Web Dynpro Introduction JA450 Figure 10: Main Benefits Web Dynpro’s main goal is to enable developers to create powerful Web applications with a minimum of effort using descriptive tools in a structured design. One guiding principle in the Web Dynpro philosophy is, the fewer lines of hand-written code there are in the UI, the better. Since the repetitive tasks of UI coding have been eliminated, the developer can focus their attention on the flow of business data through the application. Web Dynpro provides technical features such as support for internationalization and flicker-free interaction. Flicker-free means, that only the parts of the UI which changes on user interaction are refreshed. This makes the UI looking more “stable” and minimizes the data for UI generation transferred between server and client. Web Dynpro has been realized in Java and ABAP. The applications can run on a range of devices and on various types of network – an important feature for collaboration scenarios. Metamodel and Custom Coding A Web Dynpro application is developed using a declarative programming approach. Within the SAP NetWeaver Development Studio there are special tools that allow you to define the architecture of your application without needing to write any code. This representation is known as a metamodel. 22 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Overview The application metamodel is then used to generated skeleton coding that provides the framework within which you can create your own custom business logic. Once your application has been built and deployed to the SAP AS Java, it executes within a standard server-side runtime environment known as the Web Dynpro Framework (WDF). Figure 11: Metamodel and Custom Coding All Web Dynpro applications are constructed from the same basic units. However, through the use of custom coding the standard framework can be extended to supply any required business functionality. Not all implementation decisions need to be made at design time. It is perfectly possible to implement a Web Dynpro application in which the appearance of the user interface is decided at runtime. This allows a highly flexible application to be written without requiring the need to directly write any HTML or JavaScript. Web Dynpro application metadata is platform independent. It is therefore possible to develop an application on one platform and then deploy it on another. Caution: The NWDS used for developing and the NWAS running the application must have the same release state. Therefore both are shipped together. 2008 © 2008 SAP AG. All rights reserved. 23
    • Unit 2: Web Dynpro Introduction JA450 Application Scenarios Web Dynpro for Java was first released for the SAP Web Application Server 6.40. Web Dynpro for ABAP was released for the SAP NetWeaver Application Server 7.0. The design paradigm is identical in both worlds but use of course different techniques to realize an application. Figure 12: Application Scenarios The development in Java takes place in the NWDS, for ABAP it is integrated in the ABAP Workbench. Both tool sets generate metadata for the respective programming language. The result is a web page accessible via HTTP(S) and capable of being integrated in the SAP Enterprise Portal (EP). The generated user interface looks nearly the same with small differences depending on the release state between Java and ABAP. So when deciding between Java and ABAP as programming language for Web Dynpro, the user interface is not the crucial factor. It is the used business data especially the services available for accessing. Web Dynpro for Java can be supplied with information from following types of backend systems: • • • Remote enabled Function Modules (RFMs) in an ABAP backend system Enterprise Java Beans (EJBs) in a Java backend system Web Services in an arbitrary backend system ABAP is capable of connecting to RFMs and Web Services but not to EJBs. However when interacting with the ABAP world it is more easy to develop directly in ABAP and of course delivers a better performance. Therefore if the 24 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Overview available data services are primary available in ABAP, develop Web Dynpro for ABAP. But if you need to connect different data sources especially Java to your application, develop Web Dynpro for Java. Hint: One more reason developing Web Dynpro for Java is when extending the generated coding of the SAP Visual Composer. It is a web-based Java tool generating pattern-based UIs without the possibility of custom coding. 2008 © 2008 SAP AG. All rights reserved. 25
    • Unit 2: Web Dynpro Introduction JA450 Lesson Summary You should now be able to: • explain the basic principle of Web Dynpro. • explain the Web Dynpro metamodel. 26 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Architecture Lesson: Architecture Lesson Overview Overview: This lesson demonstrates the structure of a Web Dynpro application derived from the standard Model View Controller design paradigm. Lesson Objectives After completing this lesson, you will be able to: • • • explain the Model View Controller design paradigm. explain the architecture of a Web Dynpro Component. describe the tasks of the different Web Dynpro controllers. Business Example You want to understand what a Web Dynpro component is and how it is structured regarding the Model View Controller design paradigm. Model View Controller The Model View Controller (MVC) design paradigm was invented by the Norwegian software designer Trygve Reenskaug (pronounced “TRIG-vuh RAINS-cow”) whilst working for Xerox PARC in the late seventies. The first implementation was with the release of the Smalltalk-80 programming language. It was a revolutionary design paradigm because it was the first to describe software components in terms of the functional responsibilities each should fulfil: Model Decouples the backend system from the local application View Visualizes the application data supplied by the model Controller Binds the model and view together and selects which view to display next 2008 © 2008 SAP AG. All rights reserved. 27
    • Unit 2: Web Dynpro Introduction JA450 Figure 13: Data Processing and Presentation The diagram shows a typical implementation of the MVC. For instance, Java Server Pages (JSPs) uses this style of implementation having the web-page as fundamental unit of development. However, Web Dynpro uses a different approach to the MVC. The fundamental unit of development is the so called Web Dynpro component. It consists of visual controllers and non-visual controllers. 28 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Architecture Figure 14: Data Generation and Consumption The important changes to the standard MVC design paradigm are as followed: • • • Standard MVC allows a model to directly notify a view that it has been changed. This is not been implemented in Web Dynpro. Standard MVC allows for nested view controllers. This is not permitted in Web Dynpro. SAP has extended the design concept by adding an aggregation unit known as component. The reason for two types of controllers in Web Dynpro is because of client device independence. This means that the HTML and JavaScript for any particular web-page can not be created directly in the view, because the view does not know the technical requirements of the front end device. Therefore the UI must be defined in a client independent manner. Component The component is both the unit of application development and application reuse. It consists of visual controllers and non-visual controllers. The Web Dynpro models stand outside of the component. Models are therefore reusable across multiple components. 2008 © 2008 SAP AG. All rights reserved. 29
    • Unit 2: Web Dynpro Introduction JA450 Figure 15: MVC in Web Dynpro All controllers in a component are private to the component itself. Parts of the controllers can be declared public to be used by other components. A component offers two types of interfaces to its controllers: • • Visual interface defined by an interface view Non-visual interface defined by the interface controller The component interface consists of zero or more interface views and exactly one interface controller. The interface controller is the programmatic interface that gives a parent component access to the child component’s functionality. The parent component can call methods in the child’s interface and react on events raised by the child. The Web Dynpro Framework (WDF) never interacts with a component’s interface controller. By means of the interface view, a component’s visual interface becomes a reusable unit, thus allowing you to embed it into a larger view set. An interface view is also used by the WDF to access the application by sending requests and awaiting a response to show the UI to the user. 30 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Architecture Figure 16: Component Architecture The architecture of a Web Dynpro component can be divided into four quadrants: • • The horizontal dotted line separates the entities that are visible from outside the component from those that are only visible from within the component. The vertical dotted line separates the visual entities from the non-visual or programmatic entities. All controllers are independent programs. However, they all play a cooperative role. No controller can function in isolation from its component. Visual controllers always function as data consumers – either from the user via mouse and keyboard or from a non-visual controller. Non-visual controllers act as data generator with respect to visual controllers, but they act as data consumers with respect to models, too. 2008 © 2008 SAP AG. All rights reserved. 31
    • Unit 2: Web Dynpro Introduction JA450 Figure 17: Visual Controllers There are two types of visual controllers and one type of interface. The interface view connects to one window defining the parts visible outside of the component. In former releases the interface view had an implementation but since 7.1 it moved to the window controller. A window consists of a visual part called navigation and a non-visual part called window controller. A window can have one ore more interface views. In the navigation one or more views can be embedded and displayed in parallel. Like the window a view also consists of a visual and non-visual part. In the layout the UI elements are defined like buttons and input fields referencing to the data available in the view controller. A view can be embedded in one or more window navigations but can not be displayed simultaneously. 32 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Architecture Figure 18: Non-Visual Controllers For non-visual controllers there are also two types of controllers and one type of interface. One difference is that the interface controller connects to the one and only component controller. Data, methods and events of the component controller defined in the interface are visible outside of the component. In former releases the interface controller was a stand-alone controller like the others but since 7.1 it is just an interface for the component controller. The component controller is the central controller of the component. It is always present and needs not to be created. Everything defined here has effect on the whole component. It can access model data defined in a backend service. Custom controllers can be created to exculpate the component controller or to centralize specific data and functionality in one place. Like the component controller a custom controller can access the data of a model. 2008 © 2008 SAP AG. All rights reserved. 33
    • Unit 2: Web Dynpro Introduction 34 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Architecture Exercise 2: Hello World Exercise Objectives After completing this exercise, you will be able to: • create a Development Component project for Web Dynpro. • create a simple Web Dynpro component. • create, deploy and run a Web Dynpro application. Business Example When you want to learn a new technology or development technique, it is always good to create the most easiest application possible: Hello World. Solution training.sap.com~hello Task 1: Create a new Web Dynpro Development Component called training.sap.com~groupXX with XX as your group number. 1. Open the Web Dynpro perspective. Go to File -> New -> Web Dynpro Development Component and select MyComponents as Software Component. Enter training.sap.com as vendor, groupXX with XX as your group number and a caption for your exercise DC. Task 2: Create a Web Dynpro component called StudentComp consisting of a window called StudentWindow and an embedded view called StudentView. 1. Expand the tree of your DC in the Web Dynpro Explorer and right click on Components creating a new Web Dynpro Component. 2. Enter the name StudentComp of your component and press next. Change the name of the window to StudentWindow, the name of the interface view to StudentInterfaceView and remove the predefined view. Add a new view called StudentView checking both options Embed and Default. 3. Expand the tree entry Views of your component StudentComp and double click your StudentView. Click on the DefaultTextView in the Outline or in the Layout and change the text in its Properties in the way you like. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 35
    • Unit 2: Web Dynpro Introduction JA450 Task 3: To deploy and run create a Web Dynpro Application for your component called StudentApp. 1. 2. 36 Right click in the Web Dynpro Explorer on the tree entry Applications and choose Create Application. Enter the name StudentApp for the application. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Architecture Solution 2: Hello World Task 1: Create a new Web Dynpro Development Component called training.sap.com~groupXX with XX as your group number. 1. Open the Web Dynpro perspective. Go to File -> New -> Web Dynpro Development Component and select MyComponents as Software Component. Enter training.sap.com as vendor, groupXX with XX as your group number and a caption for your exercise DC. a) Perform as seen in the demonstration of your trainer. Task 2: Create a Web Dynpro component called StudentComp consisting of a window called StudentWindow and an embedded view called StudentView. 1. Expand the tree of your DC in the Web Dynpro Explorer and right click on Components creating a new Web Dynpro Component. a) 2. Enter the name StudentComp of your component and press next. Change the name of the window to StudentWindow, the name of the interface view to StudentInterfaceView and remove the predefined view. Add a new view called StudentView checking both options Embed and Default. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Expand the tree entry Views of your component StudentComp and double click your StudentView. Click on the DefaultTextView in the Outline or in the Layout and change the text in its Properties in the way you like. a) Perform as seen in the demonstration of your trainer. Task 3: To deploy and run create a Web Dynpro Application for your component called StudentApp. 1. Right click in the Web Dynpro Explorer on the tree entry Applications and choose Create Application. Enter the name StudentApp for the application. a) 2. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer. a) 2008 Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 37
    • Unit 2: Web Dynpro Introduction JA450 Lesson Summary You should now be able to: • explain the Model View Controller design paradigm. • explain the architecture of a Web Dynpro Component. • describe the tasks of the different Web Dynpro controllers. 38 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Unit Summary Unit Summary You • • • • • 2008 should now be able to: explain the basic principle of Web Dynpro. explain the Web Dynpro metamodel. explain the Model View Controller design paradigm. explain the architecture of a Web Dynpro Component. describe the tasks of the different Web Dynpro controllers. © 2008 SAP AG. All rights reserved. 39
    • Unit 2: Web Dynpro Introduction 40 © 2008 SAP AG. All rights reserved. JA450 2008
    • Unit 3 Web Dynpro Navigation Unit Overview This chapter covers the navigation concept of Web Dynpro starting with a simple example followed by naviagtion with viewsets and view containers. Each of these three lessons offers an own exercise. Unit Objectives After completing this unit, you will be able to: • • • • • • • • • • embed views in windows. define navigation plugs in the navigation modeler. connect plugs via navigation links. insert UI elements in the layout. explain the combination of actions and navigation. define viewsets in the navigation. create a complex navigation system. explain the term view assembly. handle view containers in the layout and navigation. explain the term re-entrant navigation link. Unit Contents Lesson: Simple Navigation ..................................................... 42 Exercise 3: Simple Navigation ............................................. 53 Lesson: View Set ................................................................ 58 Exercise 4: Navigation with Viewset ...................................... 63 Lesson: View Container......................................................... 69 Exercise 5: Navigation with View Container ............................. 71 2008 © 2008 SAP AG. All rights reserved. 41
    • Unit 3: Web Dynpro Navigation JA450 Lesson: Simple Navigation Lesson Overview This lesson explains the purpose of navigation in Web Dynpro and how a simple navigation is realized. Furthermore it shows how to insert UI elements in the layout of views for starting the navigation. Lesson Objectives After completing this lesson, you will be able to: • • • • • embed views in windows. define navigation plugs in the navigation modeler. connect plugs via navigation links. insert UI elements in the layout. explain the combination of actions and navigation. Business Example You want to use navigation to change the UI at runtime replacing views by other views. The user should decide which view will be replaced. Defining Navigation The navigation modeler is a Web Dynpro specific graphical editor in which you can define three things for the window navigation: • • • The views to be shown during navigation The position of views within the view area The navigation links between views Open the navigation modeler by double-click on the window or via the context menu of the window. 42 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Figure 19: Definition Inside Windows The navigation is an easy way to change the complete or a part of the UI shown to the user. It can be started by the user when pressing a button for example. Which views are shown and which will disappear is defined in the navigation by connecting views via plugs. 2008 © 2008 SAP AG. All rights reserved. 43
    • Unit 3: Web Dynpro Navigation JA450 Figure 20: Inbound and Outbound Plugs The first view shown to the user has the property default set to true. This is visualized in the navigation modeler by a darker blue. If this view should disappear and another view should be shown, an outbound plug must be fired. This outbound plug is connected via a navigation link to an inbound plug of another view. Firing the outbound plug starts the navigation replacing the shown view by the target view of the navigation. Outbound plugs are therefore navigation exits, inbound plugs navigation entries. Caution: If no view inside the window navigation has the property default set to true, a blank screen will be shown to the user. 44 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Figure 21: Navigation Links Although the plugs can be defined in the navigation modeler, they are part of the views they are defined in. That means if the view is embedded in another window navigation, the plugs will also be available there. In contrast the navigation links are gone because they are defined in the window navigation. This makes it possible to reuse the view in different windows. The navigation started when firing an outbound plug depends on the actual navigation link in the shown window. Caution: Firing an outbound plug having no navigation link attached to it results in a navigation error. Add UI Elements UI elements are defined in the layout of views. Web Dynpro offers a multitude of UI elements accessible via the menu next to the layout. Other UI elements as listed there are not allowed so you can not develop your own UI elements. This is because of the WDF on the server generating a UI suitable for the individual client. 2008 © 2008 SAP AG. All rights reserved. 45
    • Unit 3: Web Dynpro Navigation JA450 Figure 22: Adding via Drag & Drop One way to add UI elements to the layout is via drag & drop. The position of the UI element is not made on pixel-base but using a layout manager. Every UI element is therefore a child of the root UI element defining the layout. 46 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Figure 23: Adding via Insert Child The root UI element is invisible on the layout but can be seen in the outline of the view. All UI elements are structured hierarchically under this root using the properties of the parent UI element. You can use the context menu of the root element to insert additional children by selecting from a table of available UI elements. The UI elements are the same as the ones used by drag & drop. 2008 © 2008 SAP AG. All rights reserved. 47
    • Unit 3: Web Dynpro Navigation JA450 Figure 24: Adding via Apply Template Beside just optical design some UI Elements have a special function as their main task. For these the context menu in the outline offers the wizard to generate UI and function in one step. There are templates available for action button, forms and tables. For the action button for example, an action and action handler is generated and connected to the UI element in the layout. Starting Navigation When the user presses on a button in the UI, a so called server roundtrip is started. That means the client sends a message to the server including the information which UI element event started the roundtrip. The WDF identifies the action connected to the event and calls the registered action handler performing the implementation. 48 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Figure 25: Relating Action to Navigation A UI element is associated with an action by using the respective property. The action is then registered to the action handler. In the action handler methods can be called like the one for firing an outbound plug. 2008 © 2008 SAP AG. All rights reserved. 49
    • Unit 3: Web Dynpro Navigation JA450 Figure 26: UI Element Raises Action Calling an outbound plug method causes a navigation event to be raised. Navigation events are special asynchronous events that are placed in a navigation queue. Outbound plugs should be named according to the action that caused the navigation. 50 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Figure 27: Action Handler Fires Plug Outbound and inbound plugs are joined together using navigation links created in the navigation modeler. This causes the event handler method represented by the inbound plug to subscribe to the navigation event raised by the outbound plug. Figure 28: Event Handler on Plug 2008 © 2008 SAP AG. All rights reserved. 51
    • Unit 3: Web Dynpro Navigation JA450 Inbound plugs are special event handler methods that subscribe to navigation events raised when outbound plugs are fired. Inbound plug methods are called only when the navigation queue is processed. This will only take place if no validation errors have occurred that would cause navigation to be cancelled. Inbound plugs should be named according to the reason for which the view being displayed. 52 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Exercise 3: Simple Navigation Exercise Objectives After completing this exercise, you will be able to: • create and rename views in a Web Dynpro component. • create plugs and navigation links between views. • implement buttons for triggering navigation between views. Business Example You want to develop an application, where you can navigate from one view to another using buttons. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~navigation1XX with XX as your group number. Template training.sap.com~hello Solution training.sap.com~navigation1 Task 1: Rename your StudentView to InputView and create a new view called OutputView. 1. Right click on the StudentView in the Web Dynpro Explorer and select Refactor -> Rename.... Enter the new name InputView in the following pup-up. 2. Go to the navigation of StudentWindow and select Embed new View from the menu on the right. Click in the navigation pane and enter the name OutputView. Task 2: Define a navigation from InputView to OutputView using an outbound plug called ShowOutputOut linked to the inbound plug called ShowOutputIn. Define the reverse navigation from OutputView to InputView using ShowInputOut as outbound plug and ShowInputIn as inbound plug. 1. Select Create OutboundPlug in the navigation of StudentWindow and click on the InputView. Set the name to ShowOutputOut. 2. Select Create InboundPlug in the navigation of StudentWindow and click on the OutputView. Set the name to ShowOutputIn. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 53
    • Unit 3: Web Dynpro Navigation JA450 3. Select Create Link in the navigation of StudentWindow and drag a line from ShowOutputOut to ShowOutputIn. 4. Repeat the steps creating the outbound plug ShowInputOut in the OutputView and the inbound plug ShowInputIn in the InputView. Task 3: Create a button in the InputView with the label “Show Output” firing the outbound plug ShowOutputOut . Set the design property of the button to next. The analogue button in the OutputView has the label “Show Input” firing the outbound plug ShowInputOut. Set its design property to previous. 1. Delete the DefaultTextView in the layout of InputView. Choose Apply Template on the RootElement in the outline and select Action Button. 2. In the wizard enter “Show Output” as label. For the next step select Fire Plug and choose ShowOutputOut from the drop down list. 3. Select the button in the outline or in the layout and set its property design to next. 4. Repeat the steps creating a button with label “Show Input” firing the plug ShowInputOut. Set its property design to previous. Task 4: Deploy new archive and run your application StudentApp. 1. 54 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Solution 3: Simple Navigation Task 1: Rename your StudentView to InputView and create a new view called OutputView. 1. Right click on the StudentView in the Web Dynpro Explorer and select Refactor -> Rename.... Enter the new name InputView in the following pup-up. a) 2. Perform as seen in the demonstration of your trainer. Go to the navigation of StudentWindow and select Embed new View from the menu on the right. Click in the navigation pane and enter the name OutputView. a) Perform as seen in the demonstration of your trainer. Task 2: Define a navigation from InputView to OutputView using an outbound plug called ShowOutputOut linked to the inbound plug called ShowOutputIn. Define the reverse navigation from OutputView to InputView using ShowInputOut as outbound plug and ShowInputIn as inbound plug. 1. Select Create OutboundPlug in the navigation of StudentWindow and click on the InputView. Set the name to ShowOutputOut. a) 2. Select Create InboundPlug in the navigation of StudentWindow and click on the OutputView. Set the name to ShowOutputIn. a) 3. Perform as seen in the demonstration of your trainer. Select Create Link in the navigation of StudentWindow and drag a line from ShowOutputOut to ShowOutputIn. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the steps creating the outbound plug ShowInputOut in the OutputView and the inbound plug ShowInputIn in the InputView. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 55
    • Unit 3: Web Dynpro Navigation JA450 Task 3: Create a button in the InputView with the label “Show Output” firing the outbound plug ShowOutputOut . Set the design property of the button to next. The analogue button in the OutputView has the label “Show Input” firing the outbound plug ShowInputOut. Set its design property to previous. 1. Delete the DefaultTextView in the layout of InputView. Choose Apply Template on the RootElement in the outline and select Action Button. a) 2. In the wizard enter “Show Output” as label. For the next step select Fire Plug and choose ShowOutputOut from the drop down list. a) 3. Perform as seen in the demonstration of your trainer. Select the button in the outline or in the layout and set its property design to next. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the steps creating a button with label “Show Input” firing the plug ShowInputOut. Set its property design to previous. a) Perform as seen in the demonstration of your trainer. Task 4: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) 56 Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Simple Navigation Lesson Summary You • • • • • 2008 should now be able to: embed views in windows. define navigation plugs in the navigation modeler. connect plugs via navigation links. insert UI elements in the layout. explain the combination of actions and navigation. © 2008 SAP AG. All rights reserved. 57
    • Unit 3: Web Dynpro Navigation JA450 Lesson: View Set Lesson Overview This lesson introduces the viewsets separating the navigation of a window in multiple view areas. That makes it possible to show multiple views at the same time. Lesson Objectives After completing this lesson, you will be able to: • • • define viewsets in the navigation. create a complex navigation system. explain the term view assembly. Business Example You want to show multiple views at the same time on the UI. The user should decide which combination will be visible. Multiple Views If you embed views in the view area of the navigation, only one of the views will be shown at any time. To be able to show multiple views together there is the possibility to add viewsets to the navigation. 58 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Set Figure 29: Viewsets and View Areas A viewset is subdivided into several view areas. How many depends on the viewset and its properties. A viewset of type GridLayout consists of rows and columns defined in its properties. Every cell of this table is a view area showing only one view at a time. A viewset of type TabStrip generates a tab strip where every tab is an own view area. The viewsets of type TLayout always define three cells and therefore view areas looking like a “T”. 2008 © 2008 SAP AG. All rights reserved. 59
    • Unit 3: Web Dynpro Navigation JA450 Figure 30: Viewsets Navigation Every view area can have one or more views or again viewsets embedded within it. Which view or viewset will be shown at startup is determined by the property default. Default viewsets have a darker green like the views having a darker blue. Like before navigation takes place using plugs and links. The difference is that the view starting the navigation is not always replaced by the target view. This is only the case if both views are in the same view area. If the target view is in another view area, it will be shown inside that particular view area replacing whatever else was shown there before. Note: If you want to leave a view area empty until the user fires an action or if you want to clear a view area showing a blank screen, insert an EmptyView in the respective view area. An EmptyView can not be changed in any way offering a blank layout and one inbound plug. 60 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Set Figure 31: View Assembly The combination of views seen after each server round trip is completely variable and determined by which navigation plugs are fired. At the end of each server round trip, when the Web Dynpro Framework (WDF) renders a particular combination of views, that combination is known as a view assembly. The view assembly is therefore a subset of views embedded into a window visible at the same time. 2008 © 2008 SAP AG. All rights reserved. 61
    • Unit 3: Web Dynpro Navigation 62 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: View Set Exercise 4: Navigation with Viewset Exercise Objectives After completing this exercise, you will be able to: • change an existing navigation and layout. • use viewsets to show multiple views at the same time. • show images on the UI. Business Example You want to divide your UI into two parts. The top should always show two buttons, which change the lower part of the UI showing one of two images. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~navigation2XX with XX as your group number. Template training.sap.com~navigation1 Solution training.sap.com~navigation2 Task 1: Create a viewset in the navigation of StudentWindow having two rows and one column. Create the new view MainView in the first row and drag & drop the InputView and OutputView in the second row. 1. Go to the navigation of StudentWindow, select GridLayout from the menu on the right and click in the navigation pane. Select the viewset in the navigation and set its properties columns to 1 and default to true. 2. Select Embed new View from the menu on the right. Click in the cell [1,1] of the viewset and enter the name MainView. 3. Select InputView and OutputView and drag & drop both in the cell [1,2] of the viewset. Set the property default of InputView to true. Task 2: Define two outbound plugs in the MainView called ShowInputOut and ShowOutputOut. Connect ShowInputOut with the inbound plug ShowInputIn of InputView and ShowOutputOut with the inbound plug ShowOutputIn of OutputView. 1. Delete the plugs ShowOutputOut of the InputView and ShowInputOut of the OutputView. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 63
    • Unit 3: Web Dynpro Navigation JA450 2. Select Create OutboundPlug in the navigation of StudentWindow and click on the MainView. Set the name to ShowInputOut. 3. Select Create Link in the navigation of StudentWindow and drag a line from ShowOutputOut to ShowOutputIn. 4. Repeat the steps creating the outbound plug ShowOutputOut in the MainView and connect it with the inbound plug ShowOutputIn of OutputView. Task 3: Replace the buttons in the InputView and OutputView by an Image. Choose the web icon Money.gif for the InputView and ShoppingCart.gif for the OutputView. 1. Delete the button in the layout of InputView. Go to Actions of InputView, right click on the action ShowOutput and choose delete. In the following pop-up select Also delete associated event handler and click All. 2. In the layout of InputView, right click in the outline on the RootElement and Insert Child.... Select Image as new UI element. 3. Set the property source of the image by following Browse -> Web Icon... -> Pictogram and choose the picture Money.gif. 4. Repeat the steps for the OutputView deleting the action ShowInput and setting the source of the image to ShoppingCart.gif. Task 4: Create two buttons in the MainView, the first with label “Input” firing the plug ShowInputOut and the second with label “Output” firing the plug ShowOutputOut. 1. Delete the DefaultTextView in the layout of MainView. Choose Apply Template on the RootElement in the outline and select Action Button. 2. In the wizard enter “Input” as label. For the next step select Fire Plug and choose ShowInputOut from the drop down list. 3. Repeat the steps creating a button with label “Output” firing the plug ShowOutputOut. Task 5: Deploy new archive and run your application StudentApp. 1. 64 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Set Solution 4: Navigation with Viewset Task 1: Create a viewset in the navigation of StudentWindow having two rows and one column. Create the new view MainView in the first row and drag & drop the InputView and OutputView in the second row. 1. Go to the navigation of StudentWindow, select GridLayout from the menu on the right and click in the navigation pane. Select the viewset in the navigation and set its properties columns to 1 and default to true. a) 2. Select Embed new View from the menu on the right. Click in the cell [1,1] of the viewset and enter the name MainView. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Select InputView and OutputView and drag & drop both in the cell [1,2] of the viewset. Set the property default of InputView to true. a) Perform as seen in the demonstration of your trainer. Task 2: Define two outbound plugs in the MainView called ShowInputOut and ShowOutputOut. Connect ShowInputOut with the inbound plug ShowInputIn of InputView and ShowOutputOut with the inbound plug ShowOutputIn of OutputView. 1. Delete the plugs ShowOutputOut of the InputView and ShowInputOut of the OutputView. a) 2. Select Create OutboundPlug in the navigation of StudentWindow and click on the MainView. Set the name to ShowInputOut. a) 3. Perform as seen in the demonstration of your trainer. Select Create Link in the navigation of StudentWindow and drag a line from ShowOutputOut to ShowOutputIn. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the steps creating the outbound plug ShowOutputOut in the MainView and connect it with the inbound plug ShowOutputIn of OutputView. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 65
    • Unit 3: Web Dynpro Navigation JA450 Task 3: Replace the buttons in the InputView and OutputView by an Image. Choose the web icon Money.gif for the InputView and ShoppingCart.gif for the OutputView. 1. Delete the button in the layout of InputView. Go to Actions of InputView, right click on the action ShowOutput and choose delete. In the following pop-up select Also delete associated event handler and click All. a) 2. In the layout of InputView, right click in the outline on the RootElement and Insert Child.... Select Image as new UI element. a) 3. Perform as seen in the demonstration of your trainer. Set the property source of the image by following Browse -> Web Icon... -> Pictogram and choose the picture Money.gif. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the steps for the OutputView deleting the action ShowInput and setting the source of the image to ShoppingCart.gif. a) Perform as seen in the demonstration of your trainer. Task 4: Create two buttons in the MainView, the first with label “Input” firing the plug ShowInputOut and the second with label “Output” firing the plug ShowOutputOut. 1. Delete the DefaultTextView in the layout of MainView. Choose Apply Template on the RootElement in the outline and select Action Button. a) 2. In the wizard enter “Input” as label. For the next step select Fire Plug and choose ShowInputOut from the drop down list. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the steps creating a button with label “Output” firing the plug ShowOutputOut. a) Perform as seen in the demonstration of your trainer. Continued on next page 66 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Set Task 5: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) 2008 Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 67
    • Unit 3: Web Dynpro Navigation JA450 Lesson Summary You should now be able to: • define viewsets in the navigation. • create a complex navigation system. • explain the term view assembly. 68 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Container Lesson: View Container Lesson Overview This lesson introduces the ViewContainer UI element behaving like an entire window as part of the layout of a view. This makes it possible to design parts of the UI layout using navigation functionality. Lesson Objectives After completing this lesson, you will be able to: • • handle view containers in the layout and navigation. explain the term re-entrant navigation link. Business Example You want again to show multiple views at the same time but they should not appear next to each other but as part of a main layout. Again the user decides the combination shown. View inside View Since 7.0 it is possible to use ViewContainer UI elements to define a view area inside the layout of a view. A ViewContainer UI element is both, a UI element added to the hierarchy of a view layout, and a view area in the window where the view is embedded. Figure 32: View Container UI Element 2008 © 2008 SAP AG. All rights reserved. 69
    • Unit 3: Web Dynpro Navigation JA450 The advantage to viewsets is that you determine exactly where a view assembly will be shown inside a view. A ViewContainer UI element behaves like an entire window embedded into a view controller's layout. It may contain the visual interface of any combination of single views or entire components. The view offering the new view area can not determine which views will be shown there. Like before this is defined in the navigation of the window. There you can embed views inside the ViewContainer UI element and create navigation links. Figure 33: Re-entrant Navigation Link Before, navigation links always pointed from one view to another. If now connecting a view defining a ViewContainer UI element with a view inside the view container, a so called re-entrant navigation link is created. That means the navigation does not leave the view but re-enters it. Creating a re-entrant navigation link works the same as with normal links: Drag & drop a navigation link from the outbound plug to the inbound plug. Hint: It is recommended to use ViewContainer UI elements instead of viewsets wherever possible. 70 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Container Exercise 5: Navigation with View Container Exercise Objectives After completing this exercise, you will be able to: • use a container UI element to structure the UI layout. • use a ViewContainerUIElement to show multiple views at the same time. • set the action fired by a UI element. Business Example You want to change the content of a UI container by using buttons in the header of the UI container. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~navigation3XX with XX as your group number. Template training.sap.com~navigation2 Solution training.sap.com~navigation3 Task 1: Create a Group UI element with header “Student” in the layout of MainView enclosing a ViewContainerUIElement. Add a ToolBar to the group consisting of the two buttons with the ids InputButton and OutputButton. The buttons should fire the respective outbound plugs. 1. Go to the layout of the MainView and delete both buttons with labels “Input” and “Output”. Right click on the RootElement in the Outline and choose Insert Child... selecting a Group UI element. Set the text of the header UI element to Student. 2. Right click on the Group in the Outline and choose Insert Child... selecting a ViewContainerUIElement. Right click again on the Group and choose Insert ToolBar. 3. Right click on the ToolBar and choose Insert ToolBarItem. Select a ToolBarButton and give it the id InputButton. Set the property onAction by selecting the action Input from the drop down list. 4. Repeat the last step creating a ToolBarButton with id OutputButton firing the action Output. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 71
    • Unit 3: Web Dynpro Navigation JA450 Task 2: Refactor the navigation of StudentWindow by moving the MainView directly on the navigation pane of the window and the InputView and OutputView inside the ViewContainerUIElement of MainView. 1. Go to the navigation of StudentWindow and drag & drop the MainView directly on the navigation pane. Set its property default to true. 2. Drag & drop the InputView and OutputView inside the ViewContainerUIElement of the MainView. Set the property default of the InputView to true. Delete the GridLayout from the navigation. Task 3: Deploy new archive and run your application StudentApp. 1. 72 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Container Solution 5: Navigation with View Container Task 1: Create a Group UI element with header “Student” in the layout of MainView enclosing a ViewContainerUIElement. Add a ToolBar to the group consisting of the two buttons with the ids InputButton and OutputButton. The buttons should fire the respective outbound plugs. 1. Go to the layout of the MainView and delete both buttons with labels “Input” and “Output”. Right click on the RootElement in the Outline and choose Insert Child... selecting a Group UI element. Set the text of the header UI element to Student. a) 2. Right click on the Group in the Outline and choose Insert Child... selecting a ViewContainerUIElement. Right click again on the Group and choose Insert ToolBar. a) 3. Perform as seen in the demonstration of your trainer. Right click on the ToolBar and choose Insert ToolBarItem. Select a ToolBarButton and give it the id InputButton. Set the property onAction by selecting the action Input from the drop down list. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step creating a ToolBarButton with id OutputButton firing the action Output. a) Perform as seen in the demonstration of your trainer. Task 2: Refactor the navigation of StudentWindow by moving the MainView directly on the navigation pane of the window and the InputView and OutputView inside the ViewContainerUIElement of MainView. 1. Go to the navigation of StudentWindow and drag & drop the MainView directly on the navigation pane. Set its property default to true. a) 2. Perform as seen in the demonstration of your trainer. Drag & drop the InputView and OutputView inside the ViewContainerUIElement of the MainView. Set the property default of the InputView to true. Delete the GridLayout from the navigation. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 73
    • Unit 3: Web Dynpro Navigation JA450 Task 3: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) 74 Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: View Container Lesson Summary You should now be able to: • handle view containers in the layout and navigation. • explain the term re-entrant navigation link. 2008 © 2008 SAP AG. All rights reserved. 75
    • Unit Summary JA450 Unit Summary You should now be able to: • embed views in windows. • define navigation plugs in the navigation modeler. • connect plugs via navigation links. • insert UI elements in the layout. • explain the combination of actions and navigation. • define viewsets in the navigation. • create a complex navigation system. • explain the term view assembly. • handle view containers in the layout and navigation. • explain the term re-entrant navigation link. 76 © 2008 SAP AG. All rights reserved. 2008
    • Unit 4 Web Dynpro Context Usage Unit Overview This chapter talks in the first lesson about defining the data structure in Web Dynpro known as the context. The second one shows in detail how to connect the UI to the context. The last lessen then connects the context with the Java dictionary using simple types and structures. Each lessen has its own exercise. Unit Objectives After completing this unit, you will be able to: • • • • • • • • • create context nodes and attributes. explain how data is stored in the context. structure the UI by using UI container. use layout managers to position UI element on the screen. use data binding and context mapping for cross-view UI manipulation. use image sources offered by Web Dynpro. use simple types available in Web Dynpro. create new simple types in the local dictionary. define structures and apply structure binding. Unit Contents Lesson: Context Definition...................................................... 78 Exercise 6: Context Mapping and Data Binding......................... 91 Lesson: UI Manipulation ........................................................ 96 Exercise 7: UI Manipulation via Data Binding ..........................101 Lesson: Java Dictionary .......................................................108 Exercise 8: Java Dictionary and Structure Binding .................... 117 2008 © 2008 SAP AG. All rights reserved. 77
    • Unit 4: Web Dynpro Context Usage JA450 Lesson: Context Definition Lesson Overview This lesson introduces the context as central part of data management in Web Dynpro. Context nodes and attributes and their binding and mapping to UI elements and other contexts are introduced as well as UI containers and layout manager for structuring the UI. Lesson Objectives After completing this lesson, you will be able to: • • • • create context nodes and attributes. explain how data is stored in the context. structure the UI by using UI container. use layout managers to position UI element on the screen. Business Example You want store and transport data entered by the user in your application. The UI should be structured in a user-friendly format. Context Structure Every Web Dynpro controller has a hierarchical data storage structure known as context. The data held in the context exists only for the lifespan of the controller. Once the controller instance has been terminated, all data held within its context is lost. The structure of a context will typically be defined at design time. However it is perfectly possible not only to modify the contents of the context but also to modify its structure. 78 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Figure 34: Declaring Context Structure All controller contexts are constructed from a hierarchical arrangement of entities known as nodes and attributes. A context always has a parent node known as the root node. The root node is created automatically when the controller is initialized and always has the same properties. Note: The context root node may not be deleted or modified in any way. 2008 © 2008 SAP AG. All rights reserved. 79
    • Unit 4: Web Dynpro Context Usage JA450 Figure 35: Creating Nodes and Attributes A context node is the main abstraction class used for runtime data storage within the Web Dynpro Framework (WDF). Context nodes are arranged hierarchically and are permitted to have children. The node may have attributes or other nodes as children. All the child entities of a node are aggregated into a unit known as element. A node is a collection of such elements in the same way that a table is a collection of rows. All nodes contain an element collection even if the maximum number of elements within the collection is limited to one. An attribute is a hierarchical entity within the context that is not permitted to have children. A context attribute can not exist without being child of some parent node – be it the context root node or some other node. The context attribute is an attribute of the element objects in a context node. Speaking of a node being a collection of rows, an attribute defines the name and data type of a column. You should always have the properties view open when editing the context because there are certain properties that will critically affect the behavior of the context at runtime. If these properties are incorrectly set, then at runtime you can arrive at the false impression that data is missing from the context. 80 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Figure 36: Cardinality Values One of these properties is the collection cardinality. This property is composed of two values that taken together, describe the maximum and minimum number of elements the node collection may hold at runtime. The first value is called mandatory which sets the minimum number of elements that have to be in the node at any time to 0 or 1. The second value is called multiple which defines if the node is allowed to have multiple elements (n) or just 1. So there are four possible cardinality values specified as “min..max”: 0..1 No more than one element is allowed. 0..n Any number of elements are possible. 1..1 Exactly one default element is available. 1..n At least one default element exists. UI Manipulation Unless declared to be otherwise, all runtime data within a controller’s context is private to that controller. 2008 © 2008 SAP AG. All rights reserved. 81
    • Unit 4: Web Dynpro Context Usage JA450 Information held in the context of the component controller or a custom controller can be made accessible to the context of other controller by a technique known as context mapping. Using this technique, two or more controllers can access the same runtime data. This is the primary mechanism for sharing data between controllers within a single component. Note: It is not permitted for view or window controller to share its context data. They can only consume data of other controllers. Figure 37: Context Mapping Context mapping allows a context node in one controller to be supplied automatically with data from a corresponding node in another controller. The context node that acts as the data source is known as the mapping origin. The context node that is mapped is known as the mapped node. A mapped node does not store any data but a reference to the mapping origin. So the data is only stored in one place and shared with any number of mapped nodes. The developer can work with a mapped node or mapped attribute as if the data is stored directly in the node or attribute. The Web Dynpro Framework (WDF) handles the request using the context mapping defined at design time. Caution: A mapped node ceases to maintain its own element collection. Instead it references the element collection of the mapping origin node. 82 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Figure 38: Data Modeler In order for a mapping relationship to be established, the following steps must first be performed: • • • A node must exist in the context of controller acting as mapping origin. The mapping origin controller must be the component or a custom controller. The controller containing the mapped node must declare the use of the mapping origin controller as a required controller. The data modeler is a Web Dynpro specific graphical tool for modelling component, controller and model usage within a component. Data links can be created that define a context mapping relationship between two controllers. 2008 © 2008 SAP AG. All rights reserved. 83
    • Unit 4: Web Dynpro Context Usage JA450 Figure 39: Mapping Wizard When creating a mapping relationship between a view controller and the component controller, the Context Mapping Wizard performs several configuration steps for you: • • • It adds the component controller to the view controller’s list of required controllers. Without this step there would be no possibility of communication between the controllers. It creates the nodes and attributes in the view controller’s context using the metadata of the corresponding node in the component controller. This process, in itself, does nothing more than create a cloned context structure in the view controller. It creates the mapping relationship between the nodes and attributes in the view controller and the component controller. Now the node in the view controller acts simply as a reference to the data found in the component controller’s context. These steps can all be performed manually through the controller editor, too. Data can be mapped selectively, thus reducing the amount of data in a controller’s context to the minimal set required to fulfil a task. 84 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Figure 40: Data Binding As for the mapping between contexts there exists a functionality to map data entered in a UI element to an attribute of a context node. Data binding is the means by which data is automatically transported from a view controller’s context to a UI element in the layout. The data binding process decouples the UI element object from the application code within the view controller. Therefore in order to manipulate UI element properties, the application code in the view controller need only to manipulate the values of context nodes and attributes to which the UI elements are bound. The WDF then manages the following two tasks: • • 2008 The transport of data from the context to the UI element during the screen rendering process Repopulating the context from the UI element after data is entered by the user © 2008 SAP AG. All rights reserved. 85
    • Unit 4: Web Dynpro Context Usage JA450 Figure 41: UI Element Properties The mapping can be done manually by editing the UI element property or it can be generated by templates. You may not bind UI elements to context nodes or attributes that occur in some other controller. UI elements are private to the view controller within which they are declared. Context mapping and data binding combined makes it possible to store the application data in one place but making it possible to access the data in different controllers and UIs without implementing any Java code. The WDF manages context mapping and data binding in that way that the data entered in UI elements will be already available when custom coding accesses the business data. UI Structuring Any UI element that is defined on the abstract base class IWDUIElementContainer will be able to hold other UI elements. These UI elements are known as container UI elements. The structure in the outline of a view consists therefore of container UI elements as nodes of the UI tree and of any child UI elements which may be again container UI elements. 86 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Figure 42: UI Container The root UI element is also a container UI element or to be precise, a TransparentContainer. TransparentContainers have the purpose to structure its child UI elements but the container itself is invisible. All other containers are visible and all have the purpose to structure their children and offer some special feature e.g. a heading. Container UI elements require the definition of layout manager in order to arrange their child UI elements. Once defined, all children within that container inherit a set of layout data properties. 2008 © 2008 SAP AG. All rights reserved. 87
    • Unit 4: Web Dynpro Context Usage JA450 Figure 43: Layout Manager The default layout manager is FlowLayout for all container UI elements. You have no direct control over the position of UI elements managed by FlowLayout. The UI elements will be positioned from left to right across the screen and will automatically wrap to the next line when the right-hand screen margin is encountered. This layout manager is most useful when managing other container UI elements. The RowLayout handles UI elements in the same way as FlowLayout except that you can specify a certain UI element to appear at the start of a new row by setting the layoutData property of the UI element to RowHeadData. So you can say the RowLayout allows UI elements to be arranged into specific rows. The disadvantages using RowLayout for an input mask is the dependency to the width of the screen and that there is no vertical alignment for UI elements. If you wish to define which UI elements appear at the start of a new line and have a vertical alignment, use the layout manager MatrixLayout. Caution: Changing the layout manager will delete all layout settings made in the container UI element and its children. 88 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Figure 44: Column Oriented Layouts Setting the layoutData property to MatrixHeadData forces the UI element to start a new row. All UI elements are aligned vertically which means the widest UI element in its virtual column defines the width of the column. The UI elements in the next virtual column are arranged left-justified to this invisible line. This grid defines itself by the number of UI elements in a row, the width of the widest UI element and which UI elements start a new row. Another difference to former layout manager is, if the screen is not wide enough to accommodate all the UI elements in a particular row, a scroll bar appears. The UI elements do not flow around to start a new row. This properties makes the MatrixLayout the far mostly used layout manager in Web Dynpro for input masks. Another column oriented layout is GridLayout. It causes UI elements to be arranged into a grid in which there are always an equal number of columns per row. The number of columns is controlled by the colCount property of the container UI element. The child UI elements are added in a left-to-right, top-to-bottom manner. UI elements arranged using the GridLayout can be tightly packed together when setting the cellSpacing property to zero. This acts the same as with HTML tables including the property cellPadding of the GridLayout. Hint: If you wish one of the grid cells to be empty, use a UI element of type InvisbleElement. 2008 © 2008 SAP AG. All rights reserved. 89
    • Unit 4: Web Dynpro Context Usage 90 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Context Definition Exercise 6: Context Mapping and Data Binding Exercise Objectives After completing this exercise, you will be able to: • create nodes and attributes in the context. • map nodes and attributes between controllers. • use wizards to bind UI elements to the context. Business Example You want to enter a first name and last name of a student in one view. The entered names should be shown on a second view as read only. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context1XX with XX as your group number. Template training.sap.com~navigation3 Solution training.sap.com~context1 Task 1: Create the context node Student with Collection Cardinality of 1..1 in the component controller. Add the two context attributes FirstName and LastName both of type string to the node Student. 1. Go to the context of the component controller and right click on the context root node. Select New -> Node... choosing manually and give it the name Student. Set its property Collection Cardinality to 1..1. 2. Right click on the new node Student and select New -> Attribute.... Choose manually, give it the name FirstName and set the type to string. 3. Repeat the last step creating the context attribute LastName of type string int the context node Student. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 91
    • Unit 4: Web Dynpro Context Usage JA450 Task 2: Map the node Student of the component controller via Context Mapping to the InputView and OutputView. 1. Go to the Data Modeler of your component and select Create Data Link from the menu on the right. Draw a line from the InputView to the component controller. 2. Drag & drop in the Context Mapping pop-up the context node Student of the component controller from the right onto the context root node of the InputView on the left. Select both attributes and finish. 3. Repeat the steps mapping the context node Student of the component controller to the OutputView. Task 3: Create in the InputView and OutputView for each of the context attributes FirstName and LastName a Label UI element and an InputField. Bind the InputFields via Data Binding to the respective attributes. Use the MatrixLayout to format the UI. The InputFields of the OutputView are set to read-only 1. Go to the layout of the InputView and right click in the Outline on the RootNode. Choose Apply Template selecting Form. In the next step select both attributes FirstName and LastName of node Student and finish. 2. Change the property text of the label for FirstName to First Name and of the label for LastName to Last Name. 3. Change the property layout of the RootElement to MatrixLayout. Set its layout property stretchHorizontally to false. 4. Repeat the steps for the OutputView and in addition set the property readOnly for both InputFields to true. Task 4: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. Hint: If your InputFields are deactivated and not ready for input, you probably forgot to set the Collection Cardinality in the first task. 92 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Solution 6: Context Mapping and Data Binding Task 1: Create the context node Student with Collection Cardinality of 1..1 in the component controller. Add the two context attributes FirstName and LastName both of type string to the node Student. 1. Go to the context of the component controller and right click on the context root node. Select New -> Node... choosing manually and give it the name Student. Set its property Collection Cardinality to 1..1. a) 2. Right click on the new node Student and select New -> Attribute.... Choose manually, give it the name FirstName and set the type to string. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step creating the context attribute LastName of type string int the context node Student. a) Perform as seen in the demonstration of your trainer. Task 2: Map the node Student of the component controller via Context Mapping to the InputView and OutputView. 1. Go to the Data Modeler of your component and select Create Data Link from the menu on the right. Draw a line from the InputView to the component controller. a) 2. Drag & drop in the Context Mapping pop-up the context node Student of the component controller from the right onto the context root node of the InputView on the left. Select both attributes and finish. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the steps mapping the context node Student of the component controller to the OutputView. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 93
    • Unit 4: Web Dynpro Context Usage JA450 Task 3: Create in the InputView and OutputView for each of the context attributes FirstName and LastName a Label UI element and an InputField. Bind the InputFields via Data Binding to the respective attributes. Use the MatrixLayout to format the UI. The InputFields of the OutputView are set to read-only 1. Go to the layout of the InputView and right click in the Outline on the RootNode. Choose Apply Template selecting Form. In the next step select both attributes FirstName and LastName of node Student and finish. a) 2. Change the property text of the label for FirstName to First Name and of the label for LastName to Last Name. a) 3. Perform as seen in the demonstration of your trainer. Change the property layout of the RootElement to MatrixLayout. Set its layout property stretchHorizontally to false. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the steps for the OutputView and in addition set the property readOnly for both InputFields to true. a) Perform as seen in the demonstration of your trainer. Task 4: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. Hint: If your InputFields are deactivated and not ready for input, you probably forgot to set the Collection Cardinality in the first task. a) 94 Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Definition Lesson Summary You • • • • 2008 should now be able to: create context nodes and attributes. explain how data is stored in the context. structure the UI by using UI container. use layout managers to position UI element on the screen. © 2008 SAP AG. All rights reserved. 95
    • Unit 4: Web Dynpro Context Usage JA450 Lesson: UI Manipulation Lesson Overview This lesson demonstrates the technique for changing UI properties without accessing each individual UI element and the image sources used in Web Dynpro. Lesson Objectives After completing this lesson, you will be able to: • • use data binding and context mapping for cross-view UI manipulation. use image sources offered by Web Dynpro. Business Example You want manipulate the UI in its behavior and optic. These manipulations should be possible by user interaction. Data Binding The value of a UI element can either be hard-coded or bound to a context attribute of a suitable data type. Once a UI element property is bound to a context node or attribute, the context data is used to supply a value to the UI element. If the UI element property is one that the user can update, then the context is automatically updated with the new value during the next server roundtrip. 96 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: UI Manipulation Figure 45: Binding UI Element Properties Web Dynpro stands in direct contrast to other web frameworks because the data to be displayed is not stored in the UI element object itself. Instead the data to be displayed lives in the context and is simply visualized through the UI element. Therefore if you want to find the value entered by the user into a Web Dynpro UI element, you simply need to access the context to which the UI element has been bound. The actual UI element used to visualize Web Dynpro data is not important. Data binding combined with context mapping makes it possible to change a property of an arbitrary number of UI elements by changing only one context attribute. This context attribute even need not be changed programmatically, if the value is somewhere bound to a UI element allowing the user to change the value. Data binding and context mapping are exchanging data in both directions. 2008 © 2008 SAP AG. All rights reserved. 97
    • Unit 4: Web Dynpro Context Usage JA450 Figure 46: Controlling UI Element Properties Any property over which you wish to have programmatic control should be bound to an appropriate context node or attribute. With very few exceptions (e.g. id and layoutData), all UI element properties can be bound to a context node or attribute. Some UI elements can show images on the UI. Such an image can also be changed by binding the property to the context and entering a new value in the context attribute. Web Dynpro offers three sources for an image: • • • 98 Component image Web icon SAP icon © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: UI Manipulation Figure 47: Image Sources A component image is a file in the mimes source part of the Web Dynpro DC. The commonly known image formats are supported e.g. JPG of BMP. Web icons and SAP icons are shipped together with Web Dynpro and are available on every NetWeaver server. Especially the SAP icons, known from the ABAP system, are highly recognizable in the SAP world. 2008 © 2008 SAP AG. All rights reserved. 99
    • Unit 4: Web Dynpro Context Usage 100 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: UI Manipulation Exercise 7: UI Manipulation via Data Binding Exercise Objectives After completing this exercise, you will be able to: • change existing Context Mappings. • create and bind actions to UI elements. • change UI element properties via the context. Business Example You want to offer the user a button to switch all input UI elements on all views between read-only and writable. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context2XX with XX as your group number. Template training.sap.com~context1 Solution training.sap.com~context2 Task 1: Create the context node UIProperty with Collection Cardinality of 1..1 in the component controller. Add the context attribute ReadOnly of type boolean to the node UIProperty. 1. Go to the context of the component controller and right click on the context root node. Select New -> Node... choosing manually and give it the name UIProperty. Set its property Collection Cardinality to 1..1. 2. Right click on the new node UIProperty and select New -> Attribute.... Choose manually, give it the name ReadOnly and set the type to boolean. Task 2: Map the node UIProperty of the component controller via Context Mapping to the MainView, InputView and OutputView. 1. Go to the Data Modeler of your component and select Create Data Link from the menu on the right. Draw a line from the MainView to the component controller. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 101
    • Unit 4: Web Dynpro Context Usage JA450 2. Drag & drop in the Context Mapping pop-up the context node UIProperty of the component controller from the right onto the context root node of the MainView on the left. Select the attribute ReadOnly and finish. 3. Double click on the Data Link between InputView and component controller. Drag & drop the context node UIProperty of the component controller from the right onto the context root node of the MainView on the left. Select the attribute ReadOnly and finish. 4. Repeat the last step mapping the context node UIProperty of the component controller to the OutputView. Task 3: Create inside the MainView a new ToggleButton with the id ToggleButton in the ToolBar of the Group right-justified firing the new action Toggle. Bind the property checked to the context attribute ReadOnly and set for the properties imageSource and checkedImageSource with the SAP Icon s_b_dpch.gif. 1. Go to the layout of the MainView and right click in the Outline on the ToolBar of the Group. Choose Insert ToolBarRightItem... and select a ToolBarToggleButton. Set its id to ToggleButton. 2. Click in the property checked of the ToggleButton on Bind. Select the context attribute ReadOnly in the following pop-up. 3. Click in the property onAction of the ToggleButton on Create and set the name of the action to Toggle. 4. Set the property imageSource of the ToggleButton by following Browse -> SAP Icon... and choose the picture s_b_dpch.gif. 5. Repeat the last step setting the property checkedImageSource to the same picture. Task 4: Bind the property readOnly of all InputFields inside the InputView and OutputView to the context attribute ReadOnly. 1. Select all InputFields in the Outline of the InputView and click in the property checked on Bind. Select the context attribute ReadOnly in the following pop-up. 2. Repeat the step for the InputFields in the OutputView. Continued on next page 102 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: UI Manipulation Task 5: Deploy new archive and run your application StudentApp. 1. 2008 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 103
    • Unit 4: Web Dynpro Context Usage JA450 Solution 7: UI Manipulation via Data Binding Task 1: Create the context node UIProperty with Collection Cardinality of 1..1 in the component controller. Add the context attribute ReadOnly of type boolean to the node UIProperty. 1. Go to the context of the component controller and right click on the context root node. Select New -> Node... choosing manually and give it the name UIProperty. Set its property Collection Cardinality to 1..1. a) 2. Perform as seen in the demonstration of your trainer. Right click on the new node UIProperty and select New -> Attribute.... Choose manually, give it the name ReadOnly and set the type to boolean. a) Perform as seen in the demonstration of your trainer. Task 2: Map the node UIProperty of the component controller via Context Mapping to the MainView, InputView and OutputView. 1. Go to the Data Modeler of your component and select Create Data Link from the menu on the right. Draw a line from the MainView to the component controller. a) 2. Drag & drop in the Context Mapping pop-up the context node UIProperty of the component controller from the right onto the context root node of the MainView on the left. Select the attribute ReadOnly and finish. a) 3. Perform as seen in the demonstration of your trainer. Double click on the Data Link between InputView and component controller. Drag & drop the context node UIProperty of the component controller from the right onto the context root node of the MainView on the left. Select the attribute ReadOnly and finish. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step mapping the context node UIProperty of the component controller to the OutputView. a) Perform as seen in the demonstration of your trainer. Continued on next page 104 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: UI Manipulation Task 3: Create inside the MainView a new ToggleButton with the id ToggleButton in the ToolBar of the Group right-justified firing the new action Toggle. Bind the property checked to the context attribute ReadOnly and set for the properties imageSource and checkedImageSource with the SAP Icon s_b_dpch.gif. 1. Go to the layout of the MainView and right click in the Outline on the ToolBar of the Group. Choose Insert ToolBarRightItem... and select a ToolBarToggleButton. Set its id to ToggleButton. a) 2. Click in the property checked of the ToggleButton on Bind. Select the context attribute ReadOnly in the following pop-up. a) 3. Perform as seen in the demonstration of your trainer. Set the property imageSource of the ToggleButton by following Browse -> SAP Icon... and choose the picture s_b_dpch.gif. a) 5. Perform as seen in the demonstration of your trainer. Click in the property onAction of the ToggleButton on Create and set the name of the action to Toggle. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step setting the property checkedImageSource to the same picture. a) Perform as seen in the demonstration of your trainer. Task 4: Bind the property readOnly of all InputFields inside the InputView and OutputView to the context attribute ReadOnly. 1. Select all InputFields in the Outline of the InputView and click in the property checked on Bind. Select the context attribute ReadOnly in the following pop-up. a) 2. Perform as seen in the demonstration of your trainer. Repeat the step for the InputFields in the OutputView. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 105
    • Unit 4: Web Dynpro Context Usage JA450 Task 5: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) 106 Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: UI Manipulation Lesson Summary You should now be able to: • use data binding and context mapping for cross-view UI manipulation. • use image sources offered by Web Dynpro. 2008 © 2008 SAP AG. All rights reserved. 107
    • Unit 4: Web Dynpro Context Usage JA450 Lesson: Java Dictionary Lesson Overview This lesson focus on the types used to define context nodes and attributes. These simple types and structures can be defined manually in the local dictionary or you can use the ones provided by Web Dynpro. Lesson Objectives After completing this lesson, you will be able to: • • • use simple types available in Web Dynpro. create new simple types in the local dictionary. define structures and apply structure binding. Business Example You want to use the local dictionary to define your context structure and text objects used on the screen. Standard Types When defining a context attribute you can choose from several types in the drop-down-box of the property. The names of these types are all well-known to a Java developer but they are not the original types of the Java standard. They are all simple types specially designed for Web Dynpro. 108 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Java Dictionary Figure 48: Built-in Simple Types All of these so-called built-in simple types are fully compatible to their Java pendants but offer in addition the possibility for data binding in Web Dynpro and other UI mechanics. Caution: The Java pendant for the built-in simple type date is java.sql.Date. Do not mix it up with java.util.Date. The built-in simple types cover many types of UI properties but not all. For example the visibility of a UI element consists of three states and can therefore not be bound to a context attribute of type Boolean. 2008 © 2008 SAP AG. All rights reserved. 109
    • Unit 4: Web Dynpro Context Usage JA450 Figure 49: Predefined Simple Types Every Web Dynpro application has access to predefined simple types defining special properties of UI elements. Only context attributes having one of these types can be bound to the special properties of UI elements. Beside built-in and predefined simple types also core data types based on the CCTS (Core Component Technical Specification) standard and Java native types can be used as type for a context attribute. Unfortunately both can not be used to bind the attribute to a UI element property. There purpose lies in the coding part of Web Dynpro when calculating or working with values from external sources. 110 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Java Dictionary Figure 50: Core Data and Java Native Types All together there are four possibilities for setting the type of a context attribute: • • • • Built-in simple types Predefined simple types Core data types Java native types Dictionary Types Every Web Dynpro DC project has the possibility to define its own local dictionary. In this dictionary simple types and structures can be defined by the developer to be used in the Web Dynpro context. 2008 © 2008 SAP AG. All rights reserved. 111
    • Unit 4: Web Dynpro Context Usage JA450 Figure 51: Dictionary Simple Type Definition You can define a new simple type based on a built-in type or derive it from another simple type. Type derivation means that the simple type inherits the properties of the base type (same as inheritance in classes). Depending from the type selected, you can add additional metadata to your type like maximum and minimum length for Strings. UI elements will adopt these settings. An input field bound to an attribute using a simple type with a maximum length of 30, will be generated to offer exactly 30 spaces for input. The constraints available for a simple type depend on the built-in type. 112 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Java Dictionary Figure 52: Dictionary Simple Type Representation Simple types do not offer only technical information but also semantical one. The representation tab can be used to enter text objects used by the appropriate UI element in the layout: • • • Field label Column label Quick info If the appropriate property of the UI element is reset, the WDF will load the text object from the used simple type if available. 2008 © 2008 SAP AG. All rights reserved. 113
    • Unit 4: Web Dynpro Context Usage JA450 Figure 53: Dictionary Structure The structures define a record-like data type consisting of fields. A field can be defined by a simple types or built-in simple types. A structure can not change the simple type because it only references it. Structures and simple types should be created in different packages for a better overview. 114 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Java Dictionary Figure 54: Structure Binding Simple types combined in a structure can be used to apply structure binding for a context node and its attributes. By binding a context node to a dictionary structure, all attributes must fit to the fields defined in the structure. Therefore the types of the attributes can not be changed unless the structure binding is deleted. Also renaming the attributes is not allowed but the name is not case-sensitive. You can create a context node using a structure as template and binding the node to the structure. All attributes will be generated having the names and types defined as fields in the structure. Also context mapping will make use of the metadata defined in a structure. Hint: Fields in a structure are always written in capital letters. Context attributes generated using structure binding will also be written in capital letters. You should rename the attributes in the Java format because the methods of the typed context API inherit the names as they are written in the context. 2008 © 2008 SAP AG. All rights reserved. 115
    • Unit 4: Web Dynpro Context Usage 116 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Java Dictionary Exercise 8: Java Dictionary and Structure Binding Exercise Objectives After completing this exercise, you will be able to: • create simple types and structures in the Java dictionary. • bind a context node to a dictionary structure. • set and bind properties of complex UI elements. Business Example You want to structure the data of your application by using simple types and structures of the Java dictionary. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context3XX with XX as your group number. Template training.sap.com~context2 Solution training.sap.com~context3 Task 1: Create in the package com.sap.training.groupXX.simpleytpes the simple types FirstName and LastName of type string with the maximum length of 30. Additionally create the simple types BeginDate and EndDate of type date. Maintain the text objects for each simple type appropriately to their names. 1. Right click in the Web Dynpro Explorer on Dictionaries -> Local Dictionary -> Data Types -> Simple Types of your DC and choose Create Simple Type. Enter the simple type name FirstName and the package com.sap.training.groupXX.simpletypes. 2. In the simple type definition of FirstName set the Description to First Name of Student and the Maximum Length to 30. 3. In the simple type representation of FirstName set the Field Label and Column Label to First Name and the Quick Info to First Name of Student. 4. Repeat the steps for LastName accordingly. 5. For BeginDate and EndDate repeat the first and third step accordingly but change the Built-In Type in the second step to date and do not set a Maximum Length. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 117
    • Unit 4: Web Dynpro Context Usage JA450 Task 2: Create in the package com.sap.training.groupXX.structures the structure Student consisting of FIRSTNAME, LASTNAME, BEGINDATE and ENDDATE using the corresponding simple types created before. 1. Right click in the Web Dynpro Explorer on Dictionaries -> Local Dictionary -> Data Types -> Structures of your DC and choose Create Structure. Enter the structure name Student and the package com.sap.training.groupXX.structures. 2. In the first row of the structure enter the Element Name FIRSTNAME and select the simple type FirstName in the package com.sap.training.groupXX.simpletypes as Simple Type. 3. Repeat the last step for LASTNAME, BEGINDATE and ENDDATE accordingly. Task 3: Bind the node Student in the context of the component controller to the structure Student in the dictionary adding the attributes BeginDate and EndDate to the context node. Map both attributes to the Student nodes of InputView and OutputView. 1. Right click on the context node Student in the component controller and Edit Structure Binding.... Choose the structure Student in the package com.sap.training.groupXX.structures, select all attributes and finish. 2. Right click on the context attribute BEGINDATE and Rename... it to BeginDate. Right click on the context attribute ENDDATE and Rename... it to EndDate. 3. Right click on the context node Student in the InputView and Edit Context Mapping.... Select all attributes and finish. 4. Repeat the last step for the context node Student in the OutputView. Task 4: Create in the InputView for each of the context attributes BeginDate and EndDate a Label UI element and an InputField. Bind the InputFields via Data Binding to the respective attributes. 1. 2. 118 Right click on the transparent container in the Outline of the InputView and Apply Template choosing Form. Select the context attributes BeginDate and EndDate and finish. Bind the property readOnly of the new InputFields to the context attribute ReadOnly. Continued on next page © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Java Dictionary 3. Delete the property text of the labels for FirstName and LastName and click on Reset for the property. 4. Change the property vAlign of the LayoutData of the Image to top. Task 5: Create in the OutputView a DateNavigator separated from the former UI elements by a HorizontalGutter. Bind the properties of the DateNavigator firstSelectedDate and startsWith to the context attribute BeginDate and the property lastSelectedDate to EndDate. Set the selectionMode to range showing 2 months per row. 1. Right click on the RootElement in the Outline of the OutputView and Insert Child... choosing a HorizontalGutter. Set the properties layoutData to MatrixHeadData and colSpan to 2. 2. Repeat the complete step adding a DateNavigator to the layout of OutputView. In addition set the properties selectionMode to range and monthsPerRow to 2. 3. Click in the properties firstSelectedDate and startsWith on Bind and select the context attribute BeginDate. Click in the property lastSelectedDate on Bind and select the context attribute EndDate. 4. Delete the property text of the labels for FirstName and LastName and click on Reset for the property. Task 6: Deploy new archive and run your application StudentApp. 1. 2008 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 119
    • Unit 4: Web Dynpro Context Usage JA450 Solution 8: Java Dictionary and Structure Binding Task 1: Create in the package com.sap.training.groupXX.simpleytpes the simple types FirstName and LastName of type string with the maximum length of 30. Additionally create the simple types BeginDate and EndDate of type date. Maintain the text objects for each simple type appropriately to their names. 1. Right click in the Web Dynpro Explorer on Dictionaries -> Local Dictionary -> Data Types -> Simple Types of your DC and choose Create Simple Type. Enter the simple type name FirstName and the package com.sap.training.groupXX.simpletypes. a) 2. In the simple type definition of FirstName set the Description to First Name of Student and the Maximum Length to 30. a) 3. Perform as seen in the demonstration of your trainer. Repeat the steps for LastName accordingly. a) 5. Perform as seen in the demonstration of your trainer. In the simple type representation of FirstName set the Field Label and Column Label to First Name and the Quick Info to First Name of Student. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. For BeginDate and EndDate repeat the first and third step accordingly but change the Built-In Type in the second step to date and do not set a Maximum Length. a) Perform as seen in the demonstration of your trainer. Task 2: Create in the package com.sap.training.groupXX.structures the structure Student consisting of FIRSTNAME, LASTNAME, BEGINDATE and ENDDATE using the corresponding simple types created before. 1. Right click in the Web Dynpro Explorer on Dictionaries -> Local Dictionary -> Data Types -> Structures of your DC and choose Create Structure. Enter the structure name Student and the package com.sap.training.groupXX.structures. a) Perform as seen in the demonstration of your trainer. Continued on next page 120 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Java Dictionary 2. In the first row of the structure enter the Element Name FIRSTNAME and select the simple type FirstName in the package com.sap.training.groupXX.simpletypes as Simple Type. a) 3. Perform as seen in the demonstration of your trainer. Repeat the last step for LASTNAME, BEGINDATE and ENDDATE accordingly. a) Perform as seen in the demonstration of your trainer. Task 3: Bind the node Student in the context of the component controller to the structure Student in the dictionary adding the attributes BeginDate and EndDate to the context node. Map both attributes to the Student nodes of InputView and OutputView. 1. Right click on the context node Student in the component controller and Edit Structure Binding.... Choose the structure Student in the package com.sap.training.groupXX.structures, select all attributes and finish. a) 2. Right click on the context attribute BEGINDATE and Rename... it to BeginDate. Right click on the context attribute ENDDATE and Rename... it to EndDate. a) 3. Perform as seen in the demonstration of your trainer. Right click on the context node Student in the InputView and Edit Context Mapping.... Select all attributes and finish. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step for the context node Student in the OutputView. a) Perform as seen in the demonstration of your trainer. Task 4: Create in the InputView for each of the context attributes BeginDate and EndDate a Label UI element and an InputField. Bind the InputFields via Data Binding to the respective attributes. 1. Right click on the transparent container in the Outline of the InputView and Apply Template choosing Form. Select the context attributes BeginDate and EndDate and finish. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 121
    • Unit 4: Web Dynpro Context Usage 2. Bind the property readOnly of the new InputFields to the context attribute ReadOnly. a) 3. Perform as seen in the demonstration of your trainer. Delete the property text of the labels for FirstName and LastName and click on Reset for the property. a) 4. JA450 Perform as seen in the demonstration of your trainer. Change the property vAlign of the LayoutData of the Image to top. a) Perform as seen in the demonstration of your trainer. Task 5: Create in the OutputView a DateNavigator separated from the former UI elements by a HorizontalGutter. Bind the properties of the DateNavigator firstSelectedDate and startsWith to the context attribute BeginDate and the property lastSelectedDate to EndDate. Set the selectionMode to range showing 2 months per row. 1. Right click on the RootElement in the Outline of the OutputView and Insert Child... choosing a HorizontalGutter. Set the properties layoutData to MatrixHeadData and colSpan to 2. a) 2. Repeat the complete step adding a DateNavigator to the layout of OutputView. In addition set the properties selectionMode to range and monthsPerRow to 2. a) 3. Perform as seen in the demonstration of your trainer. Click in the properties firstSelectedDate and startsWith on Bind and select the context attribute BeginDate. Click in the property lastSelectedDate on Bind and select the context attribute EndDate. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Delete the property text of the labels for FirstName and LastName and click on Reset for the property. a) Perform as seen in the demonstration of your trainer. Task 6: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) 122 Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Java Dictionary Lesson Summary You • • • 2008 should now be able to: use simple types available in Web Dynpro. create new simple types in the local dictionary. define structures and apply structure binding. © 2008 SAP AG. All rights reserved. 123
    • Unit Summary JA450 Unit Summary You should now be able to: • create context nodes and attributes. • explain how data is stored in the context. • structure the UI by using UI container. • use layout managers to position UI element on the screen. • use data binding and context mapping for cross-view UI manipulation. • use image sources offered by Web Dynpro. • use simple types available in Web Dynpro. • create new simple types in the local dictionary. • define structures and apply structure binding. 124 © 2008 SAP AG. All rights reserved. 2008
    • Unit 5 Web Dynpro Context Manipulation Unit Overview This chapter shows the advanced options for the context starting with accessing the data at runtime followed by maintaining table-like data, calculating context attributes and designing complex context structures. It offers five exercises. Unit Objectives After completing this unit, you will be able to: • • • • • • • • • • • • • • • use shortcut variables for accessing different parts of Web Dynpro. choose the correct place for your coding in the controller implementation. describe the steps of server round trip. access the elements in the context. use the benefits of the collection cardinality. copy elements between nodes by using the WDCopyService. create and bind a Table UI element to the context. handle the selection cardinality of context nodes. delete elements from a context node. interoperate between controllers. implement calculated attributes. decide if a setter-method is possible. explain the properties of the node categories. understand the purpose of singleton nodes. implement supply functions. Unit Contents Lesson: Context Access .......................................................127 Exercise 9: Context Manipulation via Coding...........................141 Lesson: Multiple Context Elements...........................................150 Exercise 10: Table UI Element............................................159 Lesson: Selecting Context Elements.........................................168 Exercise 11: Selection with Table UI Element ..........................175 2008 © 2008 SAP AG. All rights reserved. 125
    • Unit 5: Web Dynpro Context Manipulation JA450 Lesson: Calculated Attributes .................................................181 Exercise 12: Calculated Attribute ........................................187 Lesson: Dependent Nodes ....................................................192 Exercise 13: Dependent Context Nodes ................................199 126 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access Lesson: Context Access Lesson Overview This lesson introduces the features of implementing context manipulation by using shortcut variables in coding sections called during a server round trip. Lesson Objectives After completing this lesson, you will be able to: • • • • use shortcut variables for accessing different parts of Web Dynpro. choose the correct place for your coding in the controller implementation. describe the steps of server round trip. access the elements in the context. Business Example You want implement coding for accessing the context of your controllers. Programming The main part of components and controllers are completely generated by the Web Dynpro Framework (WDF). Using this generated coding to access for example the context is made easy by using shortcut variables defined within every Web Dynpro controller. The core shortcut variable is called wdThis. The value for wdThis is passed in the constructor of a controller by the WDF. Inside the constructor all other shortcut variables get their values deriving from the variable wdThis. It is not possible to change the constructor or the shortcut variables. 2008 © 2008 SAP AG. All rights reserved. 127
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 55: Shortcut Variables Including wdThis four shortcut variables exist: wdThis wdThis is the Web Dynpro specific self reference and should be used in preference to the standard Java self reference this. wdThis is not just a reference to the coding visible as the controller implementation but a reference to the controllers private interface representing the functionality of the generated class Internal<ControllerName>. So wdThis offers access to everything defined for a controller. wdContext wdContext is the reference to the controller’s context root node and thus to the entire context. It is possible not only to read or change the values in the context but also to create or delete new nodes and attributes or change existing ones. wdControllerAPI wdControllerAPI is the reference to the API of the current controller. The API offers several services for different parts of Web Dynpro for its controller. 128 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access wdComponentAPI wdComponentAPI is the reference to the API of the component controller. The component controller is considered hierarchically superior to all other controllers in the component and therefore offers central services for all controllers in the component. Note: If the variable wdComponentAPI is used from within the component controller itself, then the wdComponentAPI and wdControllerAPI point to the same object. The shortcut variables and other custom coding can not be used everywhere in the implementation of a controller. Everything which is generated by the WDF can only be changed by the Web Dynpro tools and is saved in a metadata format. Out of this metadata the implementation visible in the NWDS is generated. Changes to this coding are not saved back in the metadata except when using special coding blocks. Figure 56: Coding Sections There are many of these blocks inside a controller surrounded by comments like //@@begin…//@@end. You can distinguish following blocks: Imports The block for Java imports is fully integrated in the development environment so when using auto-completion the imports are correctly generated inside this block. 2008 © 2008 SAP AG. All rights reserved. 129
    • Unit 5: Web Dynpro Context Manipulation JA450 Documentation The controller and every user-defined method can be documented in the appropriate documentation block using JavaDoc. Method body Every user-defined method and the so called hook methods can be implemented between these tags. The signature of the methods can not be changed in the implementation because it is generated from the controller’s metadata. Others At the end of each controller this block makes it possible to implement independent Java code. Attributes, methods and whole classes can be created but with the restriction, that everything is only usable inside the current controller. This is because everything inside this block is not part of the controller interfaces which are used for accessing the controller from outside. Caution: When trying to implement any coding outside of these blocks, everything implemented will just disappear after the next saving because it is overwritten by what is generated out the controller’s metadata. Hook Methods Hook methods are one part of the Web Dynpro phase model. The phase model is the predetermined sequence of execution steps that are always performed every time a round trip is processed for a client device. There is a 1:1 relationship between a phase model loop and a visible window. The entire sequence of processing is performed in the same order for every round trip. Each step is performed no more than once and it is not possible to move backwards from a later step to an earlier one. Once the round trip has been completed, all phase model instances for handling the individual steps are discarded. 130 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access Figure 57: Phase Model The first step in the phase model is the receipt of the incoming request. If the application has never been run before, the component lifecycle will begin now. The lifecycle method wdDoInit() is run for every component controller referenced by the application where the lifecycle parameter is set to createOnDemand. Component initialization is not part of the phase model. The doApplicationStateChange step is called a floating phase model step because the point of time at which it is called varies depending on the type of request. A Web Dynpro application can be suspended when switching to another application. Therefore this step will be called at the beginning of the phase model if a resume request is received. If necessary, the application state can now be restored from the persistent store. If a suspend request has been made during a round trip, the step will be called at the end of the phase model enabling the developer to write the state of the application to a persistent store. After validating and transporting the data from the UI to the relevant contexts and after calling eventual system event handlers, the next for the developer to be able to implement is the wdDoBeforeAction. This step is called right before the application event handlers are processed so it is possible to change or stop the application right before. 2008 © 2008 SAP AG. All rights reserved. 131
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 58: Input Side of Phase Model The main application logic is performed by the action event handlers reacting on the user input on the UI. The context is modified, events are raised and plugs are fired. But when firing plugs, the navigation is not yet started. The queue of plugs to be fired will be processed right after the step wdDoBeforeNavigation. This is the last step of the input side of the phase model. Errors depending on the user input should be raised here to prevent navigation to change the screen so the user can correct his entries. All the steps after wdDoBeforeNaviagtion do belong to the output side of the phase model focusing on creating a UI. After the navigation and view initialization the developer has the possibility in the step wdDoModifiyView to change the UI dynamically. This is the only method where a direct access to the UI elements is possible. On the other side this is the only method where context manipulation is strictly forbidden. Also all other business logic should be performed elsewhere because this could result in errors terminating the whole application. The purpose of wdModifyView is purely for UI manipulation. Caution: Do not implement any business logic in the wdDoModifyView. 132 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access Figure 59: Output Side of Phase Model By the time when arriving at validating the UI tree, the new view assembly has been constructed. If the incoming request to the WDF came from an HTML based client, then in order to improve HTTP communication efficiency, only the data that will actually be displayed on the client is rendered. The doPostProcessing step is the very last point at which application code can be executed. If any type of serious or even fatal errors has occurred, this is the last point at which the user can be notified of such a problem. However, when a message is send to the user at this time in the phase model, then this invalidates the previously rendered UI tree and the new message is added to the screen by completely re-rendering it. Hint: It is recommended that only serious or fatal errors should be reported in this manner. Many steps of the phase model are implemented as hook methods in several controllers. At controller creation time these methods are empty and can be implemented by the developer. Irrespective of whether you choose to implement code, each hook method will be called at least once. The developer is not permitted to delete or rename any hook method. Changing will be lost when the coding is regenerated. All controllers have two lifecycle hook methods called only once during the lifecycle of the controller: 2008 © 2008 SAP AG. All rights reserved. 133
    • Unit 5: Web Dynpro Context Manipulation JA450 wdDoInit() The application developer has no access to the Java constructor of any Web Dynpro controller class. All initialization code should be implemented in the wdDoInit() since the method is called immediately after the controller has been instantiated. wdDoExit() This method is called at the end of a controller’s lifecycle and is used for holding the cleanup code of the controller. It acts like a destructor known from other programming languages. Figure 60: Hook Methods The component controller as central controller of the component has special hook methods managing the behavior of the component during a server round trip. All are part of the phase model: wdDoApplicationStateChange() This method is called either if a suspend request has been made, a resume request is received or the timeout event has been raised. The developer can react on these application states inside this method. wdDoBeforeNavigation() All navigation events are placed in a queue and are processed after all views in the current view assembly have been processed. The wdDoBeforeNavigation() method is called just before the WDF processes the events in the navigation queue. Changes to the navigation queue should be made here. 134 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access wdDoPostProcessing() As the last point before the UI is send to the user, in this method is the last possibility to change anything before this happens. The UI also needs hook methods to be processed during a server round trip. Views defining the UI therefore have the following ones: wdDoBeforeAction() This method runs right before handling the application events raised by the user making it possible to change or stop the execution of these events. wdOnContextMenu() If a context menu is used on the layout, this method is called to react on the user input made in the context menu. wdDoModifyView() This method is called just before the view layout is rendered. It is the only method in which the developer is allowed direct access to the UI element objects themselves. The parameter firstTime of the method is a Boolean value informing if the screen is being rendered for the first time or re-rendered in response to an action event. Typed Context API From within any controller, there will always be the shortcut variable wdContext. This is the starting point for all access to the controller’s entire context. When you create context entities at design time, you are creating the metadata that will describe the runtime data. Once the metadata that describes nodes and attributes has been created, actual node collection object can be created. Any node declared at design time will have a set of typed classes created for it. These class and method names will contain the name of the declared node. In order to access the individual attributes within a context node, three steps must be performed. 2008 © 2008 SAP AG. All rights reserved. 135
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 61: Access Context Node Access the relevant context node Accessing a context node is just a matter of calling wdContext.node<NodeName>(). This returns an object of type I<NodeName>Node. 136 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access Figure 62: Lead Selection Obtain a reference to the current node element The lead selection describes the currently selected node element on the UI. There is always only one element at the lead selection. A reference to this so called current element can be obtained by calling the method current<NodeName>Element() for the relevant node. It is also possible to call this method directly at the root node using wdContext because the name of the node is unique for the controller. The reference to a node element is of type I<NodeName>Element. Hint: It is possible that no element has the lead selection. Keep that in mind when developing your context access. 2008 © 2008 SAP AG. All rights reserved. 137
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 63: Access Context Attributes Call the relevant access methods For every context attribute a getter- and a setter-method is generated for accessing the value. These methods are generated using the types defined in the context and are always in the form get/set<AttributeName>(). It is also possible to create new elements for a context node by using the typed context API. New elements are created outside of a context node and then added to the relevant node. 138 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access Figure 64: Create Element First you need again the reference to the relevant context node. After that you can decide if you want to create and add the new element in a single step or in two separate ones. Two steps are only interesting if you want to insert the element in a certain order. The methods for creating a new element are in the form createAndAdd<NodeName>Element() or create<NodeName>element(). Caution: It is not possible to add additional elements to nodes of the collection cardinality 1..1 or more than one element to collection cardinality 0..1. The classes of the typed context API for the context nodes and elements are internal classes of the controller API they are defined in. The class of the form I<NodeName>Node offer all methods for interacting with the relevant node and its elements. The class of the form I<NodeName>Element offers methods for accessing all attributes of the node element. 2008 © 2008 SAP AG. All rights reserved. 139
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 65: Generated Methods The context of a custom controller is publicly accessible, but the context of a view controller is always private. This is to ensure that the data generator - data consumer concepts of MVC emphasized by Web Dynpro design are enforced. In other words, a view controller is not permitted to provide its context as a data source. Therefore, the following differences exist concerning the scope of the declared classes: • • 140 The context of a custom controller belongs both to its IPublic<ControllerName> interface and its IPrivate<ControllerName> interface. The context of a view controller belongs only to it IPrivate<ControllerName> interface. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access Exercise 9: Context Manipulation via Coding Exercise Objectives After completing this exercise, you will be able to: • change the value of context attributes. • manipulate UI properties via coding. Business Example You want to offer the user buttons for initializing and clearing the input mask. Optionally you want these functions not to be available when the input mask is disabled. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context4XX with XX as your group number. Template training.sap.com~context3 Solution training.sap.com~context4 training.sap.com~context4opt Task 1: Create a ButtonRow under the input mask in the InputView having the buttons InitializeButton and ClearButton. The InitializeButton should fire the action Initialize and the ClearButton the action Clear. 1. Right click in the Outline of the InputView on the transparent container and Insert Child... choosing an Invisible Element. Set its layoutData to MatrixHeadDate. Right click again on the transparent container and Insert Child... choosing a ButtonRow. 2. Right click on the ButtonRow and Insert Button... choosing InitializeButton as id for the button. Go to its property onAction and click Create. Enter for the name and text of the action Initialize. 3. Repeat the last step creating the button ClearButton and the action Clear. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 141
    • Unit 5: Web Dynpro Context Manipulation JA450 Task 2: Create the private instance method initStudent() having no return value. The method should set the context attributes FirstName, LastName, BeginDate and EndDate of context node Student with some standard values. Call the method when the InputView is initialized or the InitializeButton is activated. 1. Go to //@@begin others part of the InputView and create the method initStudent(). 2. Get the reference to the current element of node Student by using wdContext.currentStudentElement() and save it in a variable of type IStudentElement. 3. Set the context attribute FirstName by using the methodsetFirstName() of the current element to a suitable value. 4. Repeat the last step for the context attributes LastName, BeginDate and EndDate setting them with a suitable value. 5. Call the method initStudent() in the method wdDoInit() and onActionInitialize(). Task 3: In the method onActionClear() set all attributes of the node Student to null. 1. Get in the method onActionClear() the reference to the current element of node Student by using wdContext.currentStudentElement() and save it in a variable of type IStudentElement. 2. Set the context attribute FirstName by using the methodsetFirstName() of the current element to null. 3. Repeat the last step for the context attributes LastName, BeginDate and EndDate setting them to null. Task 4: Optional: Create a new context attribute Visibility of type Visibility for the node UIProperty of the component controller. Map the new attribute to node UIProperty of the MainView and InputView. Bind the property visibility of the InitializeButton and ClearButton in the InputView to the new attribute. Toggle the value of the context attribute Visibility by the ToggleButton in the MainView between WDVisibility.VISIBLE and WDVisibility.NONE. 1. Right click on the context node UIProperty of the component controller and choose New -> Attribute.... Select Manually, enter the name Visibility and click on Browse.... Navigate to Dictionary -> Local Dictionary -> com.sap.ide.webdynpro.uielementdefinitions and select Visibility. Continued on next page 142 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access 2. Right click on the context node UIProperty of the MainView and Edit Context Mapping.. selecting the attribute Visibility. Repeat the step for the InputView. 3. Bind the property visiblity of the InitializeButton and ClearButton in the InputView by clicking on Bind and selecting the context attribute Visibility. 4. Set in the method wdDoInit() the context attribute Visibility to WDVisibility.VISIBLE by using wdcontext.currentUIPropertyElement.setVisibility(). 5. Implement an If-clause in the method onActionToggle() setting the context attribute Visibility to WDVisibility.NONE if the Visibility equals WDVisibility.VISIBLE and vice versa. Task 5: Deploy new archive and run your application StudentApp. 1. 2008 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 143
    • Unit 5: Web Dynpro Context Manipulation JA450 Solution 9: Context Manipulation via Coding Task 1: Create a ButtonRow under the input mask in the InputView having the buttons InitializeButton and ClearButton. The InitializeButton should fire the action Initialize and the ClearButton the action Clear. 1. Right click in the Outline of the InputView on the transparent container and Insert Child... choosing an Invisible Element. Set its layoutData to MatrixHeadDate. Right click again on the transparent container and Insert Child... choosing a ButtonRow. a) 2. Right click on the ButtonRow and Insert Button... choosing InitializeButton as id for the button. Go to its property onAction and click Create. Enter for the name and text of the action Initialize. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step creating the button ClearButton and the action Clear. a) Perform as seen in the demonstration of your trainer. Task 2: Create the private instance method initStudent() having no return value. The method should set the context attributes FirstName, LastName, BeginDate and EndDate of context node Student with some standard values. Call the method when the InputView is initialized or the InitializeButton is activated. 1. Go to //@@begin others part of the InputView and create the method initStudent(). a) 2. Get the reference to the current element of node Student by using wdContext.currentStudentElement() and save it in a variable of type IStudentElement. a) 3. See source code extract of the sample solution. See source code extract of the sample solution. Set the context attribute FirstName by using the methodsetFirstName() of the current element to a suitable value. a) See source code extract of the sample solution. Continued on next page 144 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access 4. Repeat the last step for the context attributes LastName, BeginDate and EndDate setting them with a suitable value. a) 5. See source code extract of the sample solution. Call the method initStudent() in the method wdDoInit() and onActionInitialize(). a) See source code extract of the sample solution. Task 3: In the method onActionClear() set all attributes of the node Student to null. 1. Get in the method onActionClear() the reference to the current element of node Student by using wdContext.currentStudentElement() and save it in a variable of type IStudentElement. a) 2. Set the context attribute FirstName by using the methodsetFirstName() of the current element to null. a) 3. See source code extract of the sample solution. See source code extract of the sample solution. Repeat the last step for the context attributes LastName, BeginDate and EndDate setting them to null. a) See source code extract of the sample solution. Task 4: Optional: Create a new context attribute Visibility of type Visibility for the node UIProperty of the component controller. Map the new attribute to node UIProperty of the MainView and InputView. Bind the property visibility of the InitializeButton and ClearButton in the InputView to the new attribute. Toggle the value of the context attribute Visibility by the ToggleButton in the MainView between WDVisibility.VISIBLE and WDVisibility.NONE. 1. Right click on the context node UIProperty of the component controller and choose New -> Attribute.... Select Manually, enter the name Visibility and click on Browse.... Navigate to Dictionary -> Local Dictionary -> com.sap.ide.webdynpro.uielementdefinitions and select Visibility. a) 2. Perform as seen in the demonstration of your trainer. Right click on the context node UIProperty of the MainView and Edit Context Mapping.. selecting the attribute Visibility. Repeat the step for the InputView. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 145
    • Unit 5: Web Dynpro Context Manipulation 3. Bind the property visiblity of the InitializeButton and ClearButton in the InputView by clicking on Bind and selecting the context attribute Visibility. a) 4. Perform as seen in the demonstration of your trainer. Set in the method wdDoInit() the context attribute Visibility to WDVisibility.VISIBLE by using wdcontext.currentUIPropertyElement.setVisibility(). a) 5. JA450 See source code extract of the sample solution. Implement an If-clause in the method onActionToggle() setting the context attribute Visibility to WDVisibility.NONE if the Visibility equals WDVisibility.VISIBLE and vice versa. a) See source code extract of the sample solution. Task 5: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result InputView //@@begin imports import java.sql.Date; import com.sap.training.context4.studentcomp.wdp.IPrivateInputView; import com.sap.training.context4.studentcomp.wdp.IPrivateInputView .IStudentElement; //@@end public void wdDoInit() { //@@begin wdDoInit() initStudent(); //@@end } public void onActionInitialize( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionInitialize(ServerEvent) initStudent(); Continued on next page 146 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access //@@end } public void onActionClear( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionClear(ServerEvent) IStudentElement currentStudentElement = wdContext.currentStudentElement(); currentStudentElement.setFirstName(null); currentStudentElement.setLastName(null); currentStudentElement.setBeginDate(null); currentStudentElement.setEndDate(null); //@@end } //@@begin others private void initStudent() { IStudentElement currentStudentElement = wdContext.currentStudentElement(); currentStudentElement.setFirstName("John"); currentStudentElement.setLastName("Smith"); currentStudentElement.setBeginDate(Date.valueOf("2008-10-20")); currentStudentElement.setEndDate(Date.valueOf("2008-10-24")); } //@@end MainView //@@begin imports import com.sap.tc.webdynpro.progmodel.api.WDVisibility; import com.sap.training.context4opt.studentcomp.wdp.IPrivateMainView; //@@end public void wdDoInit() { //@@begin wdDoInit() wdContext.currentUIPropertyElement() .setVisibility(WDVisibility.VISIBLE); //@@end } public void onActionToggle( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) Continued on next page 2008 © 2008 SAP AG. All rights reserved. 147
    • Unit 5: Web Dynpro Context Manipulation JA450 { //@@begin onActionToggle(ServerEvent) if (wdContext.currentUIPropertyElement().getVisibility().equals( WDVisibility.VISIBLE)) { wdContext.currentUIPropertyElement().setVisibility( WDVisibility.NONE); } else { wdContext.currentUIPropertyElement().setVisibility( WDVisibility.VISIBLE); } //@@end } 148 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Context Access Lesson Summary You • • • • 2008 should now be able to: use shortcut variables for accessing different parts of Web Dynpro. choose the correct place for your coding in the controller implementation. describe the steps of server round trip. access the elements in the context. © 2008 SAP AG. All rights reserved. 149
    • Unit 5: Web Dynpro Context Manipulation JA450 Lesson: Multiple Context Elements Lesson Overview This lesson shows the use of the collection cardinality and how to copy elements between context nodes. In addition the Table UI element is introduced as an example for composite UI elements. Lesson Objectives After completing this lesson, you will be able to: • • • use the benefits of the collection cardinality. copy elements between nodes by using the WDCopyService. create and bind a Table UI element to the context. Business Example You want to copy the data of your input form to a context node holding the data visualized in a table on the screen. Context Property When working with the context, the collection cardinality of a context node is one of the most important node properties. Before you try to add node elements to a node or delete node elements, you should first check the collection cardinality. The WDF will not allow adding more than one element to a node with multiple set to one. The WDF will also not allow deleting the last element in a node with mandatory set to one. 150 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements Figure 66: Cardinality Options Having the collection cardinality 1..1, the context root node is immutable for adding or deleting any element. Therefore it is assured that there will always be a current element in the context root node. For all other nodes the collection cardinality can be set freely. Often a context node of collection cardinality 1..1 is used for input masks saving the values the user enters as long as the application runs. When the input mask is used for creating new business data e.g. for a table, the new element can be copied to a central node of collection cardinality 0..n by using the WDCopyService. 2008 © 2008 SAP AG. All rights reserved. 151
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 67: WDCopyService The utility class WDCopyService offers the following methods: copyElements() Copies all elements from source to target including the lead selection. copySubtree() Copies all elements from the complete subtree of source to target recursively. copyCorresponding() Inspects all attributes of the source element, searches a compatible attribute in the target and copies the value if the search is successful. Caution: WDCopyService.copyCorresponding() only works with IWDNodeElement or ICMIGenericModelClass and their subclasses. If other classes are used as method parameter, the method will exit silently finding no matching attributes. Table UI Element Certain UI elements are displayed on the screen as aggregations of simpler UI elements. The Table UI element is one example for such a composite UI element. Without the subordinate or child UI elements, a composite UI element is not capable of displaying any information. 152 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements Figure 68: Table Columns The Table UI element acts as a parent for several TableColumn UI elements. Each column itself acts as the parent for a Caption and TableCellEditor UI element. Many simple UI elements can act as a TableCellEditor UI element displaying the actual value of context attributes. It is perfectly possible to use the table not only for displaying but also for changing the values by using the appropriate TableCellEditor UI elements. 2008 © 2008 SAP AG. All rights reserved. 153
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 69: Table Cells The Table UI element allows the two-dimensional display of data in cells arranged in rows and columns. The content of a context node is most easily visualized as a table. Each context attribute corresponds to a table column and each element in the node collection corresponds to a table row. The table must contain at least on TableColumn UI element. There is no such thing as a table row UI element. The UI elements making up a table require several bindings to the context in order to function correctly: • • • 154 The Table UI element must be bound to the context node whose elements should be displayed. The TableColumn UI element must be bound to one attribute of the node to which the parent Table UI element is bound. The TableCellEditor UI element must be bound to the attribute of the node to which the parent TableColumn UI element is bound. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements Figure 70: Binding Context to Table Irrespective of whether you have associated an action with the onLeadSelection event of the Table UI element, any time you click on a table row a round trip to the server takes place. This round trip will cause the lead selection of the corresponding context node to which this table is bound to be adjusted. The element at lead selection becomes the highlighted row when displayed on the screen. There will be as many rows in the table as there are elements in the node collection. Any context attribute of a simple data type is a candidate for becoming a table column. It is possible to create a table by adding step by step each single UI element, but in Web Dynpro there are templates available for creating and changing a table depending on the bound context. 2008 © 2008 SAP AG. All rights reserved. 155
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 71: Apply Template - Create Binding As for an input form the Apply Template functionality offers the possibility to generate a Table UI element including TableColumns and their child elements in one step. All you need is a context node having attributes to be displayed. The binding of an existing Table UI element can be changed by using the Create Binding functionality. It is possible to add additional columns or delete ones. The functionality will adjust all needed settings. Caution: The Create Binding may reset already changed UI element properties using default settings. 156 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements Figure 72: Table Child UI Elements Beside table columns a Table UI element can have a variety of child elements. They can offer additional functionality for the table like a tool bar or be just optical design like a header. Some have the possibility to add more complex features to the table for example the Popin. It is a container for normal UI elements which will be displayed, when the user opens the Popin for a single row. Through that it is possible to show additional details for one entry in the table. 2008 © 2008 SAP AG. All rights reserved. 157
    • Unit 5: Web Dynpro Context Manipulation 158 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Multiple Context Elements Exercise 10: Table UI Element Exercise Objectives After completing this exercise, you will be able to: • add new elements to a context node. • copy elements between context nodes. • generate a table for the UI. Business Example You want to add a table to the application to save the students entered in the input mask. The entries in the table should be changeable by the former output mask. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context5XX with XX as your group number. Template training.sap.com~context4opt Solution training.sap.com~context5 Task 1: Change the property Collection Cardinality of the context node Student in the component controller to 0..n. Rename the node Student in the component controller, InputView and OutputView to Students. 1. Go to the context of the component controller and change the property Collection Cardinality of node Student to 0..n. 2. Right click on the context node Student and Rename... it to Students. 3. Repeat the last step renaming the context node Student to Students in the InputView and OutputView. Hint: The syntax errors in the InputView will be fixed in the next task. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 159
    • Unit 5: Web Dynpro Context Manipulation JA450 Task 2: Create the context node NewStudent in the InputView with structure binding to the dictionary structure Student and Collection Cardinality of 1..1 adding attributes for all structure elements. Change the binding of the input fields to the corresponding attributes of the node NewStudent and adapt the coding of the InitializeButton and ClearButton to work on the node NewStudent instead of Students. 1. Right click on the context root node in the InputView and choose New -> Node... selecting Structure Binding. Navigate to Dictionaries -> Local Dictionary -> com.sap.training.groupXX.structures and choose the structure Student selecting all elements. 2. Rename the new context node to NewStudent and set its property Collection Cardinality to 1..1. Rename all attributes equivalent to the spelling of the attributes in context node Students. 3. Click in the property value of all input fields in the InputView on Bind and select compared to the old binding the equivalent context attribute in node NewStudent. 4. Adapt the coding in the methods initStudent() and onActionClear() getting a reference to the current element of the context node NewStudent instead of node Student by using wdContext.currentNewStudentElement() and saving it in a variable of type INewStudentElement. Task 3: Create a SaveButton of design next in the ButtonGroup of the InputView. Implement in the action of the SaveButton the code to add a new element to the node Students using the data entered in the current element of node NewStudent. 1. Right click on the ButtonRow and Insert Button... choosing SaveButton as id for the button. Set its property design to next and bind its property visible to the context attribute Visibility. Go to its property onAction and click Create. Enter for the name and text of the action Save. 2. Create a new Students element and add it to the context node Students by using the method wdContext.createAndAddStudentsElement(). Save the reference to the element in a variable of type IStudentsElement. 3. Get a reference to the current NewStudent element by using wdContext.currentNewStudentElement() and copy its attribute values to the new element of the node Students by usingWDCopyService.copyCorresponding(). Continued on next page 160 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements Task 4: Create a new Group UI container in the MainView next to the existing one. Set the heading to Student List, insert an empty ToolBar and a ViewContainerUIElement in the group. 1. Go to the RootElement in the Outline of the MainView and set the properties layout to MatrixLayout and the layout property stretchedHorizontally to false. 2. Right click on the RootElement and Insert Child... choosing a Group UI container. Set its heading to Student List. 3. Right click on the new group and Insert ToolBar. Right click again on the new group and Insert Child... choosing a ViewContainerUIElement. Task 5: Create a new view called TableView in the second ViewContainerUIElement of the MainView. Map the context node Students of the component controller to the context of TableView. Generate a TableUIElement bound to the context node Students. 1. Go to the navigation of StudentWindow and select Embed new View from the menu on the right. Click in the second ViewContainerUIElement of the MainView and enter the name TableView. 2. Go to the context of the TableView and right click on the context root node. Choose New -> Node... and select Mapping. Select StudentComp as required controller and choose the context node Students including all of its attributes. 3. Go to the layout of the TableView and delete the DefaultTextView. Right click on the RootElement and Apply Template choosing Table. Select all attributes of the context node Students and finish. Task 6: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. Hint: If you receive a NullPointerException for the method initStudent(), you probably forgot to set the Collection Cardinality in the second task. 2008 © 2008 SAP AG. All rights reserved. 161
    • Unit 5: Web Dynpro Context Manipulation JA450 Solution 10: Table UI Element Task 1: Change the property Collection Cardinality of the context node Student in the component controller to 0..n. Rename the node Student in the component controller, InputView and OutputView to Students. 1. Go to the context of the component controller and change the property Collection Cardinality of node Student to 0..n. a) 2. Right click on the context node Student and Rename... it to Students. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step renaming the context node Student to Students in the InputView and OutputView. Hint: The syntax errors in the InputView will be fixed in the next task. a) Perform as seen in the demonstration of your trainer. Task 2: Create the context node NewStudent in the InputView with structure binding to the dictionary structure Student and Collection Cardinality of 1..1 adding attributes for all structure elements. Change the binding of the input fields to the corresponding attributes of the node NewStudent and adapt the coding of the InitializeButton and ClearButton to work on the node NewStudent instead of Students. 1. Right click on the context root node in the InputView and choose New -> Node... selecting Structure Binding. Navigate to Dictionaries -> Local Dictionary -> com.sap.training.groupXX.structures and choose the structure Student selecting all elements. a) 2. Perform as seen in the demonstration of your trainer. Rename the new context node to NewStudent and set its property Collection Cardinality to 1..1. Rename all attributes equivalent to the spelling of the attributes in context node Students. a) Perform as seen in the demonstration of your trainer. Continued on next page 162 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements 3. Click in the property value of all input fields in the InputView on Bind and select compared to the old binding the equivalent context attribute in node NewStudent. a) 4. Perform as seen in the demonstration of your trainer. Adapt the coding in the methods initStudent() and onActionClear() getting a reference to the current element of the context node NewStudent instead of node Student by using wdContext.currentNewStudentElement() and saving it in a variable of type INewStudentElement. a) See source code extract of the sample solution. Task 3: Create a SaveButton of design next in the ButtonGroup of the InputView. Implement in the action of the SaveButton the code to add a new element to the node Students using the data entered in the current element of node NewStudent. 1. Right click on the ButtonRow and Insert Button... choosing SaveButton as id for the button. Set its property design to next and bind its property visible to the context attribute Visibility. Go to its property onAction and click Create. Enter for the name and text of the action Save. a) 2. Create a new Students element and add it to the context node Students by using the method wdContext.createAndAddStudentsElement(). Save the reference to the element in a variable of type IStudentsElement. a) 3. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Get a reference to the current NewStudent element by using wdContext.currentNewStudentElement() and copy its attribute values to the new element of the node Students by usingWDCopyService.copyCorresponding(). a) See source code extract of the sample solution. Task 4: Create a new Group UI container in the MainView next to the existing one. Set the heading to Student List, insert an empty ToolBar and a ViewContainerUIElement in the group. 1. Go to the RootElement in the Outline of the MainView and set the properties layout to MatrixLayout and the layout property stretchedHorizontally to false. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 163
    • Unit 5: Web Dynpro Context Manipulation 2. Right click on the RootElement and Insert Child... choosing a Group UI container. Set its heading to Student List. a) 3. JA450 Perform as seen in the demonstration of your trainer. Right click on the new group and Insert ToolBar. Right click again on the new group and Insert Child... choosing a ViewContainerUIElement. a) Perform as seen in the demonstration of your trainer. Task 5: Create a new view called TableView in the second ViewContainerUIElement of the MainView. Map the context node Students of the component controller to the context of TableView. Generate a TableUIElement bound to the context node Students. 1. Go to the navigation of StudentWindow and select Embed new View from the menu on the right. Click in the second ViewContainerUIElement of the MainView and enter the name TableView. a) 2. Go to the context of the TableView and right click on the context root node. Choose New -> Node... and select Mapping. Select StudentComp as required controller and choose the context node Students including all of its attributes. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Go to the layout of the TableView and delete the DefaultTextView. Right click on the RootElement and Apply Template choosing Table. Select all attributes of the context node Students and finish. a) Perform as seen in the demonstration of your trainer. Task 6: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. Hint: If you receive a NullPointerException for the method initStudent(), you probably forgot to set the Collection Cardinality in the second task. a) Perform as seen in the demonstration of your trainer. Continued on next page 164 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements Result InputView //@@begin imports import java.sql.Date; import com.sap.tc.webdynpro.progmodel.api.WDCopyService; import com.sap.training.context5.studentcomp.wdp.IPrivateInputView; import com.sap.training.context5.studentcomp.wdp.IPrivateInputView .INewStudentElement; import com.sap.training.context5.studentcomp.wdp.IPrivateInputView .IStudentsElement; //@@end public void onActionClear( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionClear(ServerEvent) INewStudentElement currentNewStudentElement = wdContext .currentNewStudentElement(); currentNewStudentElement.setFirstName(null); currentNewStudentElement.setLastName(null); currentNewStudentElement.setBeginDate(null); currentNewStudentElement.setEndDate(null); //@@end } public void onActionSave( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSave(ServerEvent) IStudentsElement studentsElement = wdContext .createAndAddStudentsElement(); WDCopyService.copyCorresponding(wdContext.currentNewStudentElement(), studentsElement); //@@end } //@@begin others private void initStudent() { INewStudentElement currentNewStudentElement = wdContext .currentNewStudentElement(); currentNewStudentElement.setFirstName("John"); currentNewStudentElement.setLastName("Smith"); currentNewStudentElement.setBeginDate(Date.valueOf("2008-10-20")); currentNewStudentElement.setEndDate(Date.valueOf("2008-10-24")); Continued on next page 2008 © 2008 SAP AG. All rights reserved. 165
    • Unit 5: Web Dynpro Context Manipulation JA450 } //@@end 166 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Multiple Context Elements Lesson Summary You • • • 2008 should now be able to: use the benefits of the collection cardinality. copy elements between nodes by using the WDCopyService. create and bind a Table UI element to the context. © 2008 SAP AG. All rights reserved. 167
    • Unit 5: Web Dynpro Context Manipulation JA450 Lesson: Selecting Context Elements Lesson Overview This lesson introduces the selection cardinality property of context nodes, uses it to delete selected elements and shows how to make coding centrally available inside a component. Lesson Objectives After completing this lesson, you will be able to: • • • handle the selection cardinality of context nodes. delete elements from a context node. interoperate between controllers. Business Example You want select multiple elements in a table and choose by that which elements in the context should be deleted. Selection Before a user is permitted to select multiple rows from a table, the context node to which the Table UI element is bound must have a selection cardinality of either 0..n or 1..n. It is not possible for a UI element to overload the settings of the context. It can only reduce the selection. Hint: To select multiple rows in a table hold down the shift or control key while clicking on the relevant rows. 168 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Selecting Context Elements Figure 73: Table Selection The default selection cardinality setting for any context node is 0..1. For all context nodes except the context root node, the collection cardinality can have the following values: 0..1 No more than one element is selectable. 0..n Any number of elements are selectable. 1..1 Exactly one element is always selected. 1..n At least one element is selected. There is still only one element at lead selection. Additional selected elements can be identified via the flag multi selected. The current element having the lead selection does not need to have its multi selected flag set to true. 2008 © 2008 SAP AG. All rights reserved. 169
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 74: Selection Values For nodes with single selection cardinality, the flag multi selected will not exist. The selected element is determined by the lead selection. Delete Elements Beside the typed context API there exists the generic context API. It offers methods suitable for all context nodes and attributes. One of these methods is for deleting context elements. 170 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Selecting Context Elements Figure 75: Delete Current Element The method removeElement() only needs the reference to the element which should be deleted. If you want to delete the current element, you should first check if one element has the lead selection. The class IWDNode offers the constant NO-SELECTION for checking if the lead selection is set. Figure 76: Delete Multiple Elements 2008 © 2008 SAP AG. All rights reserved. 171
    • Unit 5: Web Dynpro Context Manipulation JA450 In order to process all selected elements in a node collection, it is necessary to loop around all the elements in the collection, testing the flag multi selected. This can be done by calling the method isMultiSelected() for each element. The node collections do not allow gaps in their list of elements. So when deleting an element, all following elements are moved one index up. For the loop this means to check all elements it should cycle through the node in reverse order. Figure 77: Generic Methods The classes IWDNode and IWDNodeElement are the parent classes for all generated classes of the typed context API. They offer several generic methods to work with the context. These methods do not bother about the names and types in the context. They just work with the objects of type Object, Node, NodeElement and their interfaces. These objects can then be cast using the relevant typed classes. Sometimes it is easier to reach the implementation goal by using the generic API but sometimes the typed context API just does not exist. In Web Dynpro it is possible to create the context structure at runtime defining nodes and attributes. For these elements there will be no typed context API available. Only for context elements defined at design time a typed context API will be generated. 172 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Selecting Context Elements Central Coding A Web Dynpro component is not a single Java class. Instead it is an aggregation of independent but inter-related Java classes that all function together as this single entity known as a component. In order for information to be shared amongst the controllers in a component, specific declarations must be made. Once these declarations have been made, the NWDS then generates an API that gives one controller access to the other controller's methods and context. Figure 78: Required Controller The declaration for accessing a controller is called required controller. If you use something of another controller, the existence of this controller is required for the using controller to function correctly. The required controller is needed for context mapping as well as calling methods or raising events. The using controller holds a list of its required controllers which can be extended there or by drawing a data link between controllers in the data modeler. 2008 © 2008 SAP AG. All rights reserved. 173
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 79: Call Controller Method When accessing the required controller by coding, the start point is the shortcut variable wdThis. For every required controller a method is generated in the form of wdGet<ControllerName>Controller(). By using this reference, calling methods or raising events defined in the required controller can be implemented. The Apply Template functionality offers the option to generate the coding for accessing a method in another controller. Note: View controllers can not be accessed using the required controller because their API is private to the view controller itself. 174 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Selecting Context Elements Exercise 11: Selection with Table UI Element Exercise Objectives After completing this exercise, you will be able to: • handle context nodes with multiple selected elements. • delete context elements. • call methods of another controller. Business Example You want the user to be able to select multiple students in the table and you want to offer a button deleting all selected students. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context6XX with XX as your group number. Template training.sap.com~context5 Solution training.sap.com~context6 Task 1: Set the context node Students in the component controller to be able to have multiple selected elements. Create the method deleteSelectedStudents() and implement the coding to delete the current element and all multi selected elements of context node Students. 1. Go to the context of the component controller and change the property Selection Cardinality of the node Students to 0..n. 2. Go to the methods of the component controller and click on New... selecting the method type Method. Set the name to deleteSelectedStudents . 3. Inside the method deleteSelectedStudents() get a reference to the context node Students by using wdContext.nodeStudents() and save it in a variable of type IStudentsNode. 4. Use the node reference to determine if the context node Students has a current element by using the method getLeadSelection() and then remove it from the node by using removeElement(). Continued on next page 2008 © 2008 SAP AG. All rights reserved. 175
    • Unit 5: Web Dynpro Context Manipulation 5. JA450 Resolve in a loop if the context node Students has multi selected elements by using isMultiSelected() and then remove the elements from the node by using removeElementAt(). Task 2: Create a button with id DeleteButton in the toolbar of the second group firing the action Delete. Call the method deleteSelectedStudents() of the component controller in the action handler. 1. Right click on the ToolBar of the second group in the MainView and choose Insert ToolBarItem... selecting a ToolBarButton with id DeleteButton. 2. Create a new action for the DeleteButton with name and text Delete. 3. Inside the method onActionDelete get a reference to the component controller by using wdThis.wdGetStudentCompController() and call the method deleteSelectedStudents(). Task 3: Deploy new archive and run your application StudentApp. 1. 176 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Selecting Context Elements Solution 11: Selection with Table UI Element Task 1: Set the context node Students in the component controller to be able to have multiple selected elements. Create the method deleteSelectedStudents() and implement the coding to delete the current element and all multi selected elements of context node Students. 1. Go to the context of the component controller and change the property Selection Cardinality of the node Students to 0..n. a) 2. Go to the methods of the component controller and click on New... selecting the method type Method. Set the name to deleteSelectedStudents . a) 3. See source code extract of the sample solution. Use the node reference to determine if the context node Students has a current element by using the method getLeadSelection() and then remove it from the node by using removeElement(). a) 5. Perform as seen in the demonstration of your trainer. Inside the method deleteSelectedStudents() get a reference to the context node Students by using wdContext.nodeStudents() and save it in a variable of type IStudentsNode. a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Resolve in a loop if the context node Students has multi selected elements by using isMultiSelected() and then remove the elements from the node by using removeElementAt(). a) See source code extract of the sample solution. Task 2: Create a button with id DeleteButton in the toolbar of the second group firing the action Delete. Call the method deleteSelectedStudents() of the component controller in the action handler. 1. Right click on the ToolBar of the second group in the MainView and choose Insert ToolBarItem... selecting a ToolBarButton with id DeleteButton. a) 2. Perform as seen in the demonstration of your trainer. Create a new action for the DeleteButton with name and text Delete. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 177
    • Unit 5: Web Dynpro Context Manipulation 3. JA450 Inside the method onActionDelete get a reference to the component controller by using wdThis.wdGetStudentCompController() and call the method deleteSelectedStudents(). a) See source code extract of the sample solution. Continued on next page 178 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Selecting Context Elements Task 3: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result Component Controller //@@begin importsimport com.sap.tc.webdynpro.progmodel.api.IWDNode; import com.sap.training.context6.studentcomp.wdp.IPrivateStudentComp; import com.sap.training.context6.studentcomp.wdp.IPublicStudentComp .IStudentsNode; //@@end public void deleteSelectedStudents( ) { //@@begin deleteSelectedStudents() IStudentsNode studentsNode = wdContext.nodeStudents(); if (studentsNode.getLeadSelection() != IWDNode.NO_SELECTION) { studentsNode.removeElement(studentsNode.currentStudentsElement()); } for (int i = studentsNode.size() - 1; i >= 0; i--) { if (studentsNode.isMultiSelected(i)) { studentsNode.removeElementAt(i); } } //@@end } MainView public void onActionDelete( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionDelete(ServerEvent) wdThis.wdGetStudentCompController().deleteSelectedStudents(); //@@end } 2008 © 2008 SAP AG. All rights reserved. 179
    • Unit 5: Web Dynpro Context Manipulation JA450 Lesson Summary You should now be able to: • handle the selection cardinality of context nodes. • delete elements from a context node. • interoperate between controllers. 180 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Calculated Attributes Lesson: Calculated Attributes Lesson Overview This lesson sows how to implement calculated attributes and which rules should be followed while doing this. Lesson Objectives After completing this lesson, you will be able to: • • implement calculated attributes. decide if a setter-method is possible. Business Example You want to format values on the screen to make the data more readable for the user without saving it in the context. Getter Method The context in Web Dynpro offers the possibility to create so called calculated attributes. A calculated attribute does not store any data. Instead the value is calculated on demand by the WDF by calling a getter method implemented by the developer. Figure 80: Typical Usage 2008 © 2008 SAP AG. All rights reserved. 181
    • Unit 5: Web Dynpro Context Manipulation JA450 The purpose of a calculated attribute is mainly for formatting or combining values for the screen. They should not be used for calculating business data for storage reasons because the calculation is performed every time it is demanded for every node element if necessary. Therefore the calculation should be efficient and stable. The getter-method of an attribute has the form get<NodeName><AttributeName>() and will be called by the WDF automatically. The return value of the method sets the value in the context until the data is demanded again. Figure 81: Context Property calculated The getter-method must be seen from the point of view of the WDF. The WDF questions the developer to get the value for the attribute. The return value therefore returns the value to the framework setting it in the context. If the processing is more costly, then you can use the buffer mode property to preserve the calculated value. 182 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Calculated Attributes Figure 82: Method Coding When calculating a value in the getter-method it should be calculated using only values of the current element of the same node. For this reason the current element is available through the parameter element of the method. Caution: Be careful when accessing attributes of other nodes because the process of accessing might cause other supply functions to be invoked. This could lead to an infinite supply function loop. Setter Method The property readOnly of a context attribute set to true makes it impossible for the user to change the value via the UI. It can only be changed via coding. For a calculated attribute the property readOnly it set to true by default. 2008 © 2008 SAP AG. All rights reserved. 183
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 83: Context Property readOnly If changing the property to false, a new method is generated in addition to the getter-method. This setter-method has the purpose of reversing the calculation performed in the getter-method. For example a generated text on the UI could be changed by the user and then saved back in the context attributes used for calculation. 184 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Calculated Attributes Figure 84: Irreversible Calculation A setter-method is not used very often because many calculations are not needed in reverse. Even more important many calculations are just irreversible like adding two simple numbers. You can not distinguish from the result which and how many numbers have been added together. A concatenation instead is often possible to be reversed if rules for the combined String exist. Put together when working with calculated attributes you should understand the following principles: • • • • • 2008 The getter-method should derive the value of the calculated attribute using the parameter element. Avoid accessing values of other context nodes as this might cause other supply functions to be invoked. Handle errors gracefully because you can not predict when the method is called. Do not attempt to interact with models or other persistent services. The implementation should be simple and efficient. © 2008 SAP AG. All rights reserved. 185
    • Unit 5: Web Dynpro Context Manipulation 186 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Calculated Attributes Exercise 12: Calculated Attribute Exercise Objectives After completing this exercise, you will be able to: • create a calculated context attribute. • implement a calculated getter-method. • use language specific date format. Business Example You want to show the time period between begin date and end date of the student as a text on the UI which should be always up-to-date to the entered dates on the UI. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context7XX with XX as your group number. Template training.sap.com~context6 Solution training.sap.com~context7 Task 1: Create a new read-only calculated context attribute called TimeSpan of type string in the node Students of the OutputView. Implement the getter-method of the context attribute TimeSpan to return a language specific text concatenating BeginDate, “-” and EndDate. 1. Right click on the context node Students in the OutputView and choose New -> Attribute... selecting manually. Set the name to TimeSpan, the type to string and flag the checkbox Calculated. 2. In the method getStudentsTimeSpan() create a variable of type DateFormat by using its static method getDateInstance(). Set a date format and get the current session locale from the service class WDResourceHandler. 3. Use the variable of type DateFormat to format BeginDate and EndDate. Return the concatenated text of both dates separated by “-”. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 187
    • Unit 5: Web Dynpro Context Manipulation JA450 Task 2: Add a label and TextView for the context attribute TimeSpan under the existing input fields for FirstName and LastName in the OutputView. Change the position of the image to top of page. 1. Right click on the TransparentContainer in the Outline of the OutputView and Apply Template selecting Form. Flag the context attribute TimeSpan and choose a TextView to be generated from the drop down list 2. Change the property text of the label to Time Span. Change the layout data property vAling of the image to top. Task 3: Bind the property visible of the HorizontalGutter and DateNavigator to the context attribute Visibility mapped from the component controller. 1. Right click on the context node UIProperty in the OutputView and Edit Context Mapping... selecting Visibility. 2. Select both the HorizontalGutter and DateNavigator and click in the property visible on Bind selecting the context attribute Visibility. Task 4: Deploy new archive and run your application StudentApp. 1. 188 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Calculated Attributes Solution 12: Calculated Attribute Task 1: Create a new read-only calculated context attribute called TimeSpan of type string in the node Students of the OutputView. Implement the getter-method of the context attribute TimeSpan to return a language specific text concatenating BeginDate, “-” and EndDate. 1. Right click on the context node Students in the OutputView and choose New -> Attribute... selecting manually. Set the name to TimeSpan, the type to string and flag the checkbox Calculated. a) 2. In the method getStudentsTimeSpan() create a variable of type DateFormat by using its static method getDateInstance(). Set a date format and get the current session locale from the service class WDResourceHandler. a) 3. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Use the variable of type DateFormat to format BeginDate and EndDate. Return the concatenated text of both dates separated by “-”. a) See source code extract of the sample solution. Task 2: Add a label and TextView for the context attribute TimeSpan under the existing input fields for FirstName and LastName in the OutputView. Change the position of the image to top of page. 1. Right click on the TransparentContainer in the Outline of the OutputView and Apply Template selecting Form. Flag the context attribute TimeSpan and choose a TextView to be generated from the drop down list a) 2. Perform as seen in the demonstration of your trainer. Change the property text of the label to Time Span. Change the layout data property vAling of the image to top. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 189
    • Unit 5: Web Dynpro Context Manipulation JA450 Task 3: Bind the property visible of the HorizontalGutter and DateNavigator to the context attribute Visibility mapped from the component controller. 1. Right click on the context node UIProperty in the OutputView and Edit Context Mapping... selecting Visibility. a) 2. Perform as seen in the demonstration of your trainer. Select both the HorizontalGutter and DateNavigator and click in the property visible on Bind selecting the context attribute Visibility. a) Perform as seen in the demonstration of your trainer. Task 4: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result OutputView public java.lang.String getStudentsTimeSpan( IPrivateOutputView.IStudentsElement element) { //@@begin getStudentsTimeSpan DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, WDResourceHandler.getCurrentSessionLocale()); return dateFormat.format(element.getBeginDate()) + " - " + dateFormat.format(element.getEndDate()); //@@end } 190 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Calculated Attributes Lesson Summary You should now be able to: • implement calculated attributes. • decide if a setter-method is possible. 2008 © 2008 SAP AG. All rights reserved. 191
    • Unit 5: Web Dynpro Context Manipulation JA450 Lesson: Dependent Nodes Lesson Overview This lesson explains how singleton child nodes can reduce the amount of memory consumed by an application without loosing business data. Lesson Objectives After completing this lesson, you will be able to: • • • explain the properties of the node categories. understand the purpose of singleton nodes. implement supply functions. Business Example You want to reduce the amount of memory consumed by your application by loading only the actual needed business data in your context. In-/Dependent Nodes There are three different categories of context nodes in Web Dynpro: • • • 192 Context root node Independent nodes Dependent nodes © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes Figure 85: Context Structure The context root node is unique for every controller. It defines the root of the context which will be created by the WDF when creating the controller instance. So it is assumed that the context root node always exists. The nodes that have the context root node as their immediate parent are referred to as being independent. The related collection will automatically exist at runtime because the context root node is guaranteed to contain exactly one element. They exist independently of other objects. Nodes that have some other node as their parent are referred to as being dependent. The related collections will not exist before at least one element in their parent collection does exist. They depend on the existence of their parent. 2008 © 2008 SAP AG. All rights reserved. 193
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 86: Default Properties The properties differing between the three node categories are the collection cardinality and the singleton ones. Independent nodes are always singleton; dependent nodes can be set freely. The context root node is special in that case because every property is immutable having a collection cardinality of 1..1 and singleton true. Root Independent Dependent Cardinality 1..1 - - Singleton true true - Singleton Web Dynpro follows the principle of lazy data access. This means that data is only obtained when it is actually needed. When this principle is applied to the architecture of the context, it means that unless the program actually needs to look at the data in a child node, the child node will remain unprocessed. Hence, there is no need to hold multiple instances of data the user has not requested. 194 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes Figure 87: Non-Singleton Node Dependent nodes are by default non-singleton. This means that for every element in the parent node collection there will be a specific instance of a child node collection. Therefore if there are n elements in the parent node, there will be n distinct instances of a non-singleton child node. If the dependent node has its singleton property set to true, then it does not matter how many elements are present in the parent node collection. There will only ever be one instance of the child node. 2008 © 2008 SAP AG. All rights reserved. 195
    • Unit 5: Web Dynpro Context Manipulation JA450 Figure 88: Singleton Node A singleton child node can only store the data for one parent element. This one parent element is the element at lead selection. The data for all other elements must be saved elsewhere. Having only one collection for all elements, it must be assured that when this child node is accessed, it contains the correct data for the selected element in the parent node. Supply functions are the mechanism to repopulate child nodes when the lead selection in the parent node changes. The application developer must implement the supply function, but never calls it explicitly. This is done by the WDF automatically. 196 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes Figure 89: Supply Function Any context node may have a supply function defined for it. All dependent singleton nodes must have one defined. The supply function is called by the WDF when an attempt is made to read an invalid node collection. A node collection can be invalid for any one of the following reasons: • • • It has never been populated before. The lead selection in the parent node collection has changed. Application coding has invalidated the element collection. Having singleton child nodes greatly reduces the amount of memory required for a business application. That means that the Web Dynpro application does not waste time performing unnecessary processing on business data the user does not want to see. Note: A singleton child node is not practical for all applications. Imagine a table showing the data of the parent node and for every element the child data at the same time. The supply function would be called for every parent element in one single server round trip just for showing the table. 2008 © 2008 SAP AG. All rights reserved. 197
    • Unit 5: Web Dynpro Context Manipulation 198 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Dependent Nodes Exercise 13: Dependent Context Nodes Exercise Objectives After completing this exercise, you will be able to: • change the data structure of a Web Dynpro application. • use dependent nodes in the context. • understand the implementation order of the Web Dynpro parts. Business Example You want to extend your application to manage courses having students as participants. Above the former UI a table should be available for creating, changing and deleting courses. Students can only be added to existing courses. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~context8XX with XX as your group number. Template training.sap.com~context7 Solution training.sap.com~context8 Task 1: Create the dictionary simple type CourseID of type string with a maximum length of 6 and the simple type CourseTitle also of type string. Maintain the text objects appropriately. Create a new dictionary structure called Course having the two elements ID and Title referencing the defined simple types. 1. Right click on Simple Types in the Web Dynpro Explorer showing the dictionary of your DC and choose Create Simple Type. Enter the name CourseID and the package com.sap.training.groupXX.simpletypes. Set a description and define the Maximum Length to 6. Field Label and Column Label have the text ID and the Quick Info the text Course ID. 2. Repeat the last step creating the simple type CourseTitle in the same package with no length restriction. Field Label and Column Label have the text Title and the Quick Info the text Course Title. 3. Right click on Structures in the Web Dynpro Explorer showing the dictionary of your DC and choose Create Structure. Enter the name Course and the package com.sap.training.groupXX.structures. Create an element ID of simple type CourseID and an element TITLE of simple type CourseTitle. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 199
    • Unit 5: Web Dynpro Context Manipulation JA450 Task 2: Create a new context node called Courses of cardinality 0..n in the component controller bound to the dictionary structure Course using all elements. Move the context node Students as child node to the node Courses. Map the node Courses without its attributes to InputView, OutputView and TableView. For each of the views move also their context node Students as child node to the node Courses adhering the context mapping. Reestablish the data binding of the UI elements to the moved context node Students. 1. Right click on the context root node of the component controller and choose New -> Node... selecting Structure Binding. Choose the dictionary structure Course selecting all elements. Give the node the name Courses and the attribute for element TITLE the name Title. 2. Copy and paste the context node Students as child node of node Courses. Delete the old node Students and rename the new node Students_1 to Students. 3. Right click on the context root node in the InputView and choose New -> Node... selecting Mapping. Choose the context node Courses selecting no attributes or child nodes. 4. Repeat the second step of this task for the InputView. Right click on the new node Students and Edit Context Mapping... selecting the node Students of the component controller including all attributes. 5. Repeat the third and fourth step of this task for the OutputView. In addition bind each UI element formally bound to the old node Students to the new node under Courses by clicking on Bind in the respective UI property. For InputFields this would be the property value, for TextViews property text, for the DateNavigator firstSelectedDate, lastSelectedDate and startsWith. 6. Repeat the third and fourth step of this task also for the TableView. In addition right click in the Outline on the table and choose Create Binding. Select the new node Students including all of its attributes and finish. Task 3: Create a new viewset in the navigation of the StudentWindow having two rows and one column . Create a new view called CourseView in the upper cell of the viewset setting it as default. Move the MainView with all sub-views in the lower cell. 1. Go to the navigation of the StudentWindow and choose GridLayout from the menu on the right. Click in the navigation pane and set the viewset properties columns to 1 and default to true. 2. Choose Embed new View from the menu on the right and click in the upper cell of the viewset. Give the view the name CourseView. Continued on next page 200 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes 3. Drag & drop the MainView in the lower cell of the viewset setting it to default. Task 4: Map the context node Courses including its attributes but without node Students from the component controller to the context of CourseView. Create a new node called UIProperty having two attributes Enabled and ReadOnly both of type boolean. 1. Open the Data Modeler and choose Create Data Link from the menu on the right. Draw a line from CourseView to the component controller. Drag & drop the context node Courses on the left selecting the attributes ID and Title. 2. Go to the context of the CourseView and right click on the context root node. Choose New -> Node.. selecting Manually and entering the name to UIProperty. Set the Collection Cardinality to 1..1. 3. Right click on the context node UIProperty and choose New -> Attribute... selecting Manually. Enter the name Enabled and select the type boolean. 4. Repeat the last step adding the attribute ReadOnly to the node UIProperty. Task 5: Create a table in the layout of CourseView consisting of the heading Courses and a ToolBar. The table should have two rows for the context attributes ID and Title of the node Courses. The ToolBar offers two buttons on the left called NewButton and DeleteButton and one ToggleButton on the right all having a suitable icon. Bind the property enabled of the two buttons on the left to the context attribute Enabled and the property readOnly of the editor UI elements of the table to attribute ReadOnly. 1. Delete the DefaultTextView in the layout of the CourseView. Right click on the RootElement in the Outline and Apply Template choosing Table. Select the context node Courses including all attributes and change the editor elements to InputField. Bind the property readOnly of both InputFields to the context attribute ReadOnly 2. Right click on the table in the Outline and Insert -> Header with text Courses. Right click again on the table and Insert -> ToolBar. Right click on the ToolBar and Insert ToolBarItem... twice, one for the ToolBarButton NewButton and one for the ToolBarButton DeleteButton. Right click again on the ToolBar and Insert ToolBarRightItem... for the ToolBarToggleButton ToggleButton. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 201
    • Unit 5: Web Dynpro Context Manipulation JA450 3. Bind the property enabled of the NewButton and DeleteButton to the context attribute Enabled. Create the action New for the NewButton using the text New and the icon ~sapicons/s_b_crea.gif. Create the action Delete for the DeleteButton using the text Delete and the icon ~sapicons/s_b_del.gif. 4. Bind the property checked of the ToggleButton to the context attribute ReadOnly and set the properties imageSource and checkedImageSource to ~sapicons/s_b_dpch.gif. Create the action Toggle for the ToggleButton having no text or icon. Task 6: Implement the actions for the buttons NewButton, DeleteButton and ToggleButton of the CourseView. The NewButton should create a new course, the DeleteButton deletes a course and the ToggleButton toggles the values of the attributes Enabled and ReadOnly for the UI. In addition extend the coding of the method onActionSave() of the InputView for not getting an exception when trying to save a student to a not existing course. 1. In the method onActionNew() call the context method createAndAddCoursesElement(). 2. In the method onActionDelete() determine if an element of the node Courses has the lead selection by using getLeadSelection() and remove it from the node by using removeElement(). 3. In the method onActionToggle() set the value of the context attribute Enabled to false if the value is true and vice versa by using currentUIPropertyElement(). In the method wdDoInit() set the value to true. 4. Surround the existing code in the method onActionSave() of the InputView with an If-clause checking for an existing lead selection in the context node Courses by using nodeCourses().getLeadSelection(). Task 7: Deploy new archive and run your application StudentApp. 1. 202 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes Solution 13: Dependent Context Nodes Task 1: Create the dictionary simple type CourseID of type string with a maximum length of 6 and the simple type CourseTitle also of type string. Maintain the text objects appropriately. Create a new dictionary structure called Course having the two elements ID and Title referencing the defined simple types. 1. Right click on Simple Types in the Web Dynpro Explorer showing the dictionary of your DC and choose Create Simple Type. Enter the name CourseID and the package com.sap.training.groupXX.simpletypes. Set a description and define the Maximum Length to 6. Field Label and Column Label have the text ID and the Quick Info the text Course ID. a) 2. Repeat the last step creating the simple type CourseTitle in the same package with no length restriction. Field Label and Column Label have the text Title and the Quick Info the text Course Title. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Right click on Structures in the Web Dynpro Explorer showing the dictionary of your DC and choose Create Structure. Enter the name Course and the package com.sap.training.groupXX.structures. Create an element ID of simple type CourseID and an element TITLE of simple type CourseTitle. a) Perform as seen in the demonstration of your trainer. Task 2: Create a new context node called Courses of cardinality 0..n in the component controller bound to the dictionary structure Course using all elements. Move the context node Students as child node to the node Courses. Map the node Courses without its attributes to InputView, OutputView and TableView. For each of the views move also their context node Students as child node to the node Courses adhering the context mapping. Reestablish the data binding of the UI elements to the moved context node Students. 1. Right click on the context root node of the component controller and choose New -> Node... selecting Structure Binding. Choose the dictionary structure Course selecting all elements. Give the node the name Courses and the attribute for element TITLE the name Title. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 203
    • Unit 5: Web Dynpro Context Manipulation 2. Copy and paste the context node Students as child node of node Courses. Delete the old node Students and rename the new node Students_1 to Students. a) 3. Perform as seen in the demonstration of your trainer. Repeat the third and fourth step of this task for the OutputView. In addition bind each UI element formally bound to the old node Students to the new node under Courses by clicking on Bind in the respective UI property. For InputFields this would be the property value, for TextViews property text, for the DateNavigator firstSelectedDate, lastSelectedDate and startsWith. a) 6. Perform as seen in the demonstration of your trainer. Repeat the second step of this task for the InputView. Right click on the new node Students and Edit Context Mapping... selecting the node Students of the component controller including all attributes. a) 5. Perform as seen in the demonstration of your trainer. Right click on the context root node in the InputView and choose New -> Node... selecting Mapping. Choose the context node Courses selecting no attributes or child nodes. a) 4. JA450 Perform as seen in the demonstration of your trainer. Repeat the third and fourth step of this task also for the TableView. In addition right click in the Outline on the table and choose Create Binding. Select the new node Students including all of its attributes and finish. a) Perform as seen in the demonstration of your trainer. Task 3: Create a new viewset in the navigation of the StudentWindow having two rows and one column . Create a new view called CourseView in the upper cell of the viewset setting it as default. Move the MainView with all sub-views in the lower cell. 1. Go to the navigation of the StudentWindow and choose GridLayout from the menu on the right. Click in the navigation pane and set the viewset properties columns to 1 and default to true. a) 2. Perform as seen in the demonstration of your trainer. Choose Embed new View from the menu on the right and click in the upper cell of the viewset. Give the view the name CourseView. a) Perform as seen in the demonstration of your trainer. Continued on next page 204 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes 3. Drag & drop the MainView in the lower cell of the viewset setting it to default. a) Perform as seen in the demonstration of your trainer. Task 4: Map the context node Courses including its attributes but without node Students from the component controller to the context of CourseView. Create a new node called UIProperty having two attributes Enabled and ReadOnly both of type boolean. 1. Open the Data Modeler and choose Create Data Link from the menu on the right. Draw a line from CourseView to the component controller. Drag & drop the context node Courses on the left selecting the attributes ID and Title. a) 2. Go to the context of the CourseView and right click on the context root node. Choose New -> Node.. selecting Manually and entering the name to UIProperty. Set the Collection Cardinality to 1..1. a) 3. Perform as seen in the demonstration of your trainer. Right click on the context node UIProperty and choose New -> Attribute... selecting Manually. Enter the name Enabled and select the type boolean. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Repeat the last step adding the attribute ReadOnly to the node UIProperty. a) Perform as seen in the demonstration of your trainer. Task 5: Create a table in the layout of CourseView consisting of the heading Courses and a ToolBar. The table should have two rows for the context attributes ID and Title of the node Courses. The ToolBar offers two buttons on the left called NewButton and DeleteButton and one ToggleButton on the right all having a suitable icon. Bind the property enabled of the two buttons on the left to the context attribute Enabled and the property readOnly of the editor UI elements of the table to attribute ReadOnly. 1. Delete the DefaultTextView in the layout of the CourseView. Right click on the RootElement in the Outline and Apply Template choosing Table. Select the context node Courses including all attributes and change the editor elements to InputField. Bind the property readOnly of both InputFields to the context attribute ReadOnly a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 205
    • Unit 5: Web Dynpro Context Manipulation 2. Right click on the table in the Outline and Insert -> Header with text Courses. Right click again on the table and Insert -> ToolBar. Right click on the ToolBar and Insert ToolBarItem... twice, one for the ToolBarButton NewButton and one for the ToolBarButton DeleteButton. Right click again on the ToolBar and Insert ToolBarRightItem... for the ToolBarToggleButton ToggleButton. a) 3. Perform as seen in the demonstration of your trainer. Bind the property enabled of the NewButton and DeleteButton to the context attribute Enabled. Create the action New for the NewButton using the text New and the icon ~sapicons/s_b_crea.gif. Create the action Delete for the DeleteButton using the text Delete and the icon ~sapicons/s_b_del.gif. a) 4. JA450 Perform as seen in the demonstration of your trainer. Bind the property checked of the ToggleButton to the context attribute ReadOnly and set the properties imageSource and checkedImageSource to ~sapicons/s_b_dpch.gif. Create the action Toggle for the ToggleButton having no text or icon. a) Perform as seen in the demonstration of your trainer. Task 6: Implement the actions for the buttons NewButton, DeleteButton and ToggleButton of the CourseView. The NewButton should create a new course, the DeleteButton deletes a course and the ToggleButton toggles the values of the attributes Enabled and ReadOnly for the UI. In addition extend the coding of the method onActionSave() of the InputView for not getting an exception when trying to save a student to a not existing course. 1. In the method onActionNew() call the context method createAndAddCoursesElement(). a) 2. In the method onActionDelete() determine if an element of the node Courses has the lead selection by using getLeadSelection() and remove it from the node by using removeElement(). a) 3. See source code extract of the sample solution. See source code extract of the sample solution. In the method onActionToggle() set the value of the context attribute Enabled to false if the value is true and vice versa by using currentUIPropertyElement(). In the method wdDoInit() set the value to true. a) See source code extract of the sample solution. Continued on next page 206 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes 4. Surround the existing code in the method onActionSave() of the InputView with an If-clause checking for an existing lead selection in the context node Courses by using nodeCourses().getLeadSelection(). a) See source code extract of the sample solution. Task 7: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result CourseView public void wdDoInit() { //@@begin wdDoInit() wdContext.currentUIPropertyElement().setEnabled(true); //@@end } public void onActionNew( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionNew(ServerEvent) wdContext.createAndAddCoursesElement(); //@@end } public void onActionDelete( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionDelete(ServerEvent) ICoursesNode coursesNode = wdContext.nodeCourses(); if (coursesNode.getLeadSelection() != IWDNode.NO_SELECTION) { coursesNode.removeElement(wdContext.currentCoursesElement()); } //@@end } public void onActionToggle( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) Continued on next page 2008 © 2008 SAP AG. All rights reserved. 207
    • Unit 5: Web Dynpro Context Manipulation JA450 { //@@begin onActionToggle(ServerEvent) wdContext.currentUIPropertyElement().setEnabled( !wdContext.currentUIPropertyElement().getReadOnly()); //@@end } InputView public void onActionSave( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSave(ServerEvent) if (wdContext.nodeCourses().getLeadSelection() != IWDNode.NO_SELECTION) { IStudentsElement studentsElement = wdContext .createAndAddStudentsElement(); WDCopyService.copyCorresponding(wdContext .currentNewStudentElement(), studentsElement); } //@@end } 208 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dependent Nodes Lesson Summary You • • • 2008 should now be able to: explain the properties of the node categories. understand the purpose of singleton nodes. implement supply functions. © 2008 SAP AG. All rights reserved. 209
    • Unit Summary JA450 Unit Summary You should now be able to: • use shortcut variables for accessing different parts of Web Dynpro. • choose the correct place for your coding in the controller implementation. • describe the steps of server round trip. • access the elements in the context. • use the benefits of the collection cardinality. • copy elements between nodes by using the WDCopyService. • create and bind a Table UI element to the context. • handle the selection cardinality of context nodes. • delete elements from a context node. • interoperate between controllers. • implement calculated attributes. • decide if a setter-method is possible. • explain the properties of the node categories. • understand the purpose of singleton nodes. • implement supply functions. 210 © 2008 SAP AG. All rights reserved. 2008
    • Unit 6 Web Dynpro Models Unit Overview This chapter introduces the models on the example of a Web Service model. The second part then shows how to use multiple components in one application using a model component. Three exercises are available. Unit Objectives After completing this unit, you will be able to: • • • • • • • • • • explain the purpose of a model. decide between models used in your application. explain the benefits of a web service. use a model to consume a web service. understand the structure of a Web Dynpro model. define model usages in Web Dynpro components. execute backend services via models. use multiple components in one application. map data between different components. implement a model component. Unit Contents Lesson: Models .................................................................212 Lesson: Web Service Model...................................................217 Exercise 14: Defining Web Service Model ..............................235 Exercise 15: Using Web Service Model .................................239 Lesson: Model Component ....................................................247 Exercise 16: Develop Model Component ...............................255 2008 © 2008 SAP AG. All rights reserved. 211
    • Unit 6: Web Dynpro Models JA450 Lesson: Models Lesson Overview This lesson explains the purpose of models showing the three main types aRFC, aWS and EJB Model. Lesson Objectives After completing this lesson, you will be able to: • • explain the purpose of a model. decide between models used in your application. Business Example You want consume data of a backend service in your application by using models. Model Overview In the MVC design paradigm the model represents the proxy objects for accessing a backend service. Often the business data for an application is stored in a database. The model does not implement SQL coding or some other way to access the data in the database. There must already be a service available implementing the database access. The model then connects the application to this backend service. 212 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Models Figure 90: Common Model Interface The model decouples the application from the backend defining a Common Model Interface (CMI). Web Dynpro controller access every model by using the CMI in the same way for all types of models. Each model is generated especially for the relevant backend service implementing proxy classes with attributes and methods as defined by the service interface. Models are defined outside of Web Dynpro components to make them usable in multiple applications. Normally a there exists only one model instance for one backend service to define a static interface for multiple applications. 2008 © 2008 SAP AG. All rights reserved. 213
    • Unit 6: Web Dynpro Models JA450 Figure 91: Supported Models Depending on the release of Web Dynpro, there are different types of models available. Independent from that there are three main services consumable in every release: • • • Remote enabled function module of an ABAP server Web service available via UDDI or WSDL Enterprise Java Bean of a Java server For Web Dynpro on SAP NetWeaver 7.1 technology a model wizard is available for all three types. Each backend service will have its own classes generated for it: Adaptive Remote Function Call Model The Adaptive Remote Function Call (aRFC) is the best way accessing the data of an ABAP server. It is designed to work with huge data volumes stored in the database attached to an ABAP server. The adaptive part of the model makes it possible to access different ABAP releases with minor changes in the interface of the function module with the same model instance. This is possible because the model also has metadata available at runtime which is compared to metadata generated at design time. This metadata is available as dictionary types which can be used in the Web Dynpro 214 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Models Adaptive Web Service Model The Adaptive Web Service (aWS) makes it possible to consume backend services regardless of the technology providing the web service. This is the key advantage of the web service standard. The push-back for this independence is the character of data transfer making it less performing the more data is transferred. The adaptive part of the aWS Model makes it possible to identify differences in the web service interface at runtime compared to the interface which was available at design time. Unlike the aRFC Model no metadata is available for the application because the web service standard does not offer metadata information. Enterprise Java Bean Model The Enterprise Java Bean (EJB) Model is new for 7.1. In former releases the Java Bean Model has to be used to access EJBs but now they can be consumed directly by an own model. The EJB Model is the best way to access an EJB on a Java server and therefore the best way accessing data available in a database reachable by a Java server. It does not yet offer adaptive functionality. Hint: Choose your model wisely concerning about type of backend, data amount transferred and network architecture used for accessing (e.g. firewalls, tunnelling etc.). Data access is the bottle neck for quite every application. 2008 © 2008 SAP AG. All rights reserved. 215
    • Unit 6: Web Dynpro Models JA450 Lesson Summary You should now be able to: • explain the purpose of a model. • decide between models used in your application. 216 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Lesson: Web Service Model Lesson Overview This lesson shows how to generate a web service model as an example for all model types including information about the web service standard and how to implement the model usage in Web Dynpro. Lesson Objectives After completing this lesson, you will be able to: • • • • • explain the benefits of a web service. use a model to consume a web service. understand the structure of a Web Dynpro model. define model usages in Web Dynpro components. execute backend services via models. Business Example You want to consume a web service in your Web Dynpro application to show business data on your screen provided by the backend service. Web Service Web services are web-based interfaces that can be integrated into a company’s business scenarios based on open and commonly accepted standards. The process of communication between technical independent applications can be simplified by using web services. 2008 © 2008 SAP AG. All rights reserved. 217
    • Unit 6: Web Dynpro Models JA450 Figure 92: Web Service Facts Web services enable you to combine functions implemented in different software components into a single process. Web services are self-contained, modularized, executable entities that are accessible over open protocols. Web services: • • • • • use open protocols for communication (e.g. HTTP, SMTP etc.). use XML schema for the description of their messages. process XML messages framed by using the Simple Object Access Protocol (SOAP). provide endpoints using the Web Service Definition Language (WSDL). can be discovered using the Universal Description, Discovery and Integration (UDDI). In this way, web services can be published, discovered and accessed across a network. For a caller or sender, a Web service is a black box that may require input and delivers a result. 218 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 93: Web Service Paradigm The Web service paradigm consists of the web service provider and the web service consumer. The Web service provider wants to develop an application (e.g. a credit limit check) that he wants to make available to a wider community. To do so, he proceeds as follows: • • First he creates the corresponding web service. In the process of web service creation, the system produces a WSDL document. This is an XML-based description of the interface of the service, containing things like – – – the parameters expected the location of the web service supported protocols. The provider publishes the information on this service in a repository or directory, where it can easily be found and accessed by a large number of people. The most commonly used directory is UDDI. It works like a phone book where you can find information about the company that provides the web service, about what kind of service is offered and the WSDL, or rather a link to it, is also stored in the UDDI entry. So in short: info about the company, the service and the technical requirements. 2008 © 2008 SAP AG. All rights reserved. 219
    • Unit 6: Web Dynpro Models JA450 The web service consumer wants to use an application (e.g. a credit limit check): • • Search in the repository for all credit limit check applications Build a web service client using the WSDL of the web service he wants to use The service runs at the provider’s side. Security settings like authentication or billing for services can also all be managed by the provider. Defining Model The way creating a model is for all model types identical. The only difference is how the backend service is accessed and what is generated for the respective service. Models can only be created in Web Dynpro DC projects but there is no need for a component to exist. So the model definition and the Web Dynpro application can be separated in different DCs. Figure 94: Create Model The first step for creating a model is to choose the type of model. Depending on the release of Web Dynpro, the list of available types can differ from another. In this course we choose the aWS Model. For all model types applies that the name of the model should be in the form <Data/ServiceName>Model and all models must live in its own Java package. If you choose a package already consisting of some files, you are not allowed to generate the model. 220 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 95: Access Web Service For a web service the Web Service Definition Language (WSDL) file is needed. There are several ways possible to find the respective WSDL file. The easiest way is to copy the link leading to the WSDL file from the service provider. Note: The aWS Model offers the possibility to use logical names for accessing the WSDL file. These references are defined in the NetWeaver Application Server by the administrator using the NetWeaver Administrator tool. The names spaces and model classes which will be generated can be changed in the last step of the model wizard. Normally the web service should be defined in a meaning way so that a change here is normally not needed. 2008 © 2008 SAP AG. All rights reserved. 221
    • Unit 6: Web Dynpro Models JA450 Figure 96: Generation Summary After finishing the wizard the model generator starts creating everything found in the web service interface. If problems rise during generation, they are put into the import log presented at the end of the generation. The model classes inside a model can be separated into three different types: Request/Input Depending on the model type these classes are called request or input classes. They have the purpose to set data for accessing the backend server and offer the method to start the service call. Response/Output Depending on the model type these classes are called response or output classes. They are instantiated when the backend service is called and save the result data of it. Named Complex/Structure Depending on the model type these classes are called named complex or structure classes. They define the structure of the data used in the service call depending on the interface of the backend service. 222 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 97: Model Classes The number and types of classes generated depends on the backend service. For accessing one backend service there will be one request class, one response class and as many named complex classes as defined in the service interface. Scalar parameters of the service interface are defined as properties of model classes. They store simple values of elemental types like String or Long. Complex structures of data like tables are defined as named complex classes offering a property for every field of the table. 2008 © 2008 SAP AG. All rights reserved. 223
    • Unit 6: Web Dynpro Models JA450 Figure 98: Model Classes Properties The named complex classes are used in other named complex classes to define a table in combination or directly in request and response classes to define a single data set. These references are called relations between model classes and set the multiplicity of the connection between the classes. 224 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 99: Model Classes References The root of all relations is the request class. It references named complex classes for accessing the service interface and the response class to show the result of the service call. The method execute() is provided by the request class calling the backend service and sending the data stored in its properties or referenced named complex classes to the backend. The Web Dynpro Framework (WDF) will instantiated the related response class and set the data received by the service in the properties and referenced named complex classes of the response object. You can combine multiple backend services in one model having then multiple request and response classes. Named complex classes will be reused in the different service calls if their structure is identical. Hint: You should only combine those backend services in one model working on the same data like adding an employee, deleting one or getting a list of all employees. For an ABAP system these function modules are normally combined in one function group and for a Java system an EJB offers multiple service methods for working with a set of data. Using Model Because models are defined outside of Web Dynpro components, they must be referenced by a component to make it usable inside of the controllers. Every component holds its own list of used models. 2008 © 2008 SAP AG. All rights reserved. 225
    • Unit 6: Web Dynpro Models JA450 Figure 100: Model Usage A model usage can be defined via the Web Dynpro explorer or the data modeler. When embedding a model the reference called model usage is generated by the Web Dynpro tools what makes the model classes accessible by the controllers of the component. Caution: Although possible, never consume a model in a view controller. This breaks the MVC design paradigm and makes the component less maintainable. In order to use the model data declarative in Web Dynpro the model classes should be bound to a context. By drawing a data link in the data modeler the model binding is applied in the same way as with context mapping. 226 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 101: Service Controller The functionality of Apply Template offers the wizard Service Controller to not only bind the model to a controller but also generate some coding needed for working with a model. The wizard will perform the following actions: • • • • Apply model binding between model and controller Create context nodes and attributes as selected by the developer Generate coding for initializing the new context nodes Generate a method for calling the model The first step of the wizard is selecting the executable model class of the used model. Request classes are the executable model classes offering the method execute(). 2008 © 2008 SAP AG. All rights reserved. 227
    • Unit 6: Web Dynpro Models JA450 Figure 102: Select Model In the next step the wizard offers all available model classes to be generated as context nodes in the controller. The developer can decide which part of the backend service should be accessed by selecting the relevant nodes. Relations of model classes to other ones will be generated as child nodes using the multiplicity of the relation as collection cardinality of the nodes. The attributes of each node depend on the properties defined in the model classes. The complete model binding is shown in the same way as context mapping between controllers. 228 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 103: Model Binding Normally the context will consist of one context node under the context root node representing the request class followed by two child nodes, one for the request data and one representing the response class. The structure underneath differ depending on the model structure. Note: If multiple model request nodes should be used in one context, the standard names for response and return nodes must be renamed because all node names must be unique within the scope of the controller context. To be able to save data in the request node it must be initialized in the method wdDoInit() of the controller. There is no generated typed context API available to create elements in the context. Instead the model classes are instantiated directly and added to the context nodes by using the method bind(). So to be correct, the model classes themselves are the typed context API. 2008 © 2008 SAP AG. All rights reserved. 229
    • Unit 6: Web Dynpro Models JA450 Figure 104: Initialize Context The Service Controller template generates coding for instantiating the model and the request class adding it to the context. This can be performed because it is the same for every context node using model binding. But the wizard can not distinguish between nodes used as response and nodes used to send data to the backend service. Therefore the coding should be extended also instantiating the named complex classes used for the request binding them to the respective context nodes. Hint: Only for simple models the standard implementation is sufficient. In the majority of cases the developer has to extend the generated coding. In the last step of the wizard you can define a method for executing the model. The proposed name is normally sufficient. The wizard will then generate everything needed for the model execution to work correctly. 230 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 105: Call Model The model execution itself is just calling the method execute() of the model object. But to make the result available in the context, the method invalidate() of the response node must be called in addition. Invalidating a context node in Web Dynpro means that the data in the node is no longer valid and must be replaced. The WDF will then call the supply methods to repopulate the node. For a model this means that the data stored in the model object is transferred in the context node using the model binding. Caution: For a context node having no supply methods or bindings defined, invalidating means deleting all elements. Calling a backend service often means to access a function in another system. There could be plenty of problems accessing the system via the network, which are not in the sphere of influence of Web Dynpro. Therefore the exception handling should be implemented suitable to the service called. 2008 © 2008 SAP AG. All rights reserved. 231
    • Unit 6: Web Dynpro Models JA450 Figure 106: Method Calls The model data and functionality should be centralized in a non-visual controller. There should be a separate custom controller defining and initializing the context nodes as well as implementing the method for executing the model. View controllers can then map the context and call the model execution method. At runtime there will be five steps for an application interacting with a model: 1. 2. 3. 4. 5. 232 The method wdDoInit() initializes the context at start-up. The user presses a button calling the respective action handler. The action handler calls the method generated for model execution. The model execution method executes the model. The model execution method invalidates the response node. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Figure 107: Data Flow By invalidating the response node the business data is transported from the model object to the custom controller’s context. The view controller‘s context is mapped to the context of the custom controller and displays the data in the UI elements bound to its context nodes and attributes. 2008 © 2008 SAP AG. All rights reserved. 233
    • Unit 6: Web Dynpro Models 234 JA450 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Exercise 14: Defining Web Service Model Exercise Objectives After completing this exercise, you will be able to: • look for web services in the NWAS Java. • create an adaptive web service model. Business Example You want the user to be able to search for an employee, who can be saved as a student for a course. The information about employees is already available as web service. For the first step you create an adaptive web service model. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~model1XX with XX as your group number. Template training.sap.com~context8 Solution training.sap.com~model1 Task 1: Search for the Web Service for the EmployeeBean on your server and test it. Save the WSDL-URL of the web service for the next task. 1. Open the web browser and enter the URL http://<yourServer>:50000. Click on the Web Services Navigator and search for the entry for EmployeeBean. Select the entry, click on the method getEmployeeById and choose Execute for an employeeId between 1 - 500. 2. Enter other values for the employeeId for further testing. At the end click on the WSDL URL and copy it to the clipboard. Task 2: Create the adaptive web service model EmployeeModel in the package com.sap.training.groupXX.employeemodel in your DC using the WSDL URL of the Web Service for EmployeeBean. 1. Right click in the Web Dynpro Explorer on Models and Create Model. Choose an Adaptive Web Service Model. 2. Enter the name EmployeeModel and the package com.sap.training.groupXX.employeemodel. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 235
    • Unit 6: Web Dynpro Models 3. JA450 Use no logical destinations and paste the WSDL URL from the clipboard to the field WSDL. Continue the wizard until finished. Task 3: Familiarize yourself with the generated model examining the model classes. 1. 236 Expand the tree of the EmployeeModel in the Web Dynpro Explorer. Double click on the Request_GetEmployeeById model class and follow the Relations from one model class to another examining their Properties. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Solution 14: Defining Web Service Model Task 1: Search for the Web Service for the EmployeeBean on your server and test it. Save the WSDL-URL of the web service for the next task. 1. Open the web browser and enter the URL http://<yourServer>:50000. Click on the Web Services Navigator and search for the entry for EmployeeBean. Select the entry, click on the method getEmployeeById and choose Execute for an employeeId between 1 - 500. a) 2. Perform as seen in the demonstration of your trainer. Enter other values for the employeeId for further testing. At the end click on the WSDL URL and copy it to the clipboard. a) Perform as seen in the demonstration of your trainer. Task 2: Create the adaptive web service model EmployeeModel in the package com.sap.training.groupXX.employeemodel in your DC using the WSDL URL of the Web Service for EmployeeBean. 1. Right click in the Web Dynpro Explorer on Models and Create Model. Choose an Adaptive Web Service Model. a) 2. Enter the name EmployeeModel and the package com.sap.training.groupXX.employeemodel. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Use no logical destinations and paste the WSDL URL from the clipboard to the field WSDL. Continue the wizard until finished. a) Perform as seen in the demonstration of your trainer. Task 3: Familiarize yourself with the generated model examining the model classes. 1. Expand the tree of the EmployeeModel in the Web Dynpro Explorer. Double click on the Request_GetEmployeeById model class and follow the Relations from one model class to another examining their Properties. a) 2008 Perform as seen in the demonstration of your trainer. © 2008 SAP AG. All rights reserved. 237
    • Unit 6: Web Dynpro Models 238 JA450 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Exercise 15: Using Web Service Model Exercise Objectives After completing this exercise, you will be able to: • consume a model in a custom controller. Business Example You want the user to be able to search for an employee, who can be saved as a student for a course. The information about employees is already available as adaptive web service model. For the second step you consume the model in your application. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~model2XX with XX as your group number. Template training.sap.com~model1 Solution training.sap.com~model2 Task 1: Add the EmployeeModel to the Used Models of the component and create a custom controller called EmployeeCust in your component. Use the wizard Service Controller on the controller EmployeeCust for the EmployeeModel and change the generated coding in the method wdDoInit() to initialize the complete request node. 1. Go to the Data Modeler of your component, choose Embed Model in the menu on the right, click in the modeler pane and select EmployeeModel. 2. Choose Create Custom Controller in the menu on the right and set its name to EmployeeCust. 3. Right click on the controller EmployeeCust and Apply Template choosing Service Controller. Select Request_GetEmployeeById from the EmployeeModel and tag all nodes and attributes. 4. Change the implementation in the method wdDoInit() to save the reference to the request object of type Request_GetEmployeeById in a variable before binding it to the context. 5. Create a new instance of the sub node GetEmployeeById and set it for the request object by using setGetEmployeeById() before binding it to the context. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 239
    • Unit 6: Web Dynpro Models JA450 Task 2: Copy the context node NewStudent from the InputView to EmployeeCust and extend the implementation of the method executeGetEmployeeById() for copying the result of the model call to the context node NewStudent. 1. Go to the context of the InputView, copy the node NewStudent and paste it in the context of the EmployeeCust. 2. Use the WDCopyService to copy the corresponding attributes of the current Return element to the current NewStudent element after the invalidation of the response node. Task 3: Map the existing context node NewStudent of the InputView to the node NewStudent of the EmployeeCust and map a new context node called GetEmployeeById including the attribute EmployeeId from the EmployeeCust. 1. In the Data Modeler of your component choose Create Data Link from the menu on the right and drag a line from the InputView to the EmployeeCust. 2. Drag the node NewStudent from left to right on the existing node NewStudent tagging all attributes. Then drag the node GetEmployeeById from right to left on the context root node and select the attribute EmployeeId. Task 4: Create a label and input field for the new attribute EmployeeId above the existing input mask separated by a HorizontalGutter. Create a SearchButton next to the new input field calling the method executeGetEmployeeById() of the EmployeeCust. 1. Right click on the transparent container in the Outline of the InputView and Apply Template choosing Form. Select the attribute EmployeeId and finish. Set the text of the label to Employee ID and the length of the input field to 20. 2. Right click on the transparent container and Apply Template choosing Action Button. Give the action the name and text Search and the button the id SearchButton. Generate the coding for calling the method executeGetEmployeeById() of the EmployeeCust. 3. Right click on the transparent container and Insert Child... choosing a HorizontalGutter. Set its layoutData to MatrixHeadData and the colSpan to 2. 4. Move the label and input field for EmployeeId, the SearchButton and the HorizontalGutter to the top of the transparent container. Select the input field and the SearchButton and choose from the context menu Wrap With -> Transparent Container. Continued on next page 240 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model Task 5: Deploy new archive and run your application StudentApp. 1. 2008 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 241
    • Unit 6: Web Dynpro Models JA450 Solution 15: Using Web Service Model Task 1: Add the EmployeeModel to the Used Models of the component and create a custom controller called EmployeeCust in your component. Use the wizard Service Controller on the controller EmployeeCust for the EmployeeModel and change the generated coding in the method wdDoInit() to initialize the complete request node. 1. Go to the Data Modeler of your component, choose Embed Model in the menu on the right, click in the modeler pane and select EmployeeModel. a) 2. Choose Create Custom Controller in the menu on the right and set its name to EmployeeCust. a) 3. Perform as seen in the demonstration of your trainer. Change the implementation in the method wdDoInit() to save the reference to the request object of type Request_GetEmployeeById in a variable before binding it to the context. a) 5. Perform as seen in the demonstration of your trainer. Right click on the controller EmployeeCust and Apply Template choosing Service Controller. Select Request_GetEmployeeById from the EmployeeModel and tag all nodes and attributes. a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Create a new instance of the sub node GetEmployeeById and set it for the request object by using setGetEmployeeById() before binding it to the context. a) See source code extract of the sample solution. Task 2: Copy the context node NewStudent from the InputView to EmployeeCust and extend the implementation of the method executeGetEmployeeById() for copying the result of the model call to the context node NewStudent. 1. Go to the context of the InputView, copy the node NewStudent and paste it in the context of the EmployeeCust. a) Perform as seen in the demonstration of your trainer. Continued on next page 242 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model 2. Use the WDCopyService to copy the corresponding attributes of the current Return element to the current NewStudent element after the invalidation of the response node. a) See source code extract of the sample solution. Task 3: Map the existing context node NewStudent of the InputView to the node NewStudent of the EmployeeCust and map a new context node called GetEmployeeById including the attribute EmployeeId from the EmployeeCust. 1. In the Data Modeler of your component choose Create Data Link from the menu on the right and drag a line from the InputView to the EmployeeCust. a) 2. Perform as seen in the demonstration of your trainer. Drag the node NewStudent from left to right on the existing node NewStudent tagging all attributes. Then drag the node GetEmployeeById from right to left on the context root node and select the attribute EmployeeId. a) Perform as seen in the demonstration of your trainer. Task 4: Create a label and input field for the new attribute EmployeeId above the existing input mask separated by a HorizontalGutter. Create a SearchButton next to the new input field calling the method executeGetEmployeeById() of the EmployeeCust. 1. Right click on the transparent container in the Outline of the InputView and Apply Template choosing Form. Select the attribute EmployeeId and finish. Set the text of the label to Employee ID and the length of the input field to 20. a) 2. Right click on the transparent container and Apply Template choosing Action Button. Give the action the name and text Search and the button the id SearchButton. Generate the coding for calling the method executeGetEmployeeById() of the EmployeeCust. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Right click on the transparent container and Insert Child... choosing a HorizontalGutter. Set its layoutData to MatrixHeadData and the colSpan to 2. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 243
    • Unit 6: Web Dynpro Models 4. JA450 Move the label and input field for EmployeeId, the SearchButton and the HorizontalGutter to the top of the transparent container. Select the input field and the SearchButton and choose from the context menu Wrap With -> Transparent Container. a) Perform as seen in the demonstration of your trainer. Task 5: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result EmployeeCust //@@begin imports import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager; import com.sap.tc.webdynpro.progmodel.api.WDCopyService; import com.sap.training.model2.employeemodel.EmployeeModel; import com.sap.training.model2.employeemodel.GetEmployeeById; import com.sap.training.model2.employeemodel.Request_GetEmployeeById; import com.sap.training.model2.studentcomp.wdp.IPrivateEmployeeCust; //@@end public void wdDoInit() { //@@begin wdDoInit() EmployeeModel model = new EmployeeModel(); Request_GetEmployeeById request = new Request_GetEmployeeById(model); request.setGetEmployeeById(new GetEmployeeById(model)); wdContext.nodeRequest_GetEmployeeById().bind(request); //@@end } public void executeGetEmployeeById( ) { //@@begin executeGetEmployeeById() IWDMessageManager manager = wdComponentAPI.getMessageManager(); try { wdContext.currentRequest_GetEmployeeByIdElement().modelObject() .execute(); wdContext.nodeResponse().invalidate(); WDCopyService.copyCorresponding(wdContext.currentReturnElement(), Continued on next page 244 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Web Service Model wdContext.currentNewStudentElement()); } catch (Exception e) { manager.reportException(e.getMessage()); } //@@end } InputView public void onActionSearch( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSearch(ServerEvent) wdThis.wdGetEmployeeCustController().executeGetEmployeeById(); //@@end } 2008 © 2008 SAP AG. All rights reserved. 245
    • Unit 6: Web Dynpro Models JA450 Lesson Summary You should now be able to: • explain the benefits of a web service. • use a model to consume a web service. • understand the structure of a Web Dynpro model. • define model usages in Web Dynpro components. • execute backend services via models. 246 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Lesson: Model Component Lesson Overview This lesson makes the model centrally available by creating a model component and let other components access its component interface. Lesson Objectives After completing this lesson, you will be able to: • • • use multiple components in one application. map data between different components. implement a model component. Business Example You want reuse your model implementation in multiple components to make it centrally available. Multiple Components The basic building block in Web Dynpro is the component. A Web Dynpro application requires at least one component to start. Components can use other components via the component interface. 2008 © 2008 SAP AG. All rights reserved. 247
    • Unit 6: Web Dynpro Models JA450 Figure 108: Component Interaction Real world applications often use multiple components separating the tasks of the application into smaller reusable units. The component which is started by the application is called root component. Inside the component so called component usage dependencies are defined to access the component interface of other components. The interface controller defines the programmatic interface for accessing the context, methods and events of the child component. The interface views offer access to windows inside of the child component. Each component can focus on a special task like model maintenance, UI structuring or business methods. These are no special components to be defined but just normal components offering their implementation as a kind of service for other components. For example if multiple applications use the same backend data, the model maintenance can be centralized in one component offering the data to other components. 248 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Figure 109: Component Usage A component usage can be defined in the Web Dynpro explorer or in the data modeler. Inside the data modeler you will only have access to the interface controller, the programmatic part of the used component. Inside windows you will have only access to the visual interface in the form of interface views. The MVC design paradigm is still in place. When defining a model usage, the developer can choose between two types of lifecycle for the used component: createOnDemand The component instance is generated and destroyed by the WDF. manual The developer decides when to create or destroy the component instance. If set to manual you will get a NullPointerException when trying to access parts of the used component which is not yet instantiated. Like all other references the instantiated component reference can be distributed between several components. Hint: If multiple components want to access the same instance of a child component, one leading component (usually the root component) should instantiate the child and distribute the reference to the other using components. 2008 © 2008 SAP AG. All rights reserved. 249
    • Unit 6: Web Dynpro Models JA450 Centralize Model Data A good example for a child component is the model component. It exists solely for the purpose to provide an interface to model objects. Every component can be a model component by just implementing model coding inside the component and publishing the data in its interface. Figure 110: Model Component The advantage of a model component is, that the model implementation must only be done once for multiple applications using the same backend service. In addition pre- or post-processing send or received from the model can be performed before publishing the data to the using components. A model component normally has no visual interface concentrating on the model data. Such a component is also known as a faceless component. The parent component consumes the data of the child’s interface controller in a custom controller and distributes it in its controllers. 250 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Figure 111: Interface Controller It is possible to publish directly the context nodes bound to the model in the interface controller. But in order to decouple the parent component from any model interaction, the model data should be copied to a separate node. Thereby it is also possible to process the data in some way during copying like calculating values or formatting the data. The act of publishing a context node in the interface controller is by copying it from the context of the component controller in the context of the interface controller. Changes to one of the contexts must be adapted in the counterpart as well. Only context nodes of the component controller can be copied in the interface controller. 2008 © 2008 SAP AG. All rights reserved. 251
    • Unit 6: Web Dynpro Models JA450 Figure 112: Interface Context Mapping Having the context nodes in the interface controller the context mapping in the parent component works the same as with internal controllers with one difference: The parent controller can not change the context definition of the child in any way. This is because if multiple components use the same interface controller, they must rely on a steady interface in order to work correctly. Only by accessing the child component directly its interface can be changed. It is possible that not the child component acts as the source of data but the parent - although this way is unusual for a model component. In that case the child must define its context nodes as input elements. To do that the property isInputElement must be set to true. Note: When defining context nodes as input elements, the defining component is no longer usable stand-alone. There must always be a parent component supplying the data for the interface. Centralize Model Execution Beside the model data the model component also needs to offer a functionality to start the model execution. This can be event or a method defined in the interface controller of the model component. 252 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Figure 113: Call Model via Interface - Diagram Like for the data the parent component should not interact directly with the model but call a method doing so. This method is implemented in the component controller of the model component and its signature copied to the interface controller. It is also possible to copy an event to the interface controller, which is registered to an event handler of the component controller performing the model execution. In the following picture the example for a method is shown and how it could be implemented. 2008 © 2008 SAP AG. All rights reserved. 253
    • Unit 6: Web Dynpro Models JA450 Figure 114: Call Model via Interface - Coding In some way the method for starting the model execution is called for example by an action handler. The method then calls the interface method supplied by the model component and performs afterwards additional coding to publish the data in the parent component. The interface method then collects the data to be sent to the model saving it in the request node and calls the model execution method. The implementation of the execution method has been extended to copy the model result to the context node published in the interface. From here on the WDF takes care about distributing the data in all mapped nodes in all components. Hint: For error messages to be shown on the UI the exceptions of the model component should also be published as references in the interface controller. 254 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Exercise 16: Develop Model Component Exercise Objectives After completing this exercise, you will be able to: • centralize model administration in a model component. • use context mapping spanning component borders. • call methods of other Web Dynpro components. Business Example You want to change the architecture of you application separating the model administration from the business application. The user should not see any difference when using the application. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~model3XX with XX as your group number. Template training.sap.com~model2 Solution training.sap.com~model3 Task 1: Create a new faceless component called ModelComp using the model EmployeeModel. 1. Right click on Components in the Web Dynpro Explorer and choose Create Component. Enter the name ModelComp and tag only Used Models. 2. Add... a used model and select EmployeeModel. Finish the wizard. Task 2: Use the Service Controller wizard on the component controller of ModelComp for the EmployeeModel and change the generated coding in the method wdDoInit() to initialize the complete request node. 1. Right click in the Data Modeler on the component controller and Apply Template choosing Service Controller. Select Request_GetEmployeeById from the EmployeeModel and tag all nodes and attributes. 2. Copy the coding of the method wdDoInit() of the EmployeeCust to the method wdDoInit() of the ModelComp component controller replacing the generated coding and organize the imports. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 255
    • Unit 6: Web Dynpro Models JA450 Task 3: Create a new context node called Employee of Collection Cardinality 1..1 consisting of attributes compatible to the context node Return and extend the implementation of the method executeGetEmployeeById() for copying the return of the model call to the new context node Employee. 1. Go to the context of the ModelComp component controller, copy the node Return and paste it in the context root node. 2. Right click on the context node Return_1 and choose Delete Model Binding. Rename the node to Employee and set the Collection Cardinality to 1..1. 3. Use the WDCopyService to copy the corresponding attributes of the current Return element to the current Employee element after the invalidation of the response node. Task 4: Create the method getEmployeeById(long employeeId) setting the EmployeeId bound to the model and calling the execute method. Publish the new method and the context node Employee in the interface controller. 1. Go to the Methods of the ModelComp component controller and choose New... selecting Method. Set the name to getEmployeeById and add the parameter employeeId of type long. 2. Get the reference to the current GetEmployeeById element and set the EmployeeId by using the method parameter employeeId. Use wdThis to call the method executeGetEmployeeById(). 3. Copy the context node Employee from the ModelComp component controller and the method getEmployeeById(long employeeId) to the ModelComp interface controller Task 5: Delete all parts in the StudentComp bound to the EmployeeModel as well as coding working on it. 1. Go to the EmployeeCust and delete the coding in the method wdDoInit() and the whole method executeGetEmployeeById(). Hint: The source code of the deleted method executeGetEmployeeById() is still available as comment at the end of the class. 2. Delete the context node Request_GetEmployeeById of the EmployeeCust and the node GetEmployeeById of the InputView. Continued on next page 256 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component 3. Remove the EmployeeModel from the list of the Used Models of StudentComp in the Web Dynpro Explorer. Task 6: Add a component usage called ModelCompUsage for ModelComp to the StudentComp. Map the context node Employee from the interface controller of ModelComp to the EmployeeCust using FirstName and LastName. 1. Go to the Data Modeler of the component StudentComp and choose Embed Component from the menu on the right. Click in the modeler pane and set the name ModelCompUsage browsing to the component ModelComp. 2. Choose Create Data Link from the menu on the right and draw a line from the EmployeeCust to the interface controller of ModelComp. Drag & drop the context node Employee from left to right onto the context root node and select FirstName and LastName. Task 7: Create the method getEmployeeById(long employeeId) calling the interface controller method of ModelComp and copying the result from node Employee to NewStudent. 1. Go to the Methods of the EmployeeCust and choose New... selecting Method. Set the name to getEmployeeById and add the parameter employeeId of type long. 2. Call the method getEmployeeById(long employeeId) of the ModelComp interface controller by using wdGetModelCompUsageInterface(). 3. Use the WDCopyService to copy the corresponding attributes from context node Employee to node New Student. Task 8: Create a new context node called Employee of cardinality 1..1 having the attribute EmployeeId of type long in the InputView and bind the input field for the EmployeeId to the attribute. Change the coding of the SearchButton to call the new EmployeeCust method. 1. Right click on the context root node of the InputView and choose New -> Node selecting Manually for the name Employee. Set the Collection Cardinality to 1..1. 2. Right click on the context node Employee and choose New -> Attribute... selecting Manually for the name EmployeeId and type long. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 257
    • Unit 6: Web Dynpro Models JA450 3. Click in the property value of the input field for the EmployeeId on Bind and choose EmployeeId. 4. In the action handler for the SearchButton call the method getEmployeeById(long employeeId) of the EmployeeCust by using wdGetEmployeeCustController() and passing the current EmployeeId as parameter. Task 9: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. Hint: If the SearchButton does not seem to work, do not forget to check the Collection Cardinality set in task 3 and task 8. 258 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Solution 16: Develop Model Component Task 1: Create a new faceless component called ModelComp using the model EmployeeModel. 1. Right click on Components in the Web Dynpro Explorer and choose Create Component. Enter the name ModelComp and tag only Used Models. a) 2. Perform as seen in the demonstration of your trainer. Add... a used model and select EmployeeModel. Finish the wizard. a) Perform as seen in the demonstration of your trainer. Task 2: Use the Service Controller wizard on the component controller of ModelComp for the EmployeeModel and change the generated coding in the method wdDoInit() to initialize the complete request node. 1. Right click in the Data Modeler on the component controller and Apply Template choosing Service Controller. Select Request_GetEmployeeById from the EmployeeModel and tag all nodes and attributes. a) 2. Perform as seen in the demonstration of your trainer. Copy the coding of the method wdDoInit() of the EmployeeCust to the method wdDoInit() of the ModelComp component controller replacing the generated coding and organize the imports. a) See source code extract of the sample solution. Task 3: Create a new context node called Employee of Collection Cardinality 1..1 consisting of attributes compatible to the context node Return and extend the implementation of the method executeGetEmployeeById() for copying the return of the model call to the new context node Employee. 1. Go to the context of the ModelComp component controller, copy the node Return and paste it in the context root node. a) 2. Perform as seen in the demonstration of your trainer. Right click on the context node Return_1 and choose Delete Model Binding. Rename the node to Employee and set the Collection Cardinality to 1..1. a) Perform as seen in the demonstration of your trainer. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 259
    • Unit 6: Web Dynpro Models 3. JA450 Use the WDCopyService to copy the corresponding attributes of the current Return element to the current Employee element after the invalidation of the response node. a) See source code extract of the sample solution. Task 4: Create the method getEmployeeById(long employeeId) setting the EmployeeId bound to the model and calling the execute method. Publish the new method and the context node Employee in the interface controller. 1. Go to the Methods of the ModelComp component controller and choose New... selecting Method. Set the name to getEmployeeById and add the parameter employeeId of type long. a) 2. Get the reference to the current GetEmployeeById element and set the EmployeeId by using the method parameter employeeId. Use wdThis to call the method executeGetEmployeeById(). a) 3. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Copy the context node Employee from the ModelComp component controller and the method getEmployeeById(long employeeId) to the ModelComp interface controller a) Perform as seen in the demonstration of your trainer. Task 5: Delete all parts in the StudentComp bound to the EmployeeModel as well as coding working on it. 1. Go to the EmployeeCust and delete the coding in the method wdDoInit() and the whole method executeGetEmployeeById(). Hint: The source code of the deleted method executeGetEmployeeById() is still available as comment at the end of the class. a) 2. Perform as seen in the demonstration of your trainer. Delete the context node Request_GetEmployeeById of the EmployeeCust and the node GetEmployeeById of the InputView. a) Perform as seen in the demonstration of your trainer. Continued on next page 260 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component 3. Remove the EmployeeModel from the list of the Used Models of StudentComp in the Web Dynpro Explorer. a) Perform as seen in the demonstration of your trainer. Task 6: Add a component usage called ModelCompUsage for ModelComp to the StudentComp. Map the context node Employee from the interface controller of ModelComp to the EmployeeCust using FirstName and LastName. 1. Go to the Data Modeler of the component StudentComp and choose Embed Component from the menu on the right. Click in the modeler pane and set the name ModelCompUsage browsing to the component ModelComp. a) 2. Perform as seen in the demonstration of your trainer. Choose Create Data Link from the menu on the right and draw a line from the EmployeeCust to the interface controller of ModelComp. Drag & drop the context node Employee from left to right onto the context root node and select FirstName and LastName. a) Perform as seen in the demonstration of your trainer. Task 7: Create the method getEmployeeById(long employeeId) calling the interface controller method of ModelComp and copying the result from node Employee to NewStudent. 1. Go to the Methods of the EmployeeCust and choose New... selecting Method. Set the name to getEmployeeById and add the parameter employeeId of type long. a) 2. Call the method getEmployeeById(long employeeId) of the ModelComp interface controller by using wdGetModelCompUsageInterface(). a) 3. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Use the WDCopyService to copy the corresponding attributes from context node Employee to node New Student. a) See source code extract of the sample solution. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 261
    • Unit 6: Web Dynpro Models JA450 Task 8: Create a new context node called Employee of cardinality 1..1 having the attribute EmployeeId of type long in the InputView and bind the input field for the EmployeeId to the attribute. Change the coding of the SearchButton to call the new EmployeeCust method. 1. Right click on the context root node of the InputView and choose New -> Node selecting Manually for the name Employee. Set the Collection Cardinality to 1..1. a) 2. Right click on the context node Employee and choose New -> Attribute... selecting Manually for the name EmployeeId and type long. a) 3. Perform as seen in the demonstration of your trainer. Click in the property value of the input field for the EmployeeId on Bind and choose EmployeeId. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. In the action handler for the SearchButton call the method getEmployeeById(long employeeId) of the EmployeeCust by using wdGetEmployeeCustController() and passing the current EmployeeId as parameter. a) See source code extract of the sample solution. Task 9: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. Hint: If the SearchButton does not seem to work, do not forget to check the Collection Cardinality set in task 3 and task 8. a) Perform as seen in the demonstration of your trainer. Result ModelComp public void wdDoInit() { //@@begin wdDoInit() EmployeeModel model = new EmployeeModel(); Continued on next page 262 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Request_GetEmployeeById request = new Request_GetEmployeeById(model); request.setGetEmployeeById(new GetEmployeeById(model)); wdContext.nodeRequest_GetEmployeeById().bind(request); //@@end } public void executeGetEmployeeById( ) { //@@begin executeGetEmployeeById() IWDMessageManager manager = wdComponentAPI.getMessageManager(); try { wdContext.currentRequest_GetEmployeeByIdElement().modelObject() .execute(); wdContext.nodeResponse().invalidate(); WDCopyService.copyCorresponding(wdContext.currentReturnElement(), wdContext.currentEmployeeElement()); } catch (Exception e) { manager.reportException(e.getMessage()); } //@@end } public void getEmployeeById( long employeeId ) { //@@begin getEmployeeById() wdContext.currentGetEmployeeByIdElement().setEmployeeId(employeeId); wdThis.executeGetEmployeeById(); //@@end } EmployeeCust public void wdDoInit() { //@@begin wdDoInit() //@@end } public void getEmployeeById( long employeeId ) { //@@begin getEmployeeById() wdThis.wdGetModelCompUsageInterface().getEmployeeById(employeeId); WDCopyService.copyCorresponding(wdContext.currentEmployeeElement(), wdContext.currentNewStudentElement()); //@@end } Continued on next page 2008 © 2008 SAP AG. All rights reserved. 263
    • Unit 6: Web Dynpro Models JA450 InputView public void onActionSearch( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSearch(ServerEvent) wdThis.wdGetEmployeeCustController().getEmployeeById( wdContext.currentEmployeeElement().getEmployeeId()); //@@end } 264 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Model Component Lesson Summary You • • • 2008 should now be able to: use multiple components in one application. map data between different components. implement a model component. © 2008 SAP AG. All rights reserved. 265
    • Unit Summary JA450 Unit Summary You should now be able to: • explain the purpose of a model. • decide between models used in your application. • explain the benefits of a web service. • use a model to consume a web service. • understand the structure of a Web Dynpro model. • define model usages in Web Dynpro components. • execute backend services via models. • use multiple components in one application. • map data between different components. • implement a model component. 266 © 2008 SAP AG. All rights reserved. 2008
    • Unit 7 Web Dynpro UI Services Unit Overview This chapter shows the UI services for internationalization, messaging, pop-ups and value help. Therefore there are for lessons offering in total four mandatory exercises and one optional one. Unit Objectives After completing this unit, you will be able to: • • • • • • • • • • • explain the term internationalization. understand SAP’s implementation of the XLIFF standard. make Web Dynpro ready for translation. show messages on the screen. distinguish which message type should be used. create context sensitive messages. create pop-ups in Web Dynpro. ask the user questions as confirmation dialog. show user-defined modal windows. create value helps in Web Dynpro. change the list of values at runtime. Unit Contents Lesson: Internationalization ...................................................268 Lesson: Messages..............................................................276 Exercise 17: Context Attribute Message ................................285 Lesson: Pop-ups ................................................................295 Exercise 18: Confirmation Dialog ........................................303 Exercise 19: Modal Window (Optional)..................................309 Lesson: Dictionary Based Value Selectors ..................................320 Exercise 20: Extended Value Selector...................................327 2008 © 2008 SAP AG. All rights reserved. 267
    • Unit 7: Web Dynpro UI Services JA450 Lesson: Internationalization Lesson Overview This lesson introduces the term internationalization for Web Dynpro and how it is realized. Lesson Objectives After completing this lesson, you will be able to: • • • explain the term internationalization. understand SAP’s implementation of the XLIFF standard. make Web Dynpro ready for translation. Business Example You want to develop your application supporting multiple languages. SAP Standard The process by which language specific text is detached from the program code that uses it is known as internationalization. This allows the same program to operate in multiple languages without needing different versions of the code for each language. 268 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Internationalization Figure 115: Application Language Due to the fact that internationalization is such a long word, it is often abbreviated in I18N. That is, the first letter I, the last letter N and do not bother about the 18 other letters in between. The XML Language Interchange File Format (XLIFF) is a standard by which language specific text can be stored and managed. It is well-established on the market and therefore used by all translation bureaus. 2008 © 2008 SAP AG. All rights reserved. 269
    • Unit 7: Web Dynpro UI Services JA450 Figure 116: SAP Supported XLIFF In order to map the translatable texts of Web Dynpro to the XLIFF standard, SAP uses its own implementation called SAP supported XLIFF (S2X) for I18N. The NWDS offers the S2X-Editor for editing the language settings of a certain part of a Web Dynpro application. It is not a professional translation software used at translation bureaus but gives the developer the possibility to view and change the language specific texts. Because of the XLIFF standard there are other editors on the market focusing on the translation procedure. Web Dynpro Implementation Web Dynpro offers several places for language specific text. Every time the developer enters a text to be visible on the screen, this text must be able to be translatable. 270 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Internationalization Figure 117: Project Language In order to make the language consistent, the DC project language defines the base language for all texts defined in the Web Dynpro tools visible to be on the screen. The Web Dynpro Framework (WDF) will generate xlf-files storing the translatable text and setting the source language to the language of the DC project. The source language can not be changed in these xlf-files because it strictly depends on the DC project language. These xlf-files are generated according to the names of the Web Dynpro parts used in the DC project. The WDF will at built-time generate properties-files to be used by the Java standard. That is, during runtime the properties-files are used as source for the text. The xlf-files are only necessary at design-time. 2008 © 2008 SAP AG. All rights reserved. 271
    • Unit 7: Web Dynpro UI Services JA450 Figure 118: Language Specific Text When using a dictionary there is the possibility to define text objects. Therefore there will be the following xlf-files available: <SimpleTypeName>.dtsimpletype.xlf Text objects and description of a simple type <StructureName>.dtstructure.xlf Description of a structure In a component there are also different places to define a translatable text. This is of course the layout but also text in the metadata of the controllers: <ViewName>.wdview.xlf Text and tool tip properties of UI elements <WindowName>.wdwindow.xlf Window properties <ControllerName>.wdcontroller.xlf Text descriptions of actions and coding documentation <ComponentName>MessagePool.wdmessagepool.xlf Text of messages 272 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Internationalization These xlf-files can be sent to a translation bureau or translated manually. In order to do that you must copy each file to a new name adding the ISO-symbol for the language: • • • <ViewName>.wdview_<iso>.xlf <WindowName>.wdwindow_<iso>.xlf ... Afterwards the source language of the file must be changed according to the ISO-symbol. This will allow using language-specific characters in the translatable text. The properties-files will also have the ISO-symbol in its name like en, de, zh etc. Figure 119: Runtime Local Identification 2008 © 2008 SAP AG. All rights reserved. 273
    • Unit 7: Web Dynpro UI Services JA450 The decision which language will be used at runtime depends on a fallback sequence of lookup locations: 1. URL query string The URL can have the parameter sap-locale=<iso> set. 2. Locale of authenticated user If the user is authenticated, his personal locale will be used. 3. Browser language setting Many browsers can set a base language. 4. Application property The Web Dynpro application can define the property sap.locale=<Locale>. 5. Locale of Web Dynpro system The NWAS running Web Dynpro can have a base language. 6. Default locale of the Java Virtual Machine (JVM) The JVM at least has a locale set. The URL is normally used for testing purpose so in most cases the user decides about the language either by his user settings or by the browser he uses. 274 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Internationalization Lesson Summary You • • • 2008 should now be able to: explain the term internationalization. understand SAP’s implementation of the XLIFF standard. make Web Dynpro ready for translation. © 2008 SAP AG. All rights reserved. 275
    • Unit 7: Web Dynpro UI Services JA450 Lesson: Messages Lesson Overview This lesson shows how to create messages on the screen highlighting erroneous values and stopping the application until solved. Lesson Objectives After completing this lesson, you will be able to: • • • show messages on the screen. distinguish which message type should be used. create context sensitive messages. Business Example You want show message to the user if he enters wrong values in your input mask. Handling Translatable Text In Java it is normal to use properties-files to replace hard-coded Strings in the implementation by a translatable text. In Web Dynpro you do not define these properties-files on your own. Instead you define text messages in the message pool of a component. Figure 120: Message Pool 276 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages In the message pool you can define messages shown on the screen as well as text messages used in the implementation for setting a text value for UI elements. A message consists of the message key, type and text. The message key is used to access the message at runtime. In order to read the text in a message the IWDTextAccessor is needed, which is part of the component API. Figure 121: Text Accessor Depending on the key a constant is generated for every message of the component message interface in the form of IMessage<ComponentName>. The constant has the name of the capitalized key of the message. Hint: Use the Java naming style for the message key starting with a capital letter for a new word. The WDF will generate a “_” as separator in the constant. Handling UI Messages In order to show a message on the screen the IWDMessageManager must be used. Each component has its own message manager instance which is usable in every view presenting the message. 2008 © 2008 SAP AG. All rights reserved. 277
    • Unit 7: Web Dynpro UI Services JA450 Figure 122: UI Messages Standard messages will appear at the bottom of the actual view assembly when calling the respective method of the message manager. The text and icon shown depend on the used message of the message pool. The message manager can be accessed via the wdComponentAPI in every controller. It is implemented as singleton so every time you call the method getMessageManager() you will get the same instance in every controller. The message manager offers two types of methods: report…() Report-methods put the message in the message table of the message manager returning the control to the calling program. raise…() Raise-methods terminate the program immediately when called sending the message to the screen. 278 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages Figure 123: Message Manager Raise-methods should only be used to report fatal application errors in order to prevent further coding to worsen the situation. Raising a message leave the application in an undefined state so be cautious when using it. Normally reporting messages is enough to inform the user and continue with the application. When reporting errors every method offers the possibility to cancel the navigation so the screen will stay in the current view assembly. You only need to adjust your coding reacting on a called message. Note: Reporting a message can only stop the navigation if the message is of type error and the method is called before or inside the wdDoBeforeNavigation(). Check the phase model for details about the calling sequence in Web Dynpro. There is no limit of calling report-methods to show messages on the screen. The appearance of the method depends on the message type defined in the message pool. 2008 © 2008 SAP AG. All rights reserved. 279
    • Unit 7: Web Dynpro UI Services JA450 Figure 124: Basic Messages A message can have one of the following message types: • • • • • Success Warning Error Info Text Text messages can not be reported by the message manager. In reverse only text messages can be accessed by the text accessor. All types have a constant generated in the component message interface. If the user enters an invalid value into a UI element, then when the message manager is told to report an error, it can be passed the context metadata of the attribute to which the UI element is bound. In this way the message manager is able to establish a link between the text of the error message appearing on the screen and the UI element containing the invalid value. 280 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages Figure 125: Context Attribute Message The important point here is that the developer is not concerned about which UI element is used to display the invalid value. Since the invalid value is stored in the context and not the UI element, the message manager must be told which context attribute holds the offending value. The UI element is not important. All UI elements showing the erroneous value will be highlighted and the user can click on the error message what repositions the cursor on the first offending field passed to the method. The metadata of the attribute is available from the typed context API by accessing the erroneous context element and calling the method getAttributePointer(“<AttributeName>”). The returning reference of type IWDAttributePointer is available since 7.1 and combines the metadata of an attribute with context element holding the value. 2008 © 2008 SAP AG. All rights reserved. 281
    • Unit 7: Web Dynpro UI Services JA450 Figure 126: Context Attribute Message Coding The method reportContextAttributeMessage() needs beside the metadata and the message in the message pool also an Object array holding the text for the placeholders in the message text. This information is optional depending on the defined placeholders in the message text. The available placeholders are {0}, {1}, {2} and {3}. When replacing these placeholders, language specific text should be used in order to let the whole message be translatable. You can use the text defined in the different parts of Web Dynpro. The attribute name for example can be saved as field label in a simple type. When reporting messages, all will appear as a table at the bottom of the screen for the whole view assembly. It does not matter in which view controller the message was reported. The message manager is a singleton for the whole component and therefore for all views visible in a view assembly. If you want to see the messages in another area of the screen, you can add MessageArea UI element to layout of a view. 282 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages Figure 127: Message Area Every message will automatically appear inside a MessageArea UI element if present. It counts for the whole view assembly. If multiple MessageArea UI elements exist in a view assembly, the first instantiated one will be used. Hint: You should go for only one place showing messages not because of coding problems but for better usability of your application. The SAP standard for showing messages is at the bottom of the screen. 2008 © 2008 SAP AG. All rights reserved. 283
    • Unit 7: Web Dynpro UI Services 284 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Messages Exercise 17: Context Attribute Message Exercise Objectives After completing this exercise, you will be able to: • send UI messages to the user of Web Dynpro. • report context attribute messages. Business Example You want to send error messages to the user if he tries to save a student without a course or an empty student. Optionally you want to send an error message if the entered end date is before the begin date. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~uiservices1XX with XX as your group number. Template training.sap.com~model3 Solution training.sap.com~uiservices1 training.sap.com~uiservices1opt Task 1: Create a MessageArea in the layout of the MainView under the group UI elements spanning two columns in the MatrixLayout. 1. Right click in the Outline of the MainView on the RootElement and Insert Child... choosing a MessageArea. 2. Set the property layoutData to MatrixHeadData and the colSpan of the LayoutData to 2. Task 2: Create a message called NoCourseSelected of type error with a suitable text in the message pool of the StudentComp. Create one more message called EmptyInput of type error with a suitable text including a placeholder for the name of the field. 1. Go to the message pool of the StudentComp and click on the plus icon. Set the key of the new message to NoCourseSelected selecting the type error and enter the text Please select a course.. 2. Repeat the last step creating a message with the key EmptyInput of type error and the text The field {0} is empty.. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 285
    • Unit 7: Web Dynpro UI Services JA450 Task 3: Get a reference to the message manager in the InputView and report the message NoCourseSelected when trying to save a student without a course. 1. Create a private attribute of type IWDMessageManager in the InputView. Use this attribute to save the reference to the message manager in the method wdDoInit() by using wdComponentAPI.getMessageManager(). 2. Report the message NoCourseSelected in the method onActionSave() if the context node Courses has no lead selection by using reportMessage() and the reference found in IMessageStudentComp. Task 4: Create the method checkMandatoryField(String fieldName) in the InputView reporting the message EmptyInput if the value of the attribute passed in by the parameter is empty. Call the method for all input fields when trying to save a student preventing the saving if at least one message is reported. 1. Go to Methods of the InputView and choose New... selecting Method. Set the name checkMandatoryField and create the parameter fieldName of type String. 2. Save the value of the attribute of the current NewStudent element passed in by the parameter fieldName in a variable inside the method checkMandatoryField() by using getAttributeAsText(). 3. If the field entry is empty, save the attribute pointer by using getAttributePointer() of the current NewStudent element in a variable of type IWDAttributePointer. Use the attribute pointer to get the field label by using getFieldLabel() of the simple type of the attribute. 4. Report the message EmptyInput by using the method reportContextAttributeMessage() supplying its parameters with the attribute pointer, the message reference found in IMessageStudentComp and an object array consisting of the field label. 5. Call the method checkMandatoryField(String fieldName) for each attribute of the context node NewStudent using the constants of INewStudentElement in the method onActionSave(). Surround the existing If-clause with a new one checking if the message manager has exceptions. Continued on next page 286 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages Task 5: Optional: Create the method checkDate() in the InputView reporting the new message InvalideDateRange if the value of EndDate is before BeginDate. Call the method after reporting empty input fields but separated from them. 1. Go to the message pool of the StudentComp and click on the plus icon. Set the key of the new message to InvalideDateRange selecting the type error and enter the text End Date {0} must not be before Begin Date {1}.. 2. Go to Methods of the InputView and choose New... selecting Method. Set the name to checkDate. 3. Inside the method get the values for BeginDate and EndDate from the current NewStudent element and check if EndDate is in the future of BeginDate. If this is the case create an array of attribute pointers of the length 2. Add the attribute pointers for BeginDate and EndDate to the array using getAttributePointer() of the current NewStudent element. 4. Report the message InvalideDateRange by using the method reportContextAttributeMessage() supplying its parameters with the attribute pointer array, the message reference found in IMessageStudentComp and an object array consisting of the values for BeginDate and EndDate. 5. Call the method checkDate() in the method onActionSave() surrounding the inner If-clause with a new one checking if the message manager has exceptions. Task 6: Deploy new archive and run your application StudentApp. 1. 2008 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 287
    • Unit 7: Web Dynpro UI Services JA450 Solution 17: Context Attribute Message Task 1: Create a MessageArea in the layout of the MainView under the group UI elements spanning two columns in the MatrixLayout. 1. Right click in the Outline of the MainView on the RootElement and Insert Child... choosing a MessageArea. a) 2. Perform as seen in the demonstration of your trainer. Set the property layoutData to MatrixHeadData and the colSpan of the LayoutData to 2. a) Perform as seen in the demonstration of your trainer. Task 2: Create a message called NoCourseSelected of type error with a suitable text in the message pool of the StudentComp. Create one more message called EmptyInput of type error with a suitable text including a placeholder for the name of the field. 1. Go to the message pool of the StudentComp and click on the plus icon. Set the key of the new message to NoCourseSelected selecting the type error and enter the text Please select a course.. a) 2. Perform as seen in the demonstration of your trainer. Repeat the last step creating a message with the key EmptyInput of type error and the text The field {0} is empty.. a) Perform as seen in the demonstration of your trainer. Task 3: Get a reference to the message manager in the InputView and report the message NoCourseSelected when trying to save a student without a course. 1. Create a private attribute of type IWDMessageManager in the InputView. Use this attribute to save the reference to the message manager in the method wdDoInit() by using wdComponentAPI.getMessageManager(). a) 2. See source code extract of the sample solution. Report the message NoCourseSelected in the method onActionSave() if the context node Courses has no lead selection by using reportMessage() and the reference found in IMessageStudentComp. a) See source code extract of the sample solution. Continued on next page 288 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages Task 4: Create the method checkMandatoryField(String fieldName) in the InputView reporting the message EmptyInput if the value of the attribute passed in by the parameter is empty. Call the method for all input fields when trying to save a student preventing the saving if at least one message is reported. 1. Go to Methods of the InputView and choose New... selecting Method. Set the name checkMandatoryField and create the parameter fieldName of type String. a) 2. Save the value of the attribute of the current NewStudent element passed in by the parameter fieldName in a variable inside the method checkMandatoryField() by using getAttributeAsText(). a) 3. See source code extract of the sample solution. Report the message EmptyInput by using the method reportContextAttributeMessage() supplying its parameters with the attribute pointer, the message reference found in IMessageStudentComp and an object array consisting of the field label. a) 5. See source code extract of the sample solution. If the field entry is empty, save the attribute pointer by using getAttributePointer() of the current NewStudent element in a variable of type IWDAttributePointer. Use the attribute pointer to get the field label by using getFieldLabel() of the simple type of the attribute. a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Call the method checkMandatoryField(String fieldName) for each attribute of the context node NewStudent using the constants of INewStudentElement in the method onActionSave(). Surround the existing If-clause with a new one checking if the message manager has exceptions. a) See source code extract of the sample solution. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 289
    • Unit 7: Web Dynpro UI Services JA450 Task 5: Optional: Create the method checkDate() in the InputView reporting the new message InvalideDateRange if the value of EndDate is before BeginDate. Call the method after reporting empty input fields but separated from them. 1. Go to the message pool of the StudentComp and click on the plus icon. Set the key of the new message to InvalideDateRange selecting the type error and enter the text End Date {0} must not be before Begin Date {1}.. a) 2. Go to Methods of the InputView and choose New... selecting Method. Set the name to checkDate. a) 3. See source code extract of the sample solution. Report the message InvalideDateRange by using the method reportContextAttributeMessage() supplying its parameters with the attribute pointer array, the message reference found in IMessageStudentComp and an object array consisting of the values for BeginDate and EndDate. a) 5. Perform as seen in the demonstration of your trainer. Inside the method get the values for BeginDate and EndDate from the current NewStudent element and check if EndDate is in the future of BeginDate. If this is the case create an array of attribute pointers of the length 2. Add the attribute pointers for BeginDate and EndDate to the array using getAttributePointer() of the current NewStudent element. a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Call the method checkDate() in the method onActionSave() surrounding the inner If-clause with a new one checking if the message manager has exceptions. a) See source code extract of the sample solution. Task 6: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result InputView Continued on next page 290 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages //@@begin imports import java.sql.Date; import com.sap.tc.webdynpro.progmodel.api.IWDAttributePointer; import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager; import com.sap.tc.webdynpro.progmodel.api.IWDNode; import com.sap.tc.webdynpro.progmodel.api.WDCopyService; import com.sap.training.uiservices1.studentcomp.wdp.IMessageStudentComp; import com.sap.training.uiservices1.studentcomp.wdp.IPrivateInputView; import com.sap.training.uiservices1.studentcomp.wdp.IPrivateInputView. INewStudentElement; import com.sap.training.uiservices1.studentcomp.wdp.IPrivateInputView. IStudentsElement; //@@end public void wdDoInit() { //@@begin wdDoInit() msgMng = wdComponentAPI.getMessageManager(); initStudent(); //@@end } public void checkMandatoryField( java.lang.String fieldName ) { //@@begin checkMandatoryField() String fieldEntry = wdContext.currentNewStudentElement() .getAttributeAsText(fieldName); if (fieldEntry.length() == 0) { IWDAttributePointer attrPointer = wdContext .currentNewStudentElement().getAttributePointer(fieldName); String fieldLabel = attrPointer.getAttributeInfo().getSimpleType() .getFieldLabel(); msgMng.reportContextAttributeMessage(attrPointer, IMessageStudentComp.EMPTY_INPUT, new Object[] { fieldLabel }); } //@@end } //@@begin others private IWDMessageManager msgMng; private void initStudent() { INewStudentElement currentNewStudentElement = wdContext Continued on next page 2008 © 2008 SAP AG. All rights reserved. 291
    • Unit 7: Web Dynpro UI Services JA450 .currentNewStudentElement(); currentNewStudentElement.setFirstName("John"); currentNewStudentElement.setLastName("Smith"); currentNewStudentElement.setBeginDate(Date.valueOf("2008-10-20")); currentNewStudentElement.setEndDate(Date.valueOf("2008-10-24")); } //@@end InputView (Optional) public void checkDate( ) { //@@begin checkDate() INewStudentElement newStudentElement = wdContext .currentNewStudentElement(); Date beginDate = newStudentElement.getBeginDate(); Date endDate = newStudentElement.getEndDate(); if (beginDate.getTime() > endDate.getTime()) { IWDAttributePointer[] attributePointers = new IWDAttributePointer[2]; attributePointers[0] = wdContext.currentNewStudentElement() .getAttributePointer(INewStudentElement.BEGIN_DATE); attributePointers[1] = wdContext.currentNewStudentElement() .getAttributePointer(INewStudentElement.END_DATE); msgMng.reportContextAttributeMessage(attributePointers, IMessageStudentComp.INVALIDE_DATE_RANGE, new Object[] { endDate, beginDate }); } //@@end } public void onActionSave( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSave(ServerEvent) wdThis.checkMandatoryField(INewStudentElement.FIRST_NAME); wdThis.checkMandatoryField(INewStudentElement.LAST_NAME); wdThis.checkMandatoryField(INewStudentElement.BEGIN_DATE); wdThis.checkMandatoryField(INewStudentElement.END_DATE); if (!msgMng.hasExceptions()) { wdThis.checkDate(); if (!msgMng.hasExceptions()) { if (wdContext.nodeCourses().getLeadSelection() != IWDNode.NO_SELECTION) { Continued on next page 292 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Messages IStudentsElement studentsElement = wdContext .createAndAddStudentsElement(); WDCopyService.copyCorresponding(wdContext .currentNewStudentElement(), studentsElement); } else { msgMng.reportMessage( IMessageStudentComp.NO_COURSE_SELECTED, null); } } } //@@end } 2008 © 2008 SAP AG. All rights reserved. 293
    • Unit 7: Web Dynpro UI Services JA450 Lesson Summary You should now be able to: • show messages on the screen. • distinguish which message type should be used. • create context sensitive messages. 294 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups Lesson: Pop-ups Lesson Overview This lesson introduces pop-ups in Web Dynpro asking the user for action. Lesson Objectives After completing this lesson, you will be able to: • • • create pop-ups in Web Dynpro. ask the user questions as confirmation dialog. show user-defined modal windows. Business Example You want show a pop-up as user-decision before starting irreversible actions. Confirmation Dialog By definition, a window in Web Dynpro is a design time entity for arranging a set of views for display on the user interface. This is the same for pop-up windows. To show a pop-up the class IWDWindowManager is needed. Figure 128: Window Manager 2008 © 2008 SAP AG. All rights reserved. 295
    • Unit 7: Web Dynpro UI Services JA450 What the message manager is for messages that is the window manager for (pop-up) windows. It is a singleton with respect to a component and can be accessed using wdComponentAPI. The window manager offers three different types of pop-ups: • • • Confirmation Dialog Modal Window External Window The external window is just a new browser window opened using a link to the web page. Instead the confirmation dialog and the modal windows are pop-ups inside the current browser window. The confirmation dialog is a special modal window generated by the WDF when using the window manager. When showing a modal window the main screen is greyed out and not usable until the pop-up is closed. The pop-up itself can be resized and positioned somewhere in the browser window. Figure 129: Confirmation Dialog Example The purpose of a confirmation dialog is to ask the user a question which he can answer by pressing one of the available buttons. It is also possible to inform the user about a status and just offering one button to close the pop-up. What text will be seen and which buttons will be available is implemented by the developer. 296 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups When the user chooses any button on the confirmation dialog, the registered event handler will be called and the pop-up closed. The developer can implement any coding in the event handler but he can not prevent the pop-up to be closed. This is part of the design of the confirmation dialog. Figure 130: Confirmation Dialog Processing The only things what must be defined for a confirmation dialog at design time are the event handlers used in the pop-up. These event handlers should be defined in a custom controller to make it possible to show the pop-up on different views. Beside that the coding is centralized in one place. A confirmation dialog needs at least one event handler to work. Therefore the method createConfirmationDialog() offers the possibility to register one event handler. It also sets the main text of the pop-up and the label of the button generated for the event handler. Hint: Think about I18N when setting a text for the pop-up and buttons. 2008 © 2008 SAP AG. All rights reserved. 297
    • Unit 7: Web Dynpro UI Services JA450 Figure 131: Create Confirmation Dialog A reference to the event handlers can be obtained using the typed API of the controller they are defined in. Additional buttons for the pop-up can be created by calling the method addChoice() for the confirmation dialog reference. This reference has still more methods available setting properties of the confirmation dialog. The method for showing the pop-up to the user is called show(). Modal Window The modal window is a freely defined pop-up consisting of a Web Dynpro window having a set of views in its navigation. As the confirmation dialog the main screen is greyed out waiting for the pop-up to be closed. The difference is that a modal window is not automatically closed when pressing a button. It is only closed if the developer has implemented this functionality. 298 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups Figure 132: Modal Window Example The developer can use any window to use it as modal window but must offer a possibility to close it. What will be seen in the pop-up is anything what can be defined in views and windows. Even navigation is possible inside the pop-up. Although the event handlers used in the modal window are part of the views used in the Web Dynpro window, the implementation for showing and destroying the modal window should placed in a custom controller. Again this makes the pop-up reusable in different views and centralizes the coding. 2008 © 2008 SAP AG. All rights reserved. 299
    • Unit 7: Web Dynpro UI Services JA450 Figure 133: Modal Window Processing A modal window needs a window defined in the component and at least one view to be shown in the navigation of the window. The developer can make use of everything offered by Web Dynpro to design the view including context mapping and data binding. The only restriction is that the developer must offer a way to close the pop-up. The implementation for doing this should be placed in the custom controller. 300 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups Figure 134: Modal Window Navigation The method createModalWindow() of the window manager needs at minimum a reference to the defined window. This reference of type IWDWindowInfo can be obtained from the component info accessible by the method findInWindows(“<WindowName>”) of wdComponentAPI.getComponentInfo(). 2008 © 2008 SAP AG. All rights reserved. 301
    • Unit 7: Web Dynpro UI Services JA450 Figure 135: Create and Destroy Modal Window The reference to the modal window should be saved in global variable of the controller in order to be able to destroy it when needed. The method for that is called destroyInstance(). A modal window is the most flexible way to create a pop-up in Web Dynpro. When thinking about the phase model, a modal window has its own one working until the pop-up is closed. After that the phase model of the main screen takes control again. 302 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups Exercise 18: Confirmation Dialog Exercise Objectives After completing this exercise, you will be able to: • get a reference to the window manager. • create a confirmation dialog in Web Dynpro. Business Example You want to create a pop-up asking the user, if he is sure about deleting the student from the list. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~uiservices2XX with XX as your group number. Template training.sap.com~uiservices1opt Solution training.sap.com~uiservices2 Task 1: Create the event handlers onActionYes() calling the method deleteSelectedStudents() and onActionNo() in the StudentComp component controller. 1. Go to Methods of the StudentComp component controller and choose New... selecting Event handler. Set the name to onActionYes and finish. 2. Repeat the last step creating the event handler onActionNo. 3. Call the method deleteSelectedStudents() in the event handler onActionYes() by using wdThis. Task 2: Implement the method deleteStudentConfDialog() creating a confirmation dialog using the event handlers onActionYes() and onActionNo(). The dialog should ask if the user is sure to delete the students. 1. Go to Methods of the StudentComp component controller and choose New... selecting Method and set the name to deleteStudentConfDialog. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 303
    • Unit 7: Web Dynpro UI Services JA450 2. Create a private attribute of type IWDWindowManager in the component controller. Use this attribute to save the reference to the window manager in the method wdDoInit() by using wdComponentAPI.getWindowManager(). 3. Inside the method check if the context nodes Courses and Students have a lead selection by using getLeadSelection(). 4. Create a confirmation dialog by using the method createConfirmationDialog() supplying its parameters with the text Are you sure? and the action reference for Yes found in IPrivateStudentComp. 5. Add a choice to the confirmation dialog using the action reference for No found in IPrivateStudentComp. 6. Set the title to Delete Student and show the confirmation dialog. Task 3: Change the implementation of the DeleteButton in the MainView to call the new method deleteStudentConfDialog() of the component controller. 1. Replace the call for the method deleteSelectedStudents() by the method call deleteStudentConfDialog(). Task 4: Deploy new archive and run your application StudentApp. 1. 304 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups Solution 18: Confirmation Dialog Task 1: Create the event handlers onActionYes() calling the method deleteSelectedStudents() and onActionNo() in the StudentComp component controller. 1. Go to Methods of the StudentComp component controller and choose New... selecting Event handler. Set the name to onActionYes and finish. a) 2. Repeat the last step creating the event handler onActionNo. a) 3. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Call the method deleteSelectedStudents() in the event handler onActionYes() by using wdThis. a) See source code extract of the sample solution. Task 2: Implement the method deleteStudentConfDialog() creating a confirmation dialog using the event handlers onActionYes() and onActionNo(). The dialog should ask if the user is sure to delete the students. 1. Go to Methods of the StudentComp component controller and choose New... selecting Method and set the name to deleteStudentConfDialog. a) 2. Create a private attribute of type IWDWindowManager in the component controller. Use this attribute to save the reference to the window manager in the method wdDoInit() by using wdComponentAPI.getWindowManager(). a) 3. See source code extract of the sample solution. Inside the method check if the context nodes Courses and Students have a lead selection by using getLeadSelection(). a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Create a confirmation dialog by using the method createConfirmationDialog() supplying its parameters with the text Are you sure? and the action reference for Yes found in IPrivateStudentComp. a) See source code extract of the sample solution. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 305
    • Unit 7: Web Dynpro UI Services 5. Add a choice to the confirmation dialog using the action reference for No found in IPrivateStudentComp. a) 6. JA450 See source code extract of the sample solution. Set the title to Delete Student and show the confirmation dialog. a) See source code extract of the sample solution. Task 3: Change the implementation of the DeleteButton in the MainView to call the new method deleteStudentConfDialog() of the component controller. 1. Replace the call for the method deleteSelectedStudents() by the method call deleteStudentConfDialog(). a) See source code extract of the sample solution. Task 4: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result StudentComp //@@begin imports import com.sap.tc.webdynpro.progmodel.api.IWDConfirmationDialog; import com.sap.tc.webdynpro.progmodel.api.IWDNode; import com.sap.tc.webdynpro.progmodel.api.IWDWindowManager; import com.sap.training.uiservices2.studentcomp.wdp.IPrivateStudentComp; import com.sap.training.uiservices2.studentcomp.wdp.IPublicStudentComp. IStudentsNode; //@@end public void onActionYes( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionYes(ServerEvent) wdThis.deleteSelectedStudents(); //@@end } Continued on next page 306 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups public void onActionNo( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionNo(ServerEvent) //@@end } public void deleteStudentConfDialog( ) { //@@begin deleteStudentConfDialog() if (wdContext.nodeCourses().getLeadSelection() != IWDNode.NO_SELECTION) { if (wdContext.nodeStudents().getLeadSelection() != IWDNode.NO_SELECTION) { IWDConfirmationDialog confDialog = winMan .createConfirmationWindow("Are you sure?", IPrivateStudentComp.WD_EVENTHANDLER_ON_ACTION_YES, "Yes"); confDialog.addChoice( IPrivateStudentComp.WD_EVENTHANDLER_ON_ACTION_NO, "No"); confDialog.setTitle("Delete Student"); confDialog.show(); } } //@@end } MainView public void onActionDelete( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionDelete(ServerEvent) wdThis.wdGetStudentCompController().deleteStudentConfDialog(); //@@end } 2008 © 2008 SAP AG. All rights reserved. 307
    • Unit 7: Web Dynpro UI Services 308 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Pop-ups Exercise 19: Modal Window (Optional) Exercise Objectives After completing this exercise, you will be able to: • create a modal pop-up window in Web Dynpro. • call methods of multiple controllers. Business Example You want to show a pop-up to the user when searching for an employee. The pop-up can be used to search for employees until closed by the user. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~uiservices2optXX with XX as your group number. Template training.sap.com~uiservices2 Solution training.sap.com~uiservices2opt Task 1: Create a Window called EmployeeWindow having one embedded view called EmployeeView. 1. Right click on Windows in the Web Dynpro Explorer of the StudentComp and Create Window setting the name to EmployeeWindow. 2. Choose in the Navigation of the EmployeeWindow Embed new View setting the name to EmployeeView. Task 2: Create in the StudentComp component controller the methods createEmployeeModalWin() and destroyEmployeeModalWin() implementing the EmployeeWindow as modal window. 1. Go to Methods of the StudentComp component controller and choose New... selecting Method and set the name to createEmployeeModalWin. 2. Repeat the last step setting the name to destroyEmployeeModalWin. 3. Create a private attribute of type IWDWindow in the component controller for saving a reference to the modal window. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 309
    • Unit 7: Web Dynpro UI Services JA450 4. Find in the method createEmployeeModalWin() the window information of the EmployeeWindow in the component by using findInWindows(String windowName) for the method getComponentInfo(). 5. Create a modal window of title Search Employee for the modal window reference and call the method show(). 6. In the method destroyEmployeeModalWin() destroy the modal instance if the reference is not null. Task 3: Extend the context node Employee in the EmployeeCust using all attributes provided by the interface controller of ModelComp. Replace the method getEmployeeById() of the EmployeeCust dividing its implementation up into the methods searchEmployeeById() and copyEmployeeToStudent(). 1. Right click on the context node Employee in the EmployeeCust and Edit Context Mapping... selecting all attributes of the node Employee. 2. Go to Methods of the EmployeCust and choose New... selecting Method and set the name to searchEmployeeById. 3. Repeat the last step setting the name to copyEmployeeToStudent. 4. Copy the method call getEmployeeById() of the method getEmployeeById() to the new method searchEmployeeById() getting the value for the method parameter from the context attribute EmployeeId. 5. Copy the method call copyCorresponding() of the method getEmployeeById() to the new method copyEmployeeToStudent(). 6. Delete the method getEmployeeById(). Task 4: Map the context node Employee of EmployeeCust and all of its attributes to the EmployeeView and add the component controller as required controller of the EmployeeView. In the layout create an input mask for the node Employee. 1. In the Data Modeler of the StudentComp draw a data link from the EmployeeView to the EmployeeCust. Drag & drop the context node Employee from left to right to the EmployeeView. 2. Repeat the last step drawing a data link from EmployeeView to the component controller but finishing the mapping wizard without defining a context mapping. Continued on next page 310 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups 3. Delete the DefaultTextView from the layout of the EmployeeView and right click on the RootElement in the Outline. Choose Apply Template selecting Form for all context attributes of the node Employee. Change the order of the elements to EmployeeId, DepartmentId, Salutation, FirstName, LastName, Email. 4. Set the length of the input field for the EmployeeId to 20 and rename the labels deleting the “label”-suffix. Task 5: Create a SearchButton next to input field for the EmployeeId and a ButtonRow at the bottom of the EmployeeView having the buttons OkButton and CancelButton. The SearchButton starts the model execution, the OkButton starts the copy process destroying the modal window and the CancelButton only destroys the modal window. 1. Right click on the RootElement in the Outline of the EmployeeView and Insert Child... choosing a button of id SearchButton. Create the action with name and text Search for the SearchButton and drag & drop it behind the input field for EmployeeId in the Outline. 2. Right click again on the RootElement inserting a ButtonRow with MatrixHeadData. Right click on the ButtonRow and insert the buttons with id OkButton. Create the action with name and text Ok for the OkButton 3. Repeat the last step inserting the CancelButton in the ButtonRow with the action Cancel. 4. In the method onActionSearch() call the method searchEmployeeById() of the EmployeeCust. 5. In the method onActionOk() call the method copyEmployeeToStudent() of the EmployeeCust followed by the methoddestroyEmployeeModalWin() of the component controller . 6. In the method onActionCancel() call the method destroyEmployeeModalWin() of the component controller. Task 6: Map the context attribute EmployeeId of the node Employee in the InputView to the one of node Employee in the EmployeeCust and change the implementation of the SearchButton starting the model execution and creating the modal window. 1. Right click on the context node Employee in the InputView and Edit Context Mapping... selecting the attribute EmployeeId of the node Employee in the EmployeeCust. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 311
    • Unit 7: Web Dynpro UI Services JA450 2. Replace in the method onActionSearch() the method call getEmployeeById() by the method searchEmployeeById(). 3. Add the method call createEmployeeModalWin() of the component controller to the method onActionSearch(). Task 7: Deploy new archive and run your application StudentApp. 1. 312 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups Solution 19: Modal Window (Optional) Task 1: Create a Window called EmployeeWindow having one embedded view called EmployeeView. 1. Right click on Windows in the Web Dynpro Explorer of the StudentComp and Create Window setting the name to EmployeeWindow. a) 2. Perform as seen in the demonstration of your trainer. Choose in the Navigation of the EmployeeWindow Embed new View setting the name to EmployeeView. a) Perform as seen in the demonstration of your trainer. Task 2: Create in the StudentComp component controller the methods createEmployeeModalWin() and destroyEmployeeModalWin() implementing the EmployeeWindow as modal window. 1. Go to Methods of the StudentComp component controller and choose New... selecting Method and set the name to createEmployeeModalWin. a) 2. Repeat the last step setting the name to destroyEmployeeModalWin. a) 3. See source code extract of the sample solution. Create a modal window of title Search Employee for the modal window reference and call the method show(). a) 6. See source code extract of the sample solution. Find in the method createEmployeeModalWin() the window information of the EmployeeWindow in the component by using findInWindows(String windowName) for the method getComponentInfo(). a) 5. Perform as seen in the demonstration of your trainer. Create a private attribute of type IWDWindow in the component controller for saving a reference to the modal window. a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. In the method destroyEmployeeModalWin() destroy the modal instance if the reference is not null. a) See source code extract of the sample solution. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 313
    • Unit 7: Web Dynpro UI Services JA450 Task 3: Extend the context node Employee in the EmployeeCust using all attributes provided by the interface controller of ModelComp. Replace the method getEmployeeById() of the EmployeeCust dividing its implementation up into the methods searchEmployeeById() and copyEmployeeToStudent(). 1. Right click on the context node Employee in the EmployeeCust and Edit Context Mapping... selecting all attributes of the node Employee. a) 2. Go to Methods of the EmployeCust and choose New... selecting Method and set the name to searchEmployeeById. a) 3. See source code extract of the sample solution. Copy the method call copyCorresponding() of the method getEmployeeById() to the new method copyEmployeeToStudent(). a) 6. Perform as seen in the demonstration of your trainer. Copy the method call getEmployeeById() of the method getEmployeeById() to the new method searchEmployeeById() getting the value for the method parameter from the context attribute EmployeeId. a) 5. Perform as seen in the demonstration of your trainer. Repeat the last step setting the name to copyEmployeeToStudent. a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Delete the method getEmployeeById(). a) Perform as seen in the demonstration of your trainer. Task 4: Map the context node Employee of EmployeeCust and all of its attributes to the EmployeeView and add the component controller as required controller of the EmployeeView. In the layout create an input mask for the node Employee. 1. In the Data Modeler of the StudentComp draw a data link from the EmployeeView to the EmployeeCust. Drag & drop the context node Employee from left to right to the EmployeeView. a) Perform as seen in the demonstration of your trainer. Continued on next page 314 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups 2. Repeat the last step drawing a data link from EmployeeView to the component controller but finishing the mapping wizard without defining a context mapping. a) 3. Delete the DefaultTextView from the layout of the EmployeeView and right click on the RootElement in the Outline. Choose Apply Template selecting Form for all context attributes of the node Employee. Change the order of the elements to EmployeeId, DepartmentId, Salutation, FirstName, LastName, Email. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. Set the length of the input field for the EmployeeId to 20 and rename the labels deleting the “label”-suffix. a) Perform as seen in the demonstration of your trainer. Task 5: Create a SearchButton next to input field for the EmployeeId and a ButtonRow at the bottom of the EmployeeView having the buttons OkButton and CancelButton. The SearchButton starts the model execution, the OkButton starts the copy process destroying the modal window and the CancelButton only destroys the modal window. 1. Right click on the RootElement in the Outline of the EmployeeView and Insert Child... choosing a button of id SearchButton. Create the action with name and text Search for the SearchButton and drag & drop it behind the input field for EmployeeId in the Outline. a) 2. Right click again on the RootElement inserting a ButtonRow with MatrixHeadData. Right click on the ButtonRow and insert the buttons with id OkButton. Create the action with name and text Ok for the OkButton a) 3. Perform as seen in the demonstration of your trainer. Repeat the last step inserting the CancelButton in the ButtonRow with the action Cancel. a) 4. Perform as seen in the demonstration of your trainer. Perform as seen in the demonstration of your trainer. In the method onActionSearch() call the method searchEmployeeById() of the EmployeeCust. a) See source code extract of the sample solution. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 315
    • Unit 7: Web Dynpro UI Services 5. In the method onActionOk() call the method copyEmployeeToStudent() of the EmployeeCust followed by the methoddestroyEmployeeModalWin() of the component controller . a) 6. JA450 See source code extract of the sample solution. In the method onActionCancel() call the method destroyEmployeeModalWin() of the component controller. a) See source code extract of the sample solution. Task 6: Map the context attribute EmployeeId of the node Employee in the InputView to the one of node Employee in the EmployeeCust and change the implementation of the SearchButton starting the model execution and creating the modal window. 1. Right click on the context node Employee in the InputView and Edit Context Mapping... selecting the attribute EmployeeId of the node Employee in the EmployeeCust. a) 2. Replace in the method onActionSearch() the method call getEmployeeById() by the method searchEmployeeById(). a) 3. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Add the method call createEmployeeModalWin() of the component controller to the method onActionSearch(). a) See source code extract of the sample solution. Task 7: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result StudentComp //@@begin imports import com.sap.tc.webdynpro.progmodel.api.IWDConfirmationDialog; import com.sap.tc.webdynpro.progmodel.api.IWDNode; import com.sap.tc.webdynpro.progmodel.api.IWDWindowManager; import com.sap.tc.webdynpro.progmodel.repository.IWDWindowInfo; Continued on next page 316 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups import com.sap.tc.webdynpro.services.session.api.IWDWindow; import com.sap.training.uiservices2opt.studentcomp.wdp.IPrivateStudentComp; import com.sap.training.uiservices2opt.studentcomp.wdp.IPublicStudentComp. IStudentsNode; //@@end public void createEmployeeModalWin( ) { //@@begin createEmployeeModalWin() IWDWindowInfo winInfo = wdComponentAPI.getComponentInfo() .findInWindows("EmployeeWindow"); modalWindow = winMan.createModalWindow(winInfo); modalWindow.setTitle("Search Employee"); modalWindow.show(); //@@end } public void destroyEmployeeModalWin( ) { //@@begin destroyEmployeeModalWin() if (modalWindow != null) { modalWindow.destroyInstance(); } //@@end } //@@begin others private IWDWindowManager winMan; private IWDWindow modalWindow; //@@end EmployeeCust public void searchEmployeeById( ) { //@@begin searchEmployeeById() wdThis.wdGetModelCompUsageInterface().getEmployeeById( wdContext.currentEmployeeElement().getEmployeeId()); //@@end } public void copyEmployeeToStudent( ) { //@@begin copyEmployeeToStudent() WDCopyService.copyCorresponding(wdContext.currentEmployeeElement(), wdContext.currentNewStudentElement()); //@@end } Continued on next page 2008 © 2008 SAP AG. All rights reserved. 317
    • Unit 7: Web Dynpro UI Services JA450 EmployeeView public void onActionSearch( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSearch(ServerEvent) wdThis.wdGetEmployeeCustController().searchEmployeeById(); //@@end } public void onActionOk( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionOk(ServerEvent) wdThis.wdGetEmployeeCustController().copyEmployeeToStudent(); wdThis.wdGetStudentCompController().destroyEmployeeModalWin(); //@@end } public void onActionCancel( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionCancel(ServerEvent) wdThis.wdGetStudentCompController().destroyEmployeeModalWin(); //@@end } InputView public void onActionSearch( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSearch(ServerEvent) wdThis.wdGetEmployeeCustController().searchEmployeeById(); wdThis.wdGetStudentCompController().createEmployeeModalWin(); //@@end } 318 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Pop-ups Lesson Summary You • • • 2008 should now be able to: create pop-ups in Web Dynpro. ask the user questions as confirmation dialog. show user-defined modal windows. © 2008 SAP AG. All rights reserved. 319
    • Unit 7: Web Dynpro UI Services JA450 Lesson: Dictionary Based Value Selectors Lesson Overview This lesson introduces the generic UI services for value helps based on dictionary simple types. Lesson Objectives After completing this lesson, you will be able to: • • create value helps in Web Dynpro. change the list of values at runtime. Business Example You want to offer the user a value help for selecting an entry from a list. Simple Value Selector Web Dynpro provides generic UI services for the application development. They enable you to easily create a value help for constants, for example countries or zip codes. Two of these value helps are based on enumerations. Figure 136: Simple Type Enumeration 320 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dictionary Based Value Selectors An enumeration can be defined at design-time in the dictionary as part of a simple type at runtime using modifiable simple types. The value helps generated on top of this are replaceable by each other. The Simple Value Selector (SVS) is the name given to a DropDownByKey UI element that displays a set of values. The SVS is especially useful for small value sets of around 30 entries. Figure 137: DropDownByKey UI Element For the developer creating a SVS means using a simple type as type for a context attribute and bind a DropDownByKey UI element to this attribute. If an enumeration is maintained in the simple type or is created at runtime, the UI element will show all entries to the user. The entries of an enumeration consist of a value and its description like a Java Map. The SVS just shows the descriptions of the enumeration but saves the value in the bound context attribute. The DropDownByKey UI element does not offer to enter values manually. Extended Value Selector The difference between a Simple Value Selector (SVS) and an Extended Value Selector (EVS) in development is just the use of an InputField UI element instead of a DropDownByKey UI element. 2008 © 2008 SAP AG. All rights reserved. 321
    • Unit 7: Web Dynpro UI Services JA450 Figure 138: InputField UI Element The EVS gets useful if the number of entries in the drop-down-list becomes too long to be usable. It displays the set of values in a pop-up realized as modal window. The pop-up shows the values as well as descriptions of the enumeration and offers a sort and filter function. As an input field the user can enter values by keyboard but will get an error message if the entered value is not part of the enumeration. To change the enumeration at runtime you have to move your way from the context attribute to the enumeration of the simple type. The methods used for that are shown in the following picture. 322 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dictionary Based Value Selectors Figure 139: Change Enumeration at Runtime You can choose if you want to only read the entries of the enumeration or also change it. This decision is made by using the methods getSimpleType() followed by getSimpleValueSet() or getModifiableSimpleType() followed by getModifiableSimpleValueSet(). The result will be a reference of type ISimpleValueSet or IModifiableSimpleValueSet. The second one offers methods to clear the enumeration or add additional entries. The methods available are the same as used with Java Maps. A usability-drawback of the EVS is based on the fact, that only the key is displayed within the input field, but not the description. In contrast the SVS displays the description in the DropDownByKey UI element without providing the EVS search and filtering functionality. A combination of both advantages can be achieved by utilizing a calculated context attribute. 2008 © 2008 SAP AG. All rights reserved. 323
    • Unit 7: Web Dynpro UI Services JA450 Figure 140: Extended Value Selector Plus The EVS+ variant is based on introducing a new calculated context attribute with the property readOnly set to true. In the generated getter-method the description for a given value is calculated. The calculated context attribute is only used for UI purposes, so that the user can read the description in another UI element being bound to this attribute. It is important to know that the getter-method of the calculated attribute is called by the Web Dynpro Runtime in the same request response cycle in which the selection in the EVS-UI is handled and in which the EVS popup is closed. Although there is no chance for an application developer to get an action event handler being processed by the Web Dynpro Runtime he can use another hook: the calculated attribute getter. This getter is called by the Web Dynpro Runtime because a UI element in a visible view is bound to it so that the context data has to be retrieved. In the getter-method the following steps have to be implemented: • • • • Access the IWDAttributeInfo of the context attribute used in the EVS Access the ISimpleValueSet provided by the enumeration contained in the context attribute’s simple type Check whether the value stored in the context attribute is valid Return the description for a valid value otherwise return an empty string It is possible to extend this functionality to show the description instead of the value in the input field. Like in the EVS+ variant the calculated attribute is used for showing up the description for the key value which is stored in the 324 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dictionary Based Value Selectors context. In contrast to the EVS and EVS+ the input field itself is bound to the calculated context attribute and not the context attribute storing the value. The context attribute for the value will be calculated by using the setter-method of the calculated attribute. This variant is called EVS++. 2008 © 2008 SAP AG. All rights reserved. 325
    • Unit 7: Web Dynpro UI Services 326 © 2008 SAP AG. All rights reserved. JA450 2008
    • JA450 Lesson: Dictionary Based Value Selectors Exercise 20: Extended Value Selector Exercise Objectives After completing this exercise, you will be able to: • maintain an enumeration of a simple type. • use the enumeration for a value help. • implement the EVS+ pattern Business Example You want to offer a value help for selecting the course id, filling the course title with the according value. Continue with your DC of the last exercise or copy the template to a new name like training.sap.com~uiservices3XX with XX as your group number. Template training.sap.com~uiservices2opt Solution training.sap.com~uiservices3 Task 1: Maintain a list of courses in the enumeration of the simple type CourseID. 1. Navigate to the simple type CourseID of the local dictionary in the Web Dynpro Explorer selecting the Enumeration. 2. Create multiple entries in the enumeration by choose New... entering following values and texts: JA100 SAP J2SE Fundamentals JA400 Introduction to Java EE 5 JA410 Java on SAP NetWeaver Technology 7.1 JA450 Web Dynpro for Java on SAP NetWeaver 7.1 Continued on next page 2008 © 2008 SAP AG. All rights reserved. 327
    • Unit 7: Web Dynpro UI Services JA450 Task 2: Set the context attribute Title in the StudentComp component controller to calculated. Implement the generated getter-method setting the course title by the enumeration text of the simple type CourseID corresponding to the selected course id in the context. 1. Set the property Calculated of the context attribute Title in the node Courses of the component controller to true. Go to the mapped context attribute Title in the CourseView and set the property Read-only to true. 2. Inside the method getCourseTitel() save the reference to the simple type CourseID as a local variable getting the attribute info of the parameter element. 3. Check if the current course id is valid and return the text corresponding to the value of the id using the simple value service of the simple type. 4. Surround the coding of the last step with a try-block catching the exception DdCheckException and returning an empty String on exception. Task 3: Deploy new archive and run your application StudentApp. 1. 328 Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dictionary Based Value Selectors Solution 20: Extended Value Selector Task 1: Maintain a list of courses in the enumeration of the simple type CourseID. 1. Navigate to the simple type CourseID of the local dictionary in the Web Dynpro Explorer selecting the Enumeration. a) 2. Perform as seen in the demonstration of your trainer. Create multiple entries in the enumeration by choose New... entering following values and texts: JA100 SAP J2SE Fundamentals JA400 Introduction to Java EE 5 JA410 Java on SAP NetWeaver Technology 7.1 JA450 Web Dynpro for Java on SAP NetWeaver 7.1 a) Perform as seen in the demonstration of your trainer. Task 2: Set the context attribute Title in the StudentComp component controller to calculated. Implement the generated getter-method setting the course title by the enumeration text of the simple type CourseID corresponding to the selected course id in the context. 1. Set the property Calculated of the context attribute Title in the node Courses of the component controller to true. Go to the mapped context attribute Title in the CourseView and set the property Read-only to true. a) 2. Inside the method getCourseTitel() save the reference to the simple type CourseID as a local variable getting the attribute info of the parameter element. a) 3. See source code extract of the sample solution. Check if the current course id is valid and return the text corresponding to the value of the id using the simple value service of the simple type. a) 4. Perform as seen in the demonstration of your trainer. See source code extract of the sample solution. Surround the coding of the last step with a try-block catching the exception DdCheckException and returning an empty String on exception. a) See source code extract of the sample solution. Continued on next page 2008 © 2008 SAP AG. All rights reserved. 329
    • Unit 7: Web Dynpro UI Services JA450 Task 3: Deploy new archive and run your application StudentApp. 1. Right click on your StudentApp in the Web Dynpro Explorer and Deploy new Archive and Run. Enter the user and password provided by your trainer if needed. a) Perform as seen in the demonstration of your trainer. Result StudentComp public java.lang.String getCoursesTitle( IPrivateStudentComp.ICoursesElement element) { //@@begin getCoursesTitle ISimpleType courseIdSimpleType = element.getAttributePointer( IPublicStudentComp.ICoursesElement.ID).getAttributeInfo() .getSimpleType(); try { courseIdSimpleType.checkValid(element.getID()); String courseTitle = courseIdSimpleType.getSVServices().getValues() .getText(element.getID()); return courseTitle; } catch (DdCheckException e) { return ""; } //@@end } 330 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Lesson: Dictionary Based Value Selectors Lesson Summary You should now be able to: • create value helps in Web Dynpro. • change the list of values at runtime. 2008 © 2008 SAP AG. All rights reserved. 331
    • Unit Summary JA450 Unit Summary You should now be able to: • explain the term internationalization. • understand SAP’s implementation of the XLIFF standard. • make Web Dynpro ready for translation. • show messages on the screen. • distinguish which message type should be used. • create context sensitive messages. • create pop-ups in Web Dynpro. • ask the user questions as confirmation dialog. • show user-defined modal windows. • create value helps in Web Dynpro. • change the list of values at runtime. 332 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Course Summary Course Summary You should now be able to: • • • • • 2008 develop a basic Web Dynpro application create and implement a UI using Views and Windows. create and implement programming logic using Web Dynpro Controllers. interact with a business backend system via Web Service. use and implement Web Dynpro UI Services. © 2008 SAP AG. All rights reserved. 333
    • Course Summary 334 JA450 © 2008 SAP AG. All rights reserved. 2008
    • Appendix 1 Tools and Classes IWDController All controllers created by the Web Dynpro IDE implement this interface. IWDComponent This interface extends IWDController and is implemented by all Web Dynpro components . IWDViewController All view controllers created by the Web Dynpro IDE implement this interface. This interface extends IWDController. Web Dynpro Explorer The use of the Web Dynpro perspective is essential for editing any form of Web Dynpro DC project. The Web Dynpro Explorer displays the logical structure of the entire Web Dynpro DC project. The nodes and sub-nodes represent the hierarchical structure of a Web Dynpro DC project. You open the Web Dynpro Explorer by choosing Windows -> Show View -> Web Dynpro Explorer from the menu. By default, this will add a new tab to the same window in which the Navigator and Project Explorers appear. If you want to activate the Web Dynpro Explorer after working with another tool, then choose the Web Dynpro Explorer tab. 2008 © 2008 SAP AG. All rights reserved. 335
    • Appendix 1: Tools and Classes JA450 Data Modeler Within the Web Dynpro Explorer, you will find the Data Modeler. This is a graphical tool that shows the relationship between the various controllers and models within one Web Dynpro Component. The perspective area that displays the Data Modeler is the Diagram View. The Data Modeler helps you perform the following development tasks: • Controller creation • Declaring the use of a custom controller by another controller • Declaring the use of a model by the component • Nesting Components • Creating context mappings by means of data links To open the Data Modeler, either choose Open Data Modeler from the context menu for the component name in the Web Dynpro Explorer or double click on the component name. Navigation Modeler The Navigation Modeler is a graphical Web Dynpro tool for designing and implementing the navigation relationships that exist between the views in a Window. It is displayed in the Diagram View editor. The Navigation Modeler allows you to create and change the following entities of a Web Dynpro window: • View Sets • Views • Plugs • Navigation Links You can start the Navigation Modeler by either choosing the context menu entry Open Navigation Modeler for the window name in the Web Dynpro Explorer or double clicking on the window name. Window A Web Dynpro window is the superset of all views that could possibly be displayed within the given screen layout. At any one time only a subset of these views is ever visible. View Assembly From the superset of views defined within a Window, only a subset will ever be visible at any one time. The visible subset of views is known the view assembly. This is the set of views that are actually rendered and sent to the client. 336 © 2008 SAP AG. All rights reserved. 2008
    • JA450 Appendix 1: Tools and Classes Web Dynpro Explorer The Web Dynpro Explorer provides various tools for editing all aspects of a controller. Irrespective of the type, all controllers have the following editor tabs: • • • • Properties (Lists the required controllers) Context (Runtime storage area used by all controllers) Methods (User defined instance methods; not for component interface view controllers ) Implementation (Java editor for modifying the controllers standard hook methods) Custom Controller Editor A custom controller has the following specific features: • • A custom controller has no visual interface. Therefore, the editor does not contain a “Layout” tab. A custom controller can raise server-side events. Any method of any controller within the same component can be defined as a listener for these events (once an appropriate usage declaration has first been made). View Controller Editor A Web Dynpro Component may have zero or more view Controllers, and each View Controller has exactly one view layout. A view controller has the following specific features: • • • A View Controller has exactly one visual interface. A View Controller can respond to client side events via runtime objects known as actions. Navigation takes place to and from View Controllers via plugs. Plugs are special event handlers that respond to either inbound or outbound navigation events. View Layout Editor The View Layout Editor is the graphical tool within the Web Dynpro Explorer that allows you to design and build the user interface (UI) part of a view controller. To open the View Layout Editor, choose Edit from the context menu of the view in the Web Dynpro Explorer, Navigation Modeler or Data Modeler. Once the View Layout Editor has been opened, you can edit all the various UI elements within the view layout. If you want to enlarge the work area of any of the editor windows, simply double-click on the editor windows title bar and it will become full screen. To revert to the original size, double-click on the title bar again. 2008 © 2008 SAP AG. All rights reserved. 337
    • Appendix 1: Tools and Classes JA450 Internationalization All Web Dynpro Projects and Development Components (DC) must have a language specified when they are created. This defines the default language for all hard coded texts strings and dictionary metadata. The Project or DC language is used only for translation purposes. It is not referenced at runtime. Message Editor Allows you to create and edit Web Dynpro specific text messages that you want to display on the screen. It is only capable of editing texts in the Projects or DCs default language. It defines messages that are to appear on the user interface via the IWDMessageManager class. 338 © 2008 SAP AG. All rights reserved. 2008
    • Index A Adaptive Remote Function Call Model, 214 Adaptive Web Service Model, 215 Add UI Elements, 45 Application Scenarios, 24 Apply Template, 156 Architecture of Application Server Java, 5 Delete Elements, 170 Dictionary Simple Type, 111 Dictionary Structure, 114 E B Enterprise Java Bean Model, 215 Extended Value Selector, 321 Extended Value Selector Plus, 324 Extended Value Selector Plus Plus, 324 Built-in Simple Types, 108 G C Generic Context API Methods, 172 Getter Method, 181 Centralize Model Execution, 252 Cluster Architecture, 6 Coding Sections, 129 Collection Cardinality, 81, 151 Common Model Interface, 213 Component, 29 Component Model, 12 Component Usage, 249 Confirmation Dialog, 296 Context Attribute Message, 280 Context Mapping, 82 Context Property, 150 Context Structure, 78 Core Data Types, 110 Create Binding, 156 D Data Binding, 85, 96 Data Modeler, 83 Defining Model, 220 Defining Navigation, 42 2008 H Hook Methods, 133 I Invalidate Context Node, 231 L Language Specific Text, 272 Layout Manager, 87 Lead Selection, 137 M Mapping Wizard, 84 Message Area, 282 Message Manager, 277 Message Pool, 277 Message Types, 280 Metamodel and Custom Coding, 22 Modal Window, 298 Model Classes, 222 Model Component, 250 Model Overview, 212 Model Types, 214 © 2008 SAP AG. All rights reserved. 339
    • Index JA450 Model Usage, 225 Model View Controller, 27 Multiple Components, 247 Multiple Views, 58 N Singleton Nodes, 194 Starting Navigation, 48 Supply Function, 196 T Navigation Plugs, 44 NetWeaver Developer Studio, 10 Node Categories, 192 Non-Visual Controllers, 33 Table Selection, 168 Table UI Element, 152 Text Accessor, 277 Typed Context API, 135 Typed Context API Methods, 139 P U Phase Model, 130 Predefined Simple Types, 110 Project Language, 271 UI Container, 86 UI Manipulation, 81 R View Assembly, 61 ViewContainer UI Element, 69 Visual Controllers, 31 Re-entrant Navigation Link, 70 Required Controller, 173 Runtime Local Identification, 274 S SAP NetWeaver Platform, 2 SAP supported XLIFF, 270 Selection Cardinality, 169 Service Controller, 227 Setter Method, 183 Shortcut Variables, 127 Simple Type Enumeration, 320 Simple Value Selector, 321 340 © 2008 SAP AG. All rights reserved. V W Web Dynpro Introduction, 20 Web Service, 217 Web Service Consumer, 220 Web Service Paradigm, 219 Web Service Provider, 219 Window Manager, 295 X XML Language Interchange File Format, 269 2008
    • Feedback SAP AG has made every effort in the preparation of this course to ensure the accuracy and completeness of the materials. If you have any corrections or suggestions for improvement, please record them in the appropriate place in the course evaluation. 2008 © 2008 SAP AG. All rights reserved. 341