a simple input form in webdynpro java
TRANSCRIPT
![Page 1: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/1.jpg)
SAP® EducationSAP Developer Network Web Dynpro
A Simple InputForm in WebDynpro JavaApplicationsAn Explanation and How ToGuide on how to create an inputform with error validation
Releases: SAP Netweaver Composition Environment 7.1
SAP NetWeaver 7.1
![Page 2: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/2.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 2
Copyright
© Copyright 2008 SAP AG. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or for any purposewithout the express permission of SAP AG. The information contained herein may bechanged without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietarysoftware components of other software vendors.
Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of MicrosoftCorporation.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 PowerPCare trademarks or registered trademarks of IBM Corporation.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registeredtrademarks 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 aretrademarks or registered trademarks of Citrix Systems, Inc.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, WorldWide 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 fortechnology 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 andservices mentioned herein as well as their respective logos are trademarks or registeredtrademarks of SAP AG in Germany and in several other countries all over the world. All otherproduct and service names mentioned are the trademarks of their respective companies.Data contained in this document serves informational purposes only. National productspecifications may vary.
These materials are subject to change without notice. These materials are provided by SAPAG and its affiliated companies ("SAP Group") for informational purposes only, withoutrepresentation or warranty of any kind, and SAP Group shall not be liable for errors oromissions with respect to the materials. The only warranties for SAP Group products andservices are those that are set forth in the express warranty statements accompanying suchproducts and services, if any. Nothing herein should be construed as constituting anadditional warranty.
![Page 3: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/3.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 3
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 ofinformation at a glance. For more information, see Help on Help General InformationClasses and Information Classes for Business Information Warehouse on the first page of anyversion of SAP Library.
Typographic Conventions
Type Style Description
Example text Words or characters quoted from the screen. These include fieldnames, screen titles, pushbuttons labels, menu names, menu paths,and menu options.
Cross-references to other documentation.Example text Emphasized words or phrases in body text, graphic titles, and table
titles.
EXAMPLE TEXT Technical names of system objects. These include report names,program names, transaction codes, table names, and key concepts of aprogramming language when they are surrounded by body text, forexample, SELECT and INCLUDE.
Example text Output on the screen. This includes file and directory names and theirpaths, messages, names of variables and parameters, source text, andnames of installation, upgrade and database tools.
Example text Exact user entry. These are words or characters that you enter in thesystem exactly as they appear in the documentation.
<Example text> Variable user entry. Angle brackets indicate that you replace thesewords and characters with appropriate entries to make entries in thesystem.
EXAMPLE TEXT Keys on the keyboard, for example, F2 or ENTER.
![Page 4: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/4.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 4
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
![Page 5: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/5.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 5
A Simple Input FormThe Web Dynpro runtime environment provides generic UI services with which applicationdevelopers can easily display messages of different types in the Web browser. Using theexample of a simple input form, we would like to demonstrate how you can support the userwith the task of correcting faulty input values or help the user if he has left out mandatoryinputs. In addition, the application example will contain messages that serve the user as aconfirmation for successful actions or as a warning. Here it is possible that the applicationuser is shown several messages at the same time, and these may even include errormessages. The messages are displayed as a link so that the user can select the link andautomatically receive an input recommendation to correct the error in the corresponding UIelement. If the input error occurs in a table, for example, the system automatically navigatesto the appropriate line, which may not even be visible.
At the Web Dynpro component level, messages can be defined using a special MessageEditor that is provided by the Web Dynpro tools. A Java class with the nameIMessage<ComponentName> is generated from the messages entered there. This class canbe used in different controller implementations to access the message texts containedtherein. The message editor supports all three message types: error, warning, and standardmessage. 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 differentmethod calls of the Message Manager, which is represented by the interfacecom.sap.tc.webdynpro.progmodel.api.IWDMessageManager. The Message Managerprovides 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 asingle parameter of the type String. A different type of IWDMessageManager methods displaysmessages that are based on invalid value attributes. In addition, there areIWDMessageManager methods, which use parameters of the type IWDMessage. Suchmessages are entered using the Message Editor and displayed at runtime, language-dependent, in the Web browser. For more information on this topic, refer to Error Handling[Extern] and Messages [Extern].
FeaturesYou define messages of the type IWDMessage in the Message Editor of the WebDynpro 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 inputswithin a single view at runtime.
You set a value transfer between two views by declaring an additional parameter of thetype String for inbound and outbound plug instead of using the context mappingfunction.
PrerequisitesKnowledge
Web Dynpro programming model: views, controller contexts and data binding,navigation transitions, actions, Java DictionaryIf you do not have the required basic knowledge, work through the sections Creating aSimple Web Dynpro Application [Extern] and Creating an Extended Web DynproApplication [Extern].
Basic knowledge of the Java programming language.
![Page 6: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/6.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 6
Note: the solution Development Component project can be downloaded for yourreference – 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 FlowThe 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 containmethods for input check)
First look at the application example [Page 7] for displaying the error behavior andthe message within a Web Dynpro application. The application scenario should beimplemented in the Web Dynpro project presented here.
![Page 7: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/7.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 7
Application Example for Displaying MessagesTo demonstrate the error behavior and the display of messages within a Web Dynproapplication, it is sufficient to have a simple form with three input fields for Name, Birthday, andE-Mail Address. The field Name is marked as mandatory. The following graphic demonstratesthis 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-mailmessage can be edited and sent. This navigation link should only be followed up by the WebDynpro runtime environment if the input field for the e-mail address contains an entry. If this isnot the case, a corresponding error message is displayed in the form of a link; when the link isgenerated, it focuses directly on the corresponding error source – in this case, the input fieldfor the e-mail address.
The e-mail address entered previously should be contained in the title of the view for editingthe e-mail text. Above a navigation link to the input form, you will find the pushbutton Send E-Mail; use this button to send the e-mail message.
![Page 8: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/8.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 8
After you have pressed the button Send E-Mail, the system displays a message, in theFormView View, that the e-mail message has been sent successfully.
Storing the sample form should involve different input checks, and the results of the checksshould be displayed to the user through appropriate message texts. The messages aredirectly linked with the corresponding UI input elements so that the user can navigate to theappropriate UI element quite easily. The UI elements linked to the error message are alsohighlighted in color.
![Page 9: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/9.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 9
Entering a name for the user is required. This is marked by an asterisk at the label in front ofthe 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 restof 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 anappropriate message.
By pressing the button Clear Errors, the user can then return to the initial status of theapplication example, if error messages to be processed are displayed. In this case, the inputcheck is suppressed.
Now start with the Specifying the Project Structure [Page 10], which needs to besetup to create the sample application described here.
For more information on the APIs used for error handling as well as their methods, refer to thesection Error Handling [Extern].
![Page 10: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/10.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 10
Specifying the Project StructureProcedureFirst 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 andEMailEditorView
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 viewcontroller, refer to the section Implementing the EmailEditorView ViewController [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
![Page 11: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/11.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 11
Web-Dynpro component: SimpleErrorsComp
Interface view: SimpleErrorsCompInterfaceView
Startup plug: Default
Now start developing the Web Dynpro component declaratively [Page 11].
Declarative Development of a Web DynproComponentIn the following sections, we will look at the declarative development steps that are requiredfor the Component Controller and including the two views FormView and EmailEditorView inthe form sample application.
Definition of tree data types of the type Simple Type in the Java Dictionary: Inthe Java Dictionary, first define three data types of the type Simple Type with thenames Name, Birthday, and EmailAddress. When you have done this, you willbe able to type their value attributes accordingly in the controller context of theFormView view.
Declarative development of the Component Controller. In this section you willdeclare the Component Controller’s context and public methods which will beaccessible to other controllers (in this case view controllers).
Declarative development of the two views FormView and EMailEditorView: Inthese sections, you declare the controller context mapping of the views to thecomponent controller context, structure the layout of the two views in the Designerview of the Web Dynpro tools, and declare different actions in order to bind theappropriate UI results to the said views.
The procedure for declarative view development demands basic knowledge ofworking with the Web Dynpro tools as well as knowledge of the architecture andthe programming model for Web Dynpro applications. For more details on this,refer to the sections Creating a Simple Web Dynpro Application [Extern] orCreating an Enhanced Web Dynpro Application [Extern], or take a look at thedocumentation on the Web Dynpro Tools [Extern].
First, declare the three data types Name, Birthday and EmailAddress [Page 12] inthe Java Dictionary.
![Page 12: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/12.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 12
Defining Simple Data Types in the Java DictionaryDefine the data types Name, Birthday and EmailAddress in the Java Dictionary in yourWeb Dynpro example project:
Property Value
Simple Type Name
Name Name
Package com.sap.sap.demo.wd.tut.errbeh.datatypes
Built-In Type String
Simple Type Representation – TextObjects – Field Label
Name
Simple Type Birthday
Name Birthday
Package com.sap.sap.demo.wd.tut.errbeh.datatypes
Built-In Type Date
Simple Type Representation – TextObjects – Field Label
Birthday
Simple Type EmailAddress
Name EmailAddress
Package com.sap.sap.demo.wd.tut.errbeh.datatypes
Built-In Type String
Simple Type Representation – TextObjects – Field Label
E-Mail Address
For more information about defining a static Simple Type data type in the JavaDictionary, see Including a Simple Value Selector [Extern].
Defining MessagesThe Web Dynpro tools provide a special Message Editor [Extern] for defining messages ofdifferent types.
![Page 13: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/13.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 13
A message is defined by a specified key, message type, and message text. The threemessage types error, warning, and standard are predefined. At runtime, messages ofdifferent 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 thespecifications of the java.text.MessageFormat class.
When defining Web Dynpro message texts with placeholders, the followingrestriction applies: You cannot use element formats in placeholders, butonly integer arguments. A message text such as "On {0,date} at{0,time} the number {1} is again {2,number,integer}" istherefore not permitted and must be replaced with "On {0} at {1} thenumber {2} is again {3}".
In Web Dynpro message texts, all parameters are treated as strings. Youconvert parameters of the type Data and Time into a String value according tothe format method of the relevant Java Dictionary type.
Therefore, all context attribute values to be displayed in placeholders ofmessage texts must be converted to strings by calling the methodIWDNodeElement.getAttributeAsText("<Attribute Name>").
A Java class IMessage<ComponentName> is generated using the messages defined in theMessage Editor. This class contains each message as a constant. Message texts can beoutput at runtime according to the defined settings using the IWDMessageManager interface.The corresponding parameters must be passed for each defined message. The access to themessage texts is key-based, the message texts themselves are stored in separate files afterthe translation process for different languages.
An example: In the Message Editor, you define a message of the type errorusing the MissingInput key. The message text contains the label text for theentry field as a placeholder. This placeholder is indicated by {0}.
Messages Defined in the Message Editor
Message Key Message Type Message Text
MissingInput error {0}: Entry of a valid {0} is required forproceeding with the requested service.
You can display the defined message in the implementation of the viewcontroller using the method reportContextAttributeMessage()of theIWDMessageManager interface. The message is contained in the generatedIMessageSimpleErrors interface as a constant called MISSING_INPUT. Thevalue 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"});
...
![Page 14: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/14.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 14
After executing this source code, the error message is displayed on the userinterface in the Web browser, as follows:
Procedure...
1. Select the Message Editor of the Web Dynpro component SimpleErrors by choosingthe node Message Pool in the Web Dynpro Explorer:
2. Add the following three messages using the button in the Message Editor:
Messages Defined in the Message Editor
Message Key MessageType Message Text
DateIsInFuture error Please enter a valid date for field {0}. You entered{1}, which is a date in the future and therefore not avalid date of birth.
DesiredEMail warning You did not enter an e-mail address. Therefore, youwill not be informed about product news and specialoffers.
MissingInput error {0}: Entry of a valid {0} is required for proceeding withthe requested service.
![Page 15: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/15.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 15
Greeting text – checkoff theTranslatecheckbox.
Please enter the email for {0}!
The next step is to implement methods for error handling [Page 12] and in theComponent Controller.
Developing the Component ControllerIn this section, we will first list the declarative parts of the Component Controller. Thedescription of the components is limited to the basic information items involved.
Context of the Component ControllerController Context of the FormView View
Context Element Type Property Value
Name Attribute type Name
Simple Type definedpreviously in the JavaDictionary stored inthe DataDictionarypackage with thenamecom.sap.demo.wd.tut.errbeh.datatypes
Birthday Attribute type Birthday
Simple type in theJava Dictionary
EMailAddress Attribute type EmailAddress
![Page 16: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/16.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 16
Simple type in theJava Dictionary
EMailText Attribute type string
Implementing the Component Controller methodsUseThe first step to implementing the Component Controller is to define the needed methods thatthe views will need to execute. In this case we will need to define methods for saving andvalidating data.
The IWDMessageManager interface is used in different controller methods to displaymessages.
ProcedureBefore you can actually start implementing the controller, you must declare four additionalmethods 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 theMethods tab of the Component Controller editor:
Public Methods in the Component Controller SimpleErrors.java
Method Name -Description
Type of ReturnValue
Parameter Name Parameter Type
save – used to validateand then save data.
void
checkMandatory –used to check if amandatory field hasbeen entered.
void filedName string
initialize – used toinitialize the contextattributes of theComponent Controller.
void
sendEmail – used tosend an email
void
These are the methods that will be exposed to and called by other controllers, in this caseview controllers.
![Page 17: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/17.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 17
Implementing MethodsThe public methods save(),checkMandatory(),initialize(), and sendEmail()are defined in the SimpleErrorsComp.java class file since you declaratively defined these inthe prior step. Addtionally you will need to manually define two other private methods in theSimpleErrorsComp 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 willvalidate 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 usethe temporary storage of the Web Dynpro runtime environment for multiple messages anddisplay 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 (seejava.text.MessageFormat).
In addition, quite often when a validation error occurs you would like to cancel any navigationto other views from taking place. To cancel navigation the following method exists on theIWDMessageManager class:messageMgr.cancelNavigation();
1. Implement the private methods checkDesired() and checkDateInPast()as wellas a private variable of type IWDMessageManager which will be used to store areference to Web Dynpro’s Message Manager service. Make sure to initialize themessage manager in the wdDoInit() method. The implementation is shown in thebelow source code snippet.
Note: private methods and variables are defined at the bottom of the ComponentController class between the special tags //@@begin others and //@@end.
Note: You will need to add import statements to your implementation so that it canaccess 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 usesjava.sql.Date, so be sure to choose that one!
SimpleErrorsComp.java...
public void wdDoInit() {
//@@begin wdDoInit()this.messageMgr = wdComponentAPI.getMessageManager();
//@@end }
...
// @@begin othersprivate IWDMessageManager messageMgr = null;
![Page 18: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/18.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 18
// Private helper methods for validationprivate void checkDateInPast(java.lang.String fieldName) {
Date theDate = (Date) wdContext.currentContextElement().getAttributeValue(fieldName);
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(), andcheckMandatory()using the following source code. Note: since we declared thesepublic methods in the Component Controller editor, the method stubs were generatedin the java implementation. And code you add to these methods must occur betweenthe special tags inside of the method block, for example: // @@begincheckMandatory() and // @@end for the checkMandatory() method.
SimpleErrorsComp.java...
// @@begin javadoc:checkMandatory()/*** Method declared by application.*/
// @@endpublic 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.*/
![Page 19: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/19.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 19
// @@endpublic void initialize() {
// @@begin initialize()wdContext.currentContextElement().setName(null);wdContext.currentContextElement().setBirthday(new Date(0));wdContext.currentContextElement().setEMailAddress(null);// @@end
}
// @@begin javadoc:save()/*** Method declared by application.*/
// @@endpublic 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.*/
//@@endpublic 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 thecorresponding context node interfaces. For example, for the Name attribute, theconstant IPublicSimpleErrors.IContextElement.NAME is generated in the rootnode of the context of the FormView view. The value of this constant macthes thestring "Name". At design time, you can thus already avoid runtime errors caused byincorrectly typed attribute names.
3. Call the initialize method from the wdDoInit() method to initialize the contextattributes.
SimpleErrorsComp.java...
//@@begin javadoc:wdDoInit()/** Hook method called to initialize controller. */
//@@endpublic void wdDoInit()
{//@@begin wdDoInit()this.messageMgr = wdComponentAPI.getMessageManager();this.initialize();
//@@end
}
...
![Page 20: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/20.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 20
Now that the necessary methods have been developed on the Component Controller we canmove on to developing the View and View Controllers that will make use of them.
Developing the FormView ViewIn this section, we will first list the declarative and visual development parts of the FormViewview and its controller. The description of the components is limited to the basic informationitems involved.
Controller Context of the ViewIn the controller context of the FormView view, you require three attributes for Name, Birthdayand E-Mail Address for the form data. These already exist on the Component Controller’scontext so all we have to do is map the View Controller’s context to that of the ComponentController’s.
To do this you need to open up the Data Modeler by double clicking on the SimpleErrorscomponent icon in the project structure. Once it is opened you can drag Data Link from theView to the Component Controller. This will display a popup window where you can see thecontext of the View Controller and the Component Controller. You can drag and drop theComponent Controller’s context elements to context of the View Controller.
The following context elements should be mapped from the Component Controller to the ViewController: Name, Birthday, and EMailAddress.
The Data Modeler should look like this when you are done mapping the FormView ViewController to the Component Controller:
![Page 21: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/21.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 21
Layout of the View and Data BindingThe following table lists the structure of the UI elements contained in the layout of theFormView 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 pathspecification for the value attribute.
When designing the view layout according to the following table, note that thelabelFor property for UI elements of type Label can only be selected if thesubsequent 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 Emaillabel type here doesn’t show up due to a bug with the label being outside the container of the emailinputfield.
Property Value
Container RootUIElementContainer of type TransparentContainer
Properties of Transparent Container –layout
GridLayout
Layout – colCount 1
Page Header PageHeader of type PageHeader in UI element RootUIElementContainer
Properties of PageHeader – title Error and Message Behavior
Layout – paddingButtom small
Group FormGroup of type Group in UI element RootUIElementContainer
Properties of Group - design Sapcolor
Properties of Group - layout GridLayout
Properties of Group – width 75%
Layout – colCount 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
![Page 22: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/22.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 22
LayoutData – width 25%
Input field NameInput of type InputField in UI element FormGroup
Properties of InputField – state Required
Properties of InputField – value 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 elementFormGroup
LayoutData – colSpan 2
Button Container ButtonRow of type ButtonRow in UI element FormGroup
LayoutData – colSpan 2
LayoutData – hAlign 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 elementRootUIElementContainer
Properties of TransparentContainer – width 75%
Properties of TransparentContainer - layout GridLayout
LayoutData – paddingTop Medium
Message area MessageArea of type MessageArea in UI element MessageTransparentContainer
Use UI element MessageArea to define position of the messages output byMessage Manager. If you do not do this, the default position for all messagetexts is the final position in the view layout.
![Page 23: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/23.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 23
Actions and Binding EventsIn the view controller, define the listed actions and link the corresponding events of UIelements to these actions.
Controller Context of the FormView View
Name of the Action Text Validation Event Handler
Clear Clear Errors unchecked onActionClear
Save Save checked onActionSave
SendEMail Send E-Mail checked onActionSendEMail
Here, the Clear action is declared as a non-validating action. This ensures thatno 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 theindividual value attributes, or to reset them to the values defined originally, evenif these are not valid – that is, if validation has failed.
Afterwards, the events in individual UI elements can be linked to the previouslydefined actions. The buttons will inherit the text you entered for the Actions inthe previous step!
Binding Events to Actions in the FormView View
UI Element Name Event Name Action
SendEMailButton onAction SendEMail
SaveButton onAction Save
ClearButton onAction Clear
Now repeat the above procedure in the EmailEditorView View [Page 24].
![Page 24: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/24.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 24
Developing the EmailEditorView ViewView Controller ContextIn the context of the EmailEditorView view, the attributes EMailText, EmailAddress, andGreeting are to be declared. The EMailAddress and EMailText attributes must be mapped tothe Component Controller’s context attribute with the same names. This can be done in theData Modeler. The other attribute Greeting is only used in this view as a local variable thuscan be defined here with no mapping. The Greetings attribute needs to be defined with theView Controller editor on the Context tab.
Controller Context of the EmailEditorView View
Context Element Type Property Value
EMailAddress Attribute type Mapped to ComponentController’s context attributealso named EMailAddress.
EMailText Attribute type string
Greeting Attribute type string
Layout of the ViewThe following table contains the hierarchy of the UI elements contained in theEmailEditorView view. Properties linked to the value attributes are marked by the symbol infront of the path specification of the value attribute.
Layout of the EmailEditorView View
![Page 25: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/25.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 25
Property Value
Container RootUIElementContainer of the type TransparentContainer
Properties of Transparent Container - layout GridLayout
Layout - colCount 1
Page Header PageHeader of type PageHeader in UI element RootUIElementContainer
Properties of PageHeader – title Error and Message Behavior
LayoutData – paddingBottom small
TextView GreetingTextView of the type TextView in the UI elementRootUIElementContainer
Properties of TextView – design header1
Properties of TextView – value EMailText
LayoutData – paddingBottom large
Label EMailTextLabel of the type Label in the UI element RootUIElementContainer
Properties of Label – text E-Mail Text
Properties of Label – labelFor EMailEditorText
Input field EMailEditorText of the type TextEdit in the UI-elementRootUIElementContainer
Properties of TextEdit – cols 60
Properties of TextEdit – rows 12
Properties of TextEdit – value EMailText
Pushbutton SendEMailButton of the type Button in the UI elementRootUIElementContainer
Link LinkToFormView of the type LinkToAction in the UI element RootUIElementContainer
Properties of LinkToAction – paddingTop medium
![Page 26: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/26.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 26
Actions and Binding EventsIn the view controller, define the two actions GoBack and SendEMail:
Controller Context of the EMailEditorView View
Name of theAction Text Validation Event Handler
GoBack Go back to sample form checked onActionGoBack
SendEMail Send E-Mail checked 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 Event Name Action
SendEMailButton onAction SendEMail
LinkToForm onAction GoBack
The next step is to define the navigation structure between the two views FormViewand EMailEditorView [Page 26].
Defining the navigation structureYou can easily create the navigation structure within the form example application, becauseyou must only define two navigation links between the two views FormView andEMailEditorView 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 WebDynpro project structure. This will open up the Window Editor:
![Page 27: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/27.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 27
Note: The you may initial see only one view in the window diagram, but this is most likelybecause the are overlapping each other. Simply drag the top view to a different location onthe diagram. If there is only one view showing up, this means the other view hasn’t beenembedded in the window yet.
To create the inbound and outbound plugs with navigation links, all you have to do is selectthe Create Link from the tool bar and then drag and drop from one view to the other. This willcreate the and outbound plug in the view you dragged from (named Out) and an inbound plugto the view you dragged to (named In). Below is an example of dragging a navigation linkfrom the FormView view to the EmailEditorView view.
Now create another link fromt the EmailEditorView view to the FormView view. Note: Youshould first move the inbound and outbound plugs that were already created. This is becausewhen you create the 2nd link the plugs it generate will be created on top of the plugs thatwere already created and you won’t be able to see both sets of plugs and links (one will bebeneath the other).
The declarative part of the view development is now almost completed. The declaration of themethods required for the input checks in the controller of the FormView view is describedunder Implementing the Controller of the FormView View [Page 28].
Implementing the View ControllerYou 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:
![Page 28: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/28.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 28
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 theexample application.
Implementing the Controller of the FormView View
UseThe implementation of the FormView view controller is divided up into the followingprocedures:
The input check for the input fields Name, Birthday, and E-Mail Address is started inthe 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 theycontain incorrect entries
The navigation to the EMailEditorView should only be possible when the user hasentered an e-mail address
Note that setting the state=required property for the input fieldNameInput on the user interface merely results in the field being speciallymarked. If the user leaves the input field blank, no error is displayed by the WebDynpro runtime environment, regardless of the defined value of the property(normal or required). The application developer is responsible forchecking any input made using application code (methodcheckMandatory()).
ProcedureImplement the Event Handlers to call appropriate methods on the Component Controller andfire outbound plugs where necessary.
Event Handling1. Implement the method onActionSave(…) method. Have it call the Component
Controller’s 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 theWeb Dynpro runtime environment if no error is reported in the checkMandatory() method.
![Page 29: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/29.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 29
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.IWDCustomEventwdEvent ){
//@@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 anevent handler is called before individual user entries are validated and stored in the controllercontext. 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 *///@@endpublic void onActionClear(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent ){
//@@begin onActionClear(ServerEvent)// Re-initialize this component controller's contextwdThis.wdGetSimpleErrorsCompController().initialize();
//@@end}...
The next step is the implementation of the EMailEditor view controller [Page 29].
Implementing the Controller of theEMailEditorView View
You must implement the following event handler methods:
Event handler of the In inbound plug: The value attributes are initialized using an e-mail address, which is available through context mapping of the ComponentController’s context.
Event handler of the SendEMail action: A success message is displayed after the e-mail message has been sent and the navigation link back to the FormView view hasbeen triggered.
Event handler of the GoBack action: The navigation link back to the FormView view istriggered without displaying a message.
![Page 30: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/30.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 30
ProcedureAfter triggering the Out outbound plug in the controller of the FormView view, the inboundplug event In is executed on the EMailEditor view. Its event handler is then executed. Herewe can access the context mapped email address and use it to build a String that contains agreeting....
1. Get the EmailAddress attribute and initialize the Greeting in the event handler of the Ininbound plug. The TextAccessor service is used to generate the string from themessage 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 ifneeded.
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 whenthe user selects the Send E-Mail button. This is why the method reportSuccess(Stringmessage) of the IWDMessageManager interface is called in the Component Controller’ssendEmail() method. After selecting the link Go back to sample form, the FormView view isdisplayed again.
Both action event handler methods onActionGoBack(…) and onActionSendEMail(…) willnavigate back to the FormView view. The only difference between the two methods being thatthe onActionSendEMail(…) should call the sendEmail() method on the ComponentController (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
}...
![Page 31: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/31.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 31
View Lifetime
When specifying the project structure, you select different values for the Lifespanproperty of the two view controllers. You select framework_controled for thecontroller of the FormView view and when_visible for the controller of theEMailEditor view. Both views are embedded in a single window so that only one singleview is visible at any given time. When the user calls the application, the FormViewview is displayed, because it is declared as the default view in the SimpleErrorswindow.
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 remainafter navigating to the EMailEditor view and back to the FormView view. Therefore, thepreviously entered form data still exists in the input fields. If the Lifespan property ofthe FormView view controller was when_visible, the controller would be newlycreated and initialized when the user navigates back from the EMailEditor view. In thiscase, the entered form data would not be available without context mapping to asuperordinate controller context.
After entering an e-mail message in the EMailEditor view for the first time, return to thisview for a second time using navigation. The TextEdit UI element will be emptybecause the corresponding view controller was newly created. Therefore, theEMailText value attribute also contains an empty string value.
An application example of the selection of the Lifespan propertyframework_controled is the embedding of views in multiple tabs of aTabstrip UI element. We recommend that not every selection of a different tabautomatically terminates the view controller lifecycle and begins the lifecycle ofanother view controller, as is the case when the Lifespan propertywhen_visible is assigned to the corresponding views.
![Page 32: A Simple Input Form in Webdynpro Java](https://reader030.vdocument.in/reader030/viewer/2022020217/547f52afb479599d508b4e86/html5/thumbnails/32.jpg)
SAP Developer Network 13.05.2008
Dialog Boxes in Web Dynpro Applications NW 7.1 32
Form viewcontroller
EMailEditor viewcontrollerUser
Start application
Navigate toEMailEditor view
Navigate backto Form view
Lifespanproperty
framework_controlled
when_visible
Destroyviewcontroller
Createviewcontroller
Createviewcontroller
Congratulations! You have finished this tutorial oncreating a simple form with error handling. Youshould now be able to deploy, run and test yourapplication.