Anda di halaman 1dari 32

SAP SAP Developer Network

Education Web Dynpro

A Simple Input Form in Web Dynpro Java Applications


An Explanation and How To Guide on how to create an input form with error validation
Releases: SAP Netweaver Composition Environment 7.1 SAP NetWeaver 7.1

SAP Developer Network

13.05.2008

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. Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, Informix, i5/OS, POWER, POWER5, OpenPower and PowerPC are trademarks or registered trademarks of IBM Corporation. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated in the United States and/or other countries. Oracle is a registered trademark of Oracle Corporation. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc. HTML, XML, XHTML and W3C 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. MaxDB is a trademark of MySQL AB, Sweden. SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

Icons in Body Text


Icon Meaning Caution Example Note Recommendation Syntax

Additional icons are used in SAP Library documentation to help you identify different types of information at a glance. For more information, see Help on Help General Information Classes and Information Classes for Business Information Warehouse on the first page of any version of SAP Library.

Typographic Conventions
Type Style Example text Description Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options. Cross-references to other documentation. Example text EXAMPLE TEXT Emphasized words or phrases in body text, graphic titles, and table titles. Technical names of system objects. These include report names, program names, transaction codes, table names, and key concepts of a programming language when they are surrounded by body text, for example, SELECT and INCLUDE. Output on the screen. This includes file and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools. Exact user entry. These are words or characters that you enter in the system exactly as they appear in the documentation. Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system. Keys on the keyboard, for example, F2 or ENTER.

Example text

Example text <Example text>

EXAMPLE TEXT

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

A Simple Input Form.............................................................................................................. 5 Application Example for Displaying Messages.................................................................... 7 Specifying the Project Structure ....................................................................................... 10 Declarative Development of a Web Dynpro Component ................................................... 11 Defining Simple Type Data Types in the Java Dictionary .............................................. 12 Defining Messages ....................................................................................................... 12 Developing the Component Controller .......................................................................... 15 Developing the FormView View .................................................................................... 20 Developing the EMailEditorView View .......................................................................... 24 Defining the navigation structure ...................................................................................... 26 Implementing the View Controller..................................................................................... 27 Implementing the Controller of the FormView View ....................................................... 28 Implementing the Controller of the EMailEditorView View ............................................. 29

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

A Simple Input Form


The Web Dynpro runtime environment provides generic UI services with which application developers can easily display messages of different types in the Web browser. Using the example of a simple input form, we would like to demonstrate how you can support the user with the task of correcting faulty input values or help the user if he has left out mandatory inputs. In addition, the application example will contain messages that serve the user as a confirmation for successful actions or as a warning. Here it is possible that the application user is shown several messages at the same time, and these may even include error messages. The messages are displayed as a link so that the user can select the link and automatically receive an input recommendation to correct the error in the corresponding UI element. If the input error occurs in a table, for example, the system automatically navigates to the appropriate line, which may not even be visible. At the Web Dynpro component level, messages can be defined using a special Message Editor that is provided by the Web Dynpro tools. A Java class with the name IMessage<ComponentName> is generated from the messages entered there. This class can be used in different controller implementations to access the message texts contained therein. The message editor supports all three message types: error, warning, and standard message. Messages of the standard type are merely of informative character. Errors and other messages can be displayed to the user in the Web browser through different method calls of the Message Manager, which is represented by the interface com.sap.tc.webdynpro.progmodel.api.IWDMessageManager. The Message Manager provides application development with different method types. In the simplest case, errors, warnings, or purely informative messages can be displayed on the user interface by passing a single parameter of the type String. A different type of IWDMessageManager methods displays messages that are based on invalid value attributes. In addition, there are IWDMessageManager methods, which use parameters of the type IWDMessage. Such messages are entered using the Message Editor and displayed at runtime, languagedependent, in the Web browser. For more information on this topic, refer to Error Handling [Extern] and Messages [Extern].

Features
You define messages of the type IWDMessage in the Message Editor of the Web Dynpro tools. You perform various input checks within the controller implementation of a view. You display messages using the interface IWDMessageManager in the Web Browser. You use a non-validating action to delete or reset all possibly incorrect user inputs within a single view at runtime. You set a value transfer between two views by declaring an additional parameter of the type String for inbound and outbound plug instead of using the context mapping function.

Prerequisites
Knowledge Web Dynpro programming model: views, controller contexts and data binding, navigation transitions, actions, Java Dictionary If you do not have the required basic knowledge, work through the sections Creating a Simple Web Dynpro Application [Extern] and Creating an Extended Web Dynpro Application [Extern]. Basic knowledge of the Java programming language.

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

Note: the solution Development Component project can be downloaded for your reference Click here to download Systems, Installations, and Authorizations The SAP NetWeaver Developer Studio is installed on your PC. You have access to the SAP AS Java (Release 7.1)

Process Flow
The development process described is divided into the following sections: Application example for displaying messages Specifying the project structure Declarative development of a view Defining simple types in the Java Dictionary Creating a FormView and EMailEditorView views. In each case, define the controller context of a view, view layout, actions, and binding of events to actions Defining a navigation structure Defining messages in the Message Editor Controller implementation for FormView and EmailEditorView view (these contain methods for input check)

First look at the application example [Page 7] for displaying the error behavior and the message within a Web Dynpro application. The application scenario should be implemented in the Web Dynpro project presented here.

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

Application Example for Displaying Messages


To demonstrate the error behavior and the display of messages within a Web Dynpro application, it is sufficient to have a simple form with three input fields for Name, Birthday, and E-Mail Address. The field Name is marked as mandatory. The following graphic demonstrates this in the application scenario to be developed.

Using the Send E-Mail pushbutton, the user can navigate to a second view in which an e-mail message can be edited and sent. This navigation link should only be followed up by the Web Dynpro runtime environment if the input field for the e-mail address contains an entry. If this is not the case, a corresponding error message is displayed in the form of a link; when the link is generated, it focuses directly on the corresponding error source in this case, the input field for the e-mail address.

The e-mail address entered previously should be contained in the title of the view for editing the e-mail text. Above a navigation link to the input form, you will find the pushbutton Send EMail; use this button to send the e-mail message.

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

After you have pressed the button Send E-Mail, the system displays a message, in the FormView View, that the e-mail message has been sent successfully.

Storing the sample form should involve different input checks, and the results of the checks should be displayed to the user through appropriate message texts. The messages are directly linked with the corresponding UI input elements so that the user can navigate to the appropriate UI element quite easily. The UI elements linked to the error message are also highlighted in color.

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

Entering a name for the user is required. This is marked by an asterisk at the label in front of the name field. The input check should also point the user to the entry of a birthday date in the future.

If the e-mail address is missing, an appropriate warning message is displayed, but if the rest of the data is correct the data will still be saved. If the input check is successful after you have pressed the Save button, the system issues an appropriate message.

By pressing the button Clear Errors, the user can then return to the initial status of the application example, if error messages to be processed are displayed. In this case, the input check is suppressed.

Now start with the Specifying the Project Structure [Page 10], which needs to be setup to create the sample application described here. For more information on the APIs used for error handling as well as their methods, refer to the section Error Handling [Extern].

Dialog Boxes in Web Dynpro Applications NW 7.1

SAP Developer Network

13.05.2008

Specifying the Project Structure


Procedure
First define the following project structure for the sample form:
...

1. Web Dynpro Development Component (DC): Name: wd/tut/errbeh

Note: The Support Component property is mandatory if your Vendor is set to sap.com. 2. Web Dynpro component: Name: SimpleErrorsComp Package: com.sap.demo.wd.tut.errbeh.comp.simpleerrors Note: Web Dynpro components must be created in their own package! 3. Two Web Dynpro views: 4. Views in the Web Dynpro component SimpleErrorsComp:FormView and EMailEditorView Lifespan property (to be set under the Properties tab) View FormView: framework_controled View EmailEditorView: when_visible

For more information on the importance of the lifespan property of a view controller, refer to the section Implementing the EmailEditorView View Controller [Page 29]. Include both views in the window SimpleErrorsWin. Declare the view FormView in the window SimpleErrorsWin as the default view. 5. Web Dynpro application: Name: ErrorBehaviorApp Package: com.sap.demo.wd.tut.errbeh.app

Dialog Boxes in Web Dynpro Applications NW 7.1

10

SAP Developer Network Web-Dynpro component: SimpleErrorsComp Interface view: SimpleErrorsCompInterfaceView Startup plug: Default

13.05.2008

Now start developing the Web Dynpro component declaratively [Page 11].

Declarative Development of a Web Dynpro Component


In the following sections, we will look at the declarative development steps that are required for the Component Controller and including the two views FormView and EmailEditorView in the form sample application. Definition of tree data types of the type Simple Type in the Java Dictionary: In the Java Dictionary, first define three data types of the type Simple Type with the names Name, Birthday, and EmailAddress. When you have done this, you will be able to type their value attributes accordingly in the controller context of the FormView view. Declarative development of the Component Controller. In this section you will declare the Component Controllers context and public methods which will be accessible to other controllers (in this case view controllers). Declarative development of the two views FormView and EMailEditorView: In these sections, you declare the controller context mapping of the views to the component controller context, structure the layout of the two views in the Designer view of the Web Dynpro tools, and declare different actions in order to bind the appropriate UI results to the said views.

The procedure for declarative view development demands basic knowledge of working with the Web Dynpro tools as well as knowledge of the architecture and the programming model for Web Dynpro applications. For more details on this, refer to the sections Creating a Simple Web Dynpro Application [Extern] or Creating an Enhanced Web Dynpro Application [Extern], or take a look at the documentation on the Web Dynpro Tools [Extern].

First, declare the three data types Name, Birthday and EmailAddress [Page 12] in the Java Dictionary.

Dialog Boxes in Web Dynpro Applications NW 7.1

11

SAP Developer Network

13.05.2008

Defining Simple Data Types in the Java Dictionary


Define the data types Name, Birthday and EmailAddress in the Java Dictionary in your Web Dynpro example project:

Property Simple Type Name Name Package Built-In Type Simple Type Representation Text Objects Field Label Simple Type Birthday Name Package Built-In Type Simple Type Representation Text Objects Field Label Simple Type EmailAddress Name Package Built-In Type Simple Type Representation Text Objects Field Label

Value

Name com.sap.sap.demo.wd.tut.errbeh.datatypes String Name

Birthday com.sap.sap.demo.wd.tut.errbeh.datatypes Date Birthday

EmailAddress com.sap.sap.demo.wd.tut.errbeh.datatypes String E-Mail Address

For more information about defining a static Simple Type data type in the Java Dictionary, see Including a Simple Value Selector [Extern].

Defining Messages
The Web Dynpro tools provide a special Message Editor [Extern] for defining messages of different types.

Dialog Boxes in Web Dynpro Applications NW 7.1

12

SAP Developer Network

13.05.2008

A message is defined by a specified key, message type, and message text. The three message types error, warning, and standard are predefined. At runtime, messages of different types are displayed in the Web browser using an appropriate layout for example, specific icons for error, warning, or standard. The message texts can contain arguments. The format of these arguments is defined by the specifications of the java.text.MessageFormat class.

When defining Web Dynpro message texts with placeholders, the following restriction applies: You cannot use element formats in placeholders, but only integer arguments. A message text such as "On {0,date} at {0,time} the number {1} is again {2,number,integer}" is therefore not permitted and must be replaced with "On {0} at {1} the number {2} is again {3}". In Web Dynpro message texts, all parameters are treated as strings. You convert parameters of the type Data and Time into a String value according to the format method of the relevant Java Dictionary type. Therefore, all context attribute values to be displayed in placeholders of message texts must be converted to strings by calling the method IWDNodeElement.getAttributeAsText("<Attribute Name>").

A Java class IMessage<ComponentName> is generated using the messages defined in the Message Editor. This class contains each message as a constant. Message texts can be output at runtime according to the defined settings using the IWDMessageManager interface. The corresponding parameters must be passed for each defined message. The access to the message texts is key-based, the message texts themselves are stored in separate files after the translation process for different languages.

An example: In the Message Editor, you define a message of the type error using the MissingInput key. The message text contains the label text for the entry field as a placeholder. This placeholder is indicated by {0}.

Messages Defined in the Message Editor Message Key MissingInput Message Type error Message Text {0}: Entry of a valid {0} is required for proceeding with the requested service.

You can display the defined message in the implementation of the view controller using the method reportContextAttributeMessage()of the IWDMessageManager interface. The message is contained in the generated IMessageSimpleErrors interface as a constant called MISSING_INPUT. The value of the placeholder {0} is passed in the array {"Name"}. Implementation of the View Controller
... IWDMessageManager msgMgr = wdComponentAPI.getMessageManager(); msgMgr.reportContextAttributeMessage( wdContext.currentContextElement().getAttributePointer(fieldName), IMessageSimpleErrors.MISSING_INPUT, new Object[] {"Name"}); ...

Dialog Boxes in Web Dynpro Applications NW 7.1

13

SAP Developer Network

13.05.2008

After executing this source code, the error message is displayed on the user interface in the Web browser, as follows:

Procedure
...

1. Select the Message Editor of the Web Dynpro component SimpleErrors by choosing the node Message Pool in the Web Dynpro Explorer:

2. Add the following three messages using the Messages Defined in the Message Editor Message Key DateIsInFuture Message Type error

button in the Message Editor:

Message Text Please enter a valid date for field {0}. You entered {1}, which is a date in the future and therefore not a valid date of birth. You did not enter an e-mail address. Therefore, you will not be informed about product news and special offers. {0}: Entry of a valid {0} is required for proceeding with the requested service.

DesiredEMail

warning

MissingInput

error

Dialog Boxes in Web Dynpro Applications NW 7.1

14

SAP Developer Network

13.05.2008

Greeting

text check off the Translate checkbox.

Please enter the email for {0}!

The next step is to implement methods for error handling [Page 12] and in the Component Controller.

Developing the Component Controller


In this section, we will first list the declarative parts of the Component Controller. The description of the components is limited to the basic information items involved.

Context of the Component Controller


Controller Context of the FormView View Context Element Name Type Attribute Property type Value Name
Simple Type defined previously in the Java Dictionary stored in the DataDictionary package with the name com.sap.demo.wd. tut.errbeh.datat ypes

Birthday

Attribute

type

Birthday
Simple type in the Java Dictionary

EMailAddress

Attribute

type

EmailAddress

Dialog Boxes in Web Dynpro Applications NW 7.1

15

SAP Developer Network

13.05.2008

Simple type in the Java Dictionary

EMailText

Attribute

type

string

Implementing the Component Controller methods


Use
The first step to implementing the Component Controller is to define the needed methods that the views will need to execute. In this case we will need to define methods for saving and validating data. The IWDMessageManager interface is used in different controller methods to display messages.

Procedure
Before you can actually start implementing the controller, you must declare four additional methods in the Methods tab of the FormView view.

Method Declarations
...

1. Declare the three methods using the following table (to create the methods go to the Methods tab of the Component Controller editor: Public Methods in the Component Controller SimpleErrors.java Method Name Description save used to validate and then save data. checkMandatory used to check if a mandatory field has been entered. initialize used to initialize the context attributes of the Component Controller. sendEmail used to send an email Type of Return Value void void filedName string Parameter Name Parameter Type

void

void

These are the methods that will be exposed to and called by other controllers, in this case view controllers.

Dialog Boxes in Web Dynpro Applications NW 7.1

16

SAP Developer Network

13.05.2008

Implementing Methods
The public methods save(),checkMandatory(),initialize(), and sendEmail() are defined in the SimpleErrorsComp.java class file since you declaratively defined these in the prior step. Addtionally you will need to manually define two other private methods in the SimpleErrorsComp class, these will be called checkDesired() and checkDateInPast(). The reason these methods will be private is because no other controller needs to call them, they are only used internally by the Component Controller class. The check* methods will validate the data and then issue messages based on the results of the validation. The relevant error message is stored internally by a source code line of the following type:
messageMgr.reportContextAttributeMessage( IWDAttributePointer ptr, IMessageSimpleErrors.<MessageKey>, Object[] arguments);

By calling the report methods of the IWDMessageManager interface, it is possible to use the temporary storage of the Web Dynpro runtime environment for multiple messages and display them together in the Web browser after completing a request/response cycle. If the message text contains arguments, they are passed in an object array (see java.text.MessageFormat). In addition, quite often when a validation error occurs you would like to cancel any navigation to other views from taking place. To cancel navigation the following method exists on the IWDMessageManager class:
messageMgr.cancelNavigation();

1. Implement the private methods checkDesired() and checkDateInPast()as well as a private variable of type IWDMessageManager which will be used to store a reference to Web Dynpros Message Manager service. Make sure to initialize the message manager in the wdDoInit() method. The implementation is shown in the below source code snippet. Note: private methods and variables are defined at the bottom of the Component Controller class between the special tags //@@begin others and //@@end. Note: You will need to add import statements to your implementation so that it can access the classes needed; the easiest way to do this is by using the hot keys Ctrl + Shift + O. You will need to choose the Date type you want to import, Web Dynpro uses java.sql.Date, so be sure to choose that one!

SimpleErrorsComp.java
... public void wdDoInit() { //@@begin wdDoInit() this.messageMgr = wdComponentAPI.getMessageManager(); //@@end } ... // @@begin others private IWDMessageManager messageMgr = null;

Dialog Boxes in Web Dynpro Applications NW 7.1

17

SAP Developer Network


// Private helper methods for validation private void checkDateInPast(java.lang.String fieldName) { Date theDate = (Date) wdContext.currentContextElement() .getAttributeValue(fieldName);

13.05.2008

if (theDate != null) { if (theDate.after(new Date(System.currentTimeMillis()))) { String fieldLabel = wdContext.getNodeInfo().getAttribute( fieldName).getSimpleType().getFieldLabel(); messageMgr.reportContextAttributeMessage( wdContext.currentContextElement().getAttributePointer( fieldName), IMessageSimpleErrorsComp.DATE_IS_IN_FUTURE, new Object[] { fieldLabel, theDate }); messageMgr.cancelNavigation(); } } } private void checkDesired(java.lang.String fieldName) { Object attributeValue = wdContext.currentContextElement() .getAttributeValue(fieldName); if (attributeValue == null) { messageMgr.reportContextAttributeMessage(wdContext .currentContextElement().getAttributePointer(fieldName), IMessageSimpleErrorsComp.DESIRED_E_MAIL, null); } } // @@end } ...

2. Implement the public methods save(), initialize(), and checkMandatory()using the following source code. Note: since we declared these public methods in the Component Controller editor, the method stubs were generated in the java implementation. And code you add to these methods must occur between the special tags inside of the method block, for example: // @@begin checkMandatory() and // @@end for the checkMandatory() method.

SimpleErrorsComp.java
...
// @@begin javadoc:checkMandatory() /** * Method declared by application. */ // @@end public void checkMandatory(java.lang.String fieldName) { // @@begin checkMandatory() Object attributeValue = wdContext.currentContextElement() .getAttributeValue(fieldName); if (attributeValue == null) { String fieldLabel = wdContext.getNodeInfo().getAttribute(fieldName) .getSimpleType().getFieldLabel(); messageMgr.reportContextAttributeMessage(wdContext .currentContextElement().getAttributePointer(fieldName), IMessageSimpleErrorsComp.MISSING_INPUT, new Object[] { fieldLabel }); messageMgr.cancelNavigation(); } // @@end } // @@begin javadoc:initialize() /** * Method declared by application. */

Dialog Boxes in Web Dynpro Applications NW 7.1

18

SAP Developer Network


// @@end public void initialize() { // @@begin initialize() wdContext.currentContextElement().setName(null); wdContext.currentContextElement().setBirthday(new Date(0)); wdContext.currentContextElement().setEMailAddress(null); // @@end }

13.05.2008

// @@begin javadoc:save() /** * Method declared by application. */ // @@end public void save() { // @@begin save() this.checkMandatory(IPublicSimpleErrorsComp.IContextElement.NAME); this.checkDateInPast(IPublicSimpleErrorsComp.IContextElement.BIRTHDAY); this.checkDesired(IPublicSimpleErrorsComp.IContextElement.E_MAIL_ADDRESS); //Check if there are any error messages reported //If not report a success message if (!messageMgr.hasExceptions()) { messageMgr .reportSuccess("The sample form data was successfully saved!"); } // @@end } //@@begin javadoc:sendEmail() /** * Method declared by application. */ //@@end public void sendEmail( ) { //@@begin sendEmail() //Code to actually send an email would reside here in addition //to this success message messageMgr.reportSuccess("The mail was successfully sent to " + wdContext.currentContextElement().getEMailAddress()); //@@end } ...

For the names of the defined constant attributes, constants are created in the corresponding context node interfaces. For example, for the Name attribute, the constant IPublicSimpleErrors.IContextElement.NAME is generated in the root node of the context of the FormView view. The value of this constant macthes the string "Name". At design time, you can thus already avoid runtime errors caused by incorrectly typed attribute names. 3. Call the initialize method from the wdDoInit() method to initialize the context attributes. SimpleErrorsComp.java
... //@@begin javadoc:wdDoInit() /** Hook method called to initialize controller. */ //@@end public void wdDoInit() { //@@begin wdDoInit() this.messageMgr = wdComponentAPI.getMessageManager(); this.initialize(); //@@end } ...

Dialog Boxes in Web Dynpro Applications NW 7.1

19

SAP Developer Network

13.05.2008

Now that the necessary methods have been developed on the Component Controller we can move on to developing the View and View Controllers that will make use of them.

Developing the FormView View


In this section, we will first list the declarative and visual development parts of the FormView view and its controller. The description of the components is limited to the basic information items involved.

Controller Context of the View


In the controller context of the FormView view, you require three attributes for Name, Birthday and E-Mail Address for the form data. These already exist on the Component Controllers context so all we have to do is map the View Controllers context to that of the Component Controllers. To do this you need to open up the Data Modeler by double clicking on the SimpleErrors component icon in the project structure. Once it is opened you can drag Data Link from the View to the Component Controller. This will display a popup window where you can see the context of the View Controller and the Component Controller. You can drag and drop the Component Controllers context elements to context of the View Controller. The following context elements should be mapped from the Component Controller to the View Controller: Name, Birthday, and EMailAddress.

The Data Modeler should look like this when you are done mapping the FormView View Controller to the Component Controller:

Dialog Boxes in Web Dynpro Applications NW 7.1

20

SAP Developer Network

13.05.2008

Layout of the View and Data Binding


The following table lists the structure of the UI elements contained in the layout of the FormView view. The context paths are also specified for included properties of UI elements. Properties linked to the value attributes are marked by the symbol in front of the path specification for the value attribute.

When designing the view layout according to the following table, note that the labelFor property for UI elements of type Label can only be selected if the subsequent InputField UI element has been added.

Layout of the FormView View

Note: all label texts come from the Simple Type definitions created in a previous step. The Email label type here doesnt show up due to a bug with the label being outside the container of the email inputfield. Property Value

Container RootUIElementContainer of type TransparentContainer Properties of Transparent Container layout Layout colCount GridLayout 1

Page Header PageHeader of type PageHeader in UI element RootUIElementContainer Properties of PageHeader title Layout paddingButtom Error and Message Behavior small

Group FormGroup of type Group in UI element RootUIElementContainer Properties of Group - design Properties of Group - layout Properties of Group width Layout colCount Sapcolor GridLayout 75% 2

Caption FormGroup_header of type Caption in UI element FormGroup Properties of Caption text Sample Form

Label NameLabel of type Label in UI element FormGroup Properties of Label labelFor NameInput

Dialog Boxes in Web Dynpro Applications NW 7.1

21

SAP Developer Network

13.05.2008

LayoutData width

25%

Input field NameInput of type InputField in UI element FormGroup Properties of InputField state Properties of InputField value Required Name

Label BirthdayLabel of type Label in UI element FormGroup Properties of Label labelFor BirthdayInput

Input field BirthdayInput of type InputField in UI element FormGroup Properties of InputField value Birthday

Label EmailAddressLabel of type Label in UI element FormGroup Properties of Label labelFor EmailAddressInput

Container EMailContainer of type TransparentContainer in UI element FormGroup Properties of TransparentContainer layout FlowLayout

Input field EMailAddressInput of type InputField in UI element EMailContainer Properties of InputField value EMailAddress

Pushbutton SendEMailButton of type Button in UI element EMailContainer LayoutData cellDesign lPad

Horizontal Container HorizontalContainer of type HorizontalContainer in UI element FormGroup LayoutData colSpan 2

Button Container ButtonRow of type ButtonRow in UI element FormGroup LayoutData colSpan LayoutData hAlign 2 center

Pushbutton SaveButton of type Button in UI element ButtonRow Pushbutton ClearButton of type Button in UI element ButtonRow Container MessageTranspContainer of type TransparentContainer in UI element RootUIElementContainer Properties of TransparentContainer width Properties of TransparentContainer - layout LayoutData paddingTop 75% GridLayout Medium

Message area MessageArea of type MessageArea in UI element MessageTransparentContainer

Use UI element MessageArea to define position of the messages output by Message Manager. If you do not do this, the default position for all message texts is the final position in the view layout.

Dialog Boxes in Web Dynpro Applications NW 7.1

22

SAP Developer Network

13.05.2008

Actions and Binding Events


In the view controller, define the listed actions and link the corresponding events of UI elements to these actions. Controller Context of the FormView View Name of the Action Clear Save SendEMail Text Clear Errors Save Send E-Mail Validation unchecked checked checked Event Handler onActionClear onActionSave onActionSendEMail

Here, the Clear action is declared as a non-validating action. This ensures that no data entered by the user is validated until this data is stored in the context. This makes it possible to delete the entries in the input fields linked to the individual value attributes, or to reset them to the values defined originally, even if these are not valid that is, if validation has failed.

Afterwards, the events in individual UI elements can be linked to the previously defined actions. The buttons will inherit the text you entered for the Actions in the previous step! Binding Events to Actions in the FormView View UI Element Name SendEMailButton SaveButton ClearButton Event Name onAction onAction onAction Action SendEMail Save Clear

Now repeat the above procedure in the EmailEditorView View [Page 24].

Dialog Boxes in Web Dynpro Applications NW 7.1

23

SAP Developer Network

13.05.2008

Developing the EmailEditorView View


View Controller Context
In the context of the EmailEditorView view, the attributes EMailText, EmailAddress, and Greeting are to be declared. The EMailAddress and EMailText attributes must be mapped to the Component Controllers context attribute with the same names. This can be done in the Data Modeler. The other attribute Greeting is only used in this view as a local variable thus can be defined here with no mapping. The Greetings attribute needs to be defined with the View Controller editor on the Context tab. Controller Context of the EmailEditorView View Context Element EMailAddress Type Attribute Property type Value Mapped to Component Controllers context attribute also named EMailAddress. string string

EMailText Greeting

Attribute Attribute

type type

Layout of the View


The following table contains the hierarchy of the UI elements contained in the EmailEditorView view. Properties linked to the value attributes are marked by the symbol front of the path specification of the value attribute. Layout of the EmailEditorView View in

Dialog Boxes in Web Dynpro Applications NW 7.1

24

SAP Developer Network

13.05.2008

Property

Value

Container RootUIElementContainer of the type TransparentContainer Properties of Transparent Container - layout Layout - colCount GridLayout 1

Page Header PageHeader of type PageHeader in UI element RootUIElementContainer Properties of PageHeader title LayoutData paddingBottom Error and Message Behavior small

TextView GreetingTextView of the type TextView in the UI element RootUIElementContainer Properties of TextView design Properties of TextView value LayoutData paddingBottom header1 EMailText large

Label EMailTextLabel of the type Label in the UI element RootUIElementContainer Properties of Label text Properties of Label labelFor E-Mail Text EMailEditorText

Input field EMailEditorText of the type TextEdit in the UI-element RootUIElementContainer Properties of TextEdit cols Properties of TextEdit rows Properties of TextEdit value 60 12 EMailText

Pushbutton SendEMailButton of the type Button in the UI element RootUIElementContainer Link LinkToFormView of the type LinkToAction in the UI element RootUIElementContainer Properties of LinkToAction paddingTop medium

Dialog Boxes in Web Dynpro Applications NW 7.1

25

SAP Developer Network

13.05.2008

Actions and Binding Events


In the view controller, define the two actions GoBack and SendEMail: Controller Context of the EMailEditorView View Name of the Action GoBack SendEMail Text Go back to sample form Send E-Mail Validation checked checked Event Handler onActionGoBack onActionSendEMail

Afterwards, link the onAction events of two UI elements to the two actions defined previously. Linking Events to Actions in the EmailEditorView View UI Element Name SendEMailButton LinkToForm Event Name onAction onAction Action SendEMail GoBack

The next step is to define the navigation structure between the two views FormView and EMailEditorView [Page 26].

Defining the navigation structure


You can easily create the navigation structure within the form example application, because you must only define two navigation links between the two views FormView and EMailEditorView and the corresponding inbound plugs and outbound plugs.
Window of the Web Dynpro component SimpleErrors

Form view

EMailEditor view

Outbound plug

Inbound plug

Navigation link

To create your navigation double click on the window SimpleErrorsWindow in the Web Dynpro project structure. This will open up the Window Editor:

Dialog Boxes in Web Dynpro Applications NW 7.1

26

SAP Developer Network

13.05.2008

Note: The you may initial see only one view in the window diagram, but this is most likely because the are overlapping each other. Simply drag the top view to a different location on the diagram. If there is only one view showing up, this means the other view hasnt been embedded in the window yet. To create the inbound and outbound plugs with navigation links, all you have to do is select the Create Link from the tool bar and then drag and drop from one view to the other. This will create the and outbound plug in the view you dragged from (named Out) and an inbound plug to the view you dragged to (named In). Below is an example of dragging a navigation link from the FormView view to the EmailEditorView view.

Now create another link fromt the EmailEditorView view to the FormView view. Note: You should first move the inbound and outbound plugs that were already created. This is because when you create the 2nd link the plugs it generate will be created on top of the plugs that were already created and you wont be able to see both sets of plugs and links (one will be beneath the other).

The declarative part of the view development is now almost completed. The declaration of the methods required for the input checks in the controller of the FormView view is described under Implementing the Controller of the FormView View [Page 28].

Implementing the View Controller


You must implement two view controllers in the example application to display messages. Controller of the FormView view: Event handlers for the actions Save, Clear, and SendEMail Controller of the EmailEditorView view:

Dialog Boxes in Web Dynpro Applications NW 7.1

27

SAP Developer Network

13.05.2008

Event handlers for the EditorIn inbound plug Event handlers for the actions SendEMail and GoBack

The next step is to implement the controller of the FormView view [Page 28] of the example application.

Implementing the Controller of the FormView View

Use
The implementation of the FormView view controller is divided up into the following procedures: The input check for the input fields Name, Birthday, and E-Mail Address is started in the event handler for the Save action using the appropriate method call to the save() method on the Component Controller. The user should be able to reset all input fields by selecting Clear Errors, even if they contain incorrect entries The navigation to the EMailEditorView should only be possible when the user has entered an e-mail address

Note that setting the state=required property for the input field NameInput on the user interface merely results in the field being specially marked. If the user leaves the input field blank, no error is displayed by the Web Dynpro runtime environment, regardless of the defined value of the property (normal or required). The application developer is responsible for checking any input made using application code (method checkMandatory()).

Procedure
Implement the Event Handlers to call appropriate methods on the Component Controller and fire outbound plugs where necessary.

Event Handling
1. Implement the method onActionSave() method. Have it call the Component Controllers save() method. FormView.java
... /** declared validating event handler */ public void onActionSave(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSave(ServerEvent) wdThis.wdGetSimpleErrorsCompController().save (); //@@end } ...

Navigation to the input of an e-mail message in the EMailEditor view is only started in the Web Dynpro runtime environment if no error is reported in the checkMandatory() method.

Dialog Boxes in Web Dynpro Applications NW 7.1

28

SAP Developer Network

13.05.2008

2. The implementation of the onActionSendEMail(IWDCustomEvent wdEvent) method contains two lines of source code, one to call the checkMandatory() method on the Component Controller, and the other to fire the outbound plug: FormView.java
... /** declared validating event handler */ public void onActionSendEMail(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSendEMail(ServerEvent) wdThis.wdGetSimpleErrorsCompController() .checkMandatory(IPrivateFormView.IContextElement.E_MAIL_ADDRESS); wdThis.wdFirePlugOut(); //@@end } ...

In the last step, the event handler is implemented for the non-validating Clear action. Such an event handler is called before individual user entries are validated and stored in the controller context. This allows you to initialize the context again despite incorrect user input. 3. Add the following source code to the view controller FormView: FormView.java
... //@@begin javadoc:onActionClear(ServerEvent) /** declared non validating event handler */ //@@end public void onActionClear(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionClear(ServerEvent) // Re-initialize this component controller's context wdThis.wdGetSimpleErrorsCompController().initialize(); //@@end } ...

The next step is the implementation of the EMailEditor view controller [Page 29].

Implementing the Controller of the EMailEditorView View


You must implement the following event handler methods: Event handler of the In inbound plug: The value attributes are initialized using an email address, which is available through context mapping of the Component Controllers context. Event handler of the SendEMail action: A success message is displayed after the email message has been sent and the navigation link back to the FormView view has been triggered. Event handler of the GoBack action: The navigation link back to the FormView view is triggered without displaying a message.

Dialog Boxes in Web Dynpro Applications NW 7.1

29

SAP Developer Network

13.05.2008

Procedure
After triggering the Out outbound plug in the controller of the FormView view, the inbound plug event In is executed on the EMailEditor view. Its event handler is then executed. Here we can access the context mapped email address and use it to build a String that contains a greeting.
...

1. Get the EmailAddress attribute and initialize the Greeting in the event handler of the In inbound plug. The TextAccessor service is used to generate the string from the message pool using the message Greeting that was created in a previous step. Generating the message in this way makes it possible to support multiple languages if needed. EMailEditorView.java
... /** declared validating event handler */ public void onPlugIn(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent, java.lang.String eMailAddress ) { //@@begin onPlugDisplayEditorIn(ServerEvent)
//Build a greeting string using the email address entered. String eMailAddress = wdContext.currentContextElement().getEMailAddress(); String greeting = wdComponentAPI.getTextAccessor().getText(IMessageSimpleErrorsComp.GREETING, new Object[]{eMailAddress}); wdContext.currentContextElement().setGreeting(greeting);

//@@end } ...

Navigation back to the FormView view should trigger an appropriate success message when the user selects the Send E-Mail button. This is why the method reportSuccess(String message) of the IWDMessageManager interface is called in the Component Controllers sendEmail() method. After selecting the link Go back to sample form, the FormView view is displayed again. Both action event handler methods onActionGoBack() and onActionSendEMail() will navigate back to the FormView view. The only difference between the two methods being that the onActionSendEMail() should call the sendEmail() method on the Component Controller (which in turn should send an email and report any success/error messages). EMailEditorView.java
... /** declared validating event handler */ public void onActionGoBack(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent) { //@@begin onActionGoBack(ServerEvent) wdThis.wdFirePlugOut(); //@@end } /** declared validating event handler */ public void onActionSendEMail(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ) { //@@begin onActionSendEMail(ServerEvent) wdThis.wdGetSimpleErrorsCompController().sendEmail(); wdThis.wdFirePlugOut(); //@@end } ...

Dialog Boxes in Web Dynpro Applications NW 7.1

30

SAP Developer Network

13.05.2008

View Lifetime
When specifying the project structure, you select different values for the Lifespan property of the two view controllers. You select framework_controled for the controller of the FormView view and when_visible for the controller of the EMailEditor view. Both views are embedded in a single window so that only one single view is visible at any given time. When the user calls the application, the FormView view is displayed, because it is declared as the default view in the SimpleErrors window.
Window of the Web Dynpro component SimpleErrors

Form view

EMailEditor view

Outbound plug

Inbound plug

Navigation link

This means that, at runtime, the controller of the FormView view and its context remain after navigating to the EMailEditor view and back to the FormView view. Therefore, the previously entered form data still exists in the input fields. If the Lifespan property of the FormView view controller was when_visible, the controller would be newly created and initialized when the user navigates back from the EMailEditor view. In this case, the entered form data would not be available without context mapping to a superordinate controller context. After entering an e-mail message in the EMailEditor view for the first time, return to this view for a second time using navigation. The TextEdit UI element will be empty because the corresponding view controller was newly created. Therefore, the EMailText value attribute also contains an empty string value.

An application example of the selection of the Lifespan property framework_controled is the embedding of views in multiple tabs of a Tabstrip UI element. We recommend that not every selection of a different tab automatically terminates the view controller lifecycle and begins the lifecycle of another view controller, as is the case when the Lifespan property when_visible is assigned to the corresponding views.

Dialog Boxes in Web Dynpro Applications NW 7.1

31

SAP Developer Network

13.05.2008

User

Form view controller


Start application Create view controller

EMailEditor view controller

Navigate to EMailEditor view

Create view controller

Navigate back to Form view

Destroy view controller

Lifespan property

framework_ controlled

when_visible

Congratulations! You have finished this tutorial on creating a simple form with error handling. You should now be able to deploy, run and test your application.

Dialog Boxes in Web Dynpro Applications NW 7.1

32