25
Dynamic UI Generation in Web Dynpro SAP NetWeaver 04

Dynamic UI Generation in Web Dynpro

  • Upload
    others

  • View
    19

  • Download
    0

Embed Size (px)

Citation preview

Dynamic UI Generation in Web Dynpro

SAP NetWeaver 04

SAP Online Help

Dynamic Programming in Web Dynpro 2

Copyright © Copyright 2004 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, and Informix are trademarks or registered trademarks of IBM Corporation 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.

SAP Online Help

Dynamic Programming in Web Dynpro 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 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 Description

Example text 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 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 a programming language when they are surrounded by body text, for example, SELECT and INCLUDE.

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

Example text Exact user entry. These are words or characters that you enter in the system exactly as they appear in the documentation.

<Example text> Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system.

EXAMPLE TEXT Keys on the keyboard, for example, F2 or ENTER.

SAP Online Help

Dynamic Programming in Web Dynpro 4

Dynamic UI Generation in Web Dynpro .................................................................................... 5 Importing a Project Template................................................................................................. 6 Overview of Dynamic Programming in the Web Dynpro ....................................................... 7 Creating Dynamic User Interface Elements........................................................................... 8

Dynamically Building the Appropriate Context ................................................................. 10

Dynamically Creating the Form........................................................................................ 12

Dynamically Creating Pushbuttons with Appropriate Actions .......................................... 17

Action Handling.................................................................................................................... 20 Executing the Application TutWD_Dynamic_Init ................................................................. 24

SAP Online Help

Dynamic Programming in Web Dynpro 5

Dynamic UI Generation in Web Dynpro

The Task This tutorial will present to you the first steps for dynamic programming in Web Dynpro.

The aim of this tutorial is to dynamically create appropriate user interface elements from a given description and to integrate them into an existing incomplete Web Dynpro application. The description of the user interface elements is stored in the Java class SomeBackEnd.java.

In the tutorial, different user input fields such as text and date input fields, checkboxes, selection lists, and radio buttons are taken into consideration.

Input fields will have to be mapped to context attributes. Since the number and the respective type of context attributes is not known during dynamic creation of user interface elements, these are created dynamically during runtime. The type information required for this (including metadata such as field labels, quick infos, and value sets) is usually provided by the backend through a dictionary (in this case, by the class SomeBackEnd.java).

Furthermore, the class SomeBackEnd.java contains information on pushbuttons that are to be dynamically created. Dynamically created actions are bound to these pushbuttons.

Objectives By the end of this tutorial, you will be able to:

! Dynamically create context attributes and context nodes

! Dynamically create user interface elements and map them to context elements

! Dynamically create user interface actions and bind onAction-events of user interface elements to these actions.

Prerequisites Systems, Installed Applications, and Authorizations

• SAP NetWeaver Developer Studio is installed on your PC.

• You have access to the SAP J2EE Engine.

SAP Online Help

Dynamic Programming in Web Dynpro 6

Knowledge

• Basic knowledge of the Java programming language

• Knowledge of programming of Web Dynpro applications

Next step: Importing a Project Template [page 6]

Importing a Project Template On the SAP Developer Network (SDN) at http://sdn.sap.com, the following Web Dynpro projects are available for this tutorial:

• The project template TutWD_Dynamic_Init (the starting point for this tutorial)

• The completed Web Dynpro project TutWD_Dynamic (corresponds to the project TutWD_Dynamic_Init after completion of the tutorial)

The projects are available for download in corresponding zip files under the category Home → Developer Areas → Web Application Server → Web Dynpro.

Prerequisites • You have a user ID and password to access the SAP Developer Network

(http://sdn.sap.com).

• You have installed the SAP NetWeaver Developer Studio.

Procedure Importing the Project Template to the SAP NetWeaver Developer Studio ...

1. Call the SAP NetWeaver Developer Network by using the URL http://sdn.sap.com and log on with the corresponding user ID and password. If you do not have a user ID, you must register before you can proceed.

2. Download the zip file TutWD_Dynamic_Init.zip containing the project template TutWD_Dynamic_Init, and save the zip file to any directory on your local hard disk or directly in the work area of the SAP NetWeaver Developer Studio.

3. Extract the content of the zip file “TutWD_Dynamic_Init.zip” in the work area of the SAP NetWeaver Developer Studio or in any directory on your local hard disk.

4. Open the SAP NetWeaver Developer Studio.

a. Import the Web Dynpro project TutWD_Dynamic_Init: In the menu, choose File Import.

b. In the next window, choose Existing Project into Workspace and click Next to confirm.

c. Choose Browse, open the folder in which you saved the project TutWD_Dynamic_Init, and select the project.

d. Choose Finish to confirm.

The Web Dynpro project TutWD_Dynamic_Init appears in the Web Dynpro Explorer for further processing and completion of the tutorial.

SAP Online Help

Dynamic Programming in Web Dynpro 7

Tabular Project Structure Once you have imported the project template to the SAP NetWeaver Developer Studio, you will see the following structure in the Web Dynpro Explorer.

Web Dynpro Project Structure

Web Dynpro project: TutWD_Dynamic_Init

Web Dynpro application: DynamicApp

Web Dynpro component: DynamicComp

View: DynamicView

In the Dynamic View, there are already declared UI elements into which the UI elements to be created dynamically are entered.

Windows: Dynamic

Dictionaries

Simple Type: Country

In the Simple Type Country, certain countries that will be displayed later in the selection list are stored.

Simple Type: Sex

The Simple Type Sex is used for selecting male / female.

src packages com sap tut wd Dynamic

SomeBackEnd.java

In SomeBackEndjava, there is information on user interface elements to be created dynamically.

Next step: Overview of Dynamic Programming in Web Dynpro [page 7]

Overview of Dynamic Programming in the Web Dynpro

The Web Dynpro programming model enables you to create contexts, view layouts, and actions – not only at design time, but also dynamically at runtime (dynamic programming).

However, you should only avail of dynamic creation of user interface elements, context attributes, and actions if these are not known at design time since the error possibilities and ability to maintain the program code to be implemented are much higher.

SAP Online Help

Dynamic Programming in Web Dynpro 8

If you have user interface elements that are already known at design time and are to be displayed only when a user triggers an action, then these should not be created dynamically. There is also a considerably better variant: controlling the Visibility property of the user interface elements by mapping them to a context attribute of the type Visibility. In the tutorial, this variant is presented in the step Action Handling [page 20].

Before you begin with the dynamic programming of user interface elements, contexts, and actions, you should first create a declarative (static) example. In this way, you become aware of error sources and you get a better idea of the required UI element types and their properties.

Process Flow • Create Dynamic User Interface Elements

Dynamically Building the Appropriate Context

Dynamically Creating the Form

Dynamically embed pushbuttons with corresponding actions in the view layout

• Action Handling

Next step: Creating Dynamic User Interface Elements [page 8]

Creating Dynamic User Interface Elements

Description of the SomeBackEnd.java Class To demonstrate the creation of arbitrary user interface elements, the SomeBackEnd.java class is provided with the project template. There are two inner classes contained in this: FieldDescriptor and OperationDescriptor.

FieldDescriptor

getUIType() getName()getType() getLabel()getTooltip() getInit()

FieldDescriptor

getUIType() getName()getType() getLabel()getTooltip() getInit()

OperationDescriptor

getName()getDisplayText() getTooltip()

OperationDescriptor

getName()getDisplayText() getTooltip()

With the help of the FieldDescriptor class, the corresponding metadata – such as labels and context properties – is defined for the required form fields.

• uiType: Type of the form input field

• name: Name of the corresponding context attribute

• type: Type of the context attribute that is mapped to the input field (uiType)

• label: Text of label belonging to the input field

SAP Online Help

Dynamic Programming in Web Dynpro 9

• tooltip: Quick info of the input field

• init: Value that is to be displayed first in the form field

In the SomeBackEnd.java class, there are already predefined form fields that are created dynamically during the tutorial. private Object[] fields = {

new FieldDescriptor("InputField","firstName", "com.sap.dictionary.string", "First Name", "Enter first name here",""),

new FieldDescriptor("InputField","lastName", "com.sap.dictionary.string","Last Name", "Enter last name here",""), new FieldDescriptor("InputField","birthday", "com.sap.dictionary.date","Date of Birth", "Enter date here", null), new FieldDescriptor("DropDownByKey","country","com.sap.workshop .dynamicprogramming.simpletypes.Country", "Country","Choose your country here",""), new FieldDescriptor("RadioButtonGroupByKey","sex","com.sap. workshop.dynamicprogramming.simpletypes .Sex","Sex","Choose your sex here",""), new FieldDescriptor("CheckBox","isManager", "com.sap.dictionary.boolean", "Is a Manager", "Checked if person is a manager", new Boolean(false))

};

In the fields array, there are certain FieldDescriptors that specify a Simple type as the type for the context attribute. These simple types are already contained in the Web Dynpro project – see also: TutWD_Dynamic_Init Dictionaries Local Dictionary Data Types Simple Types.

Using the OperationDescriptor class, the information required for actions and pushbuttons is provided.

• name: ID of the pushbutton

• displayText: Label for pushbutton (mapped to an action)

• tooltip: Quick info of the pushbutton

In the SomeBackEnd.java class, there are already predefined pushbuttons that are created dynamically during the tutorial. private Object[] operations = { new OperationDescriptor ("delete","Delete", "Delete your input."), new OperationDescriptor ("save", "Save",

SAP Online Help

Dynamic Programming in Web Dynpro 10

"Save current record."), };

Next step: Dynamically Building the Appropriate Context [page 10]

Dynamically Building the Appropriate Context

The input fields defined in the class SomeBackEnd must be mapped to a context attribute for each user input.

For dynamic creation of the context belonging to the input fields, the standard method wdDoInit() of the (View) Controller is suitable since this method is executed as soon as the controller is instantiated. Another advantage of the method wdDoInit() is that it is executed only once during the life cycle of the view.

The metadata information of the controller context is represented at runtime in the objects of the types IWDNodeInfo and IWDAttributeInfo. Using the program code wdContext.getNodeInfo(), you can access – for example – the metadata information of the root node available in each context.

So that value attributes and value nodes can be dynamically created in the controller context, the interface IWDNodeInfo provides the following methods:

• addAttribute( java.lang.String name, java.lang.String dataType)

• addAttribute( java.lang.String name, • com.sap.dictionary.runtime.IDataType dataType)

• addChild( java.lang.String name, java.lang.Class elementClass, boolean singleton, boolean mandatory, boolean multiple, boolean mandatorySelection, boolean multipleSelection, boolean initializeLeadSelection, java.lang.String dataType, IWDNodeCollectionSupplier supplier, IWDNodeCollectionDisposer disposer)

After dynamic enhancement of the context structure, the added context elements can be accessed using the generic methods IWDNode.getChildNode(String,int) IWDNodeElement.getAttributeValue(String) und IWDNodeElement.setAttributeValue(String,Object).

Procedure ...

1. To dynamically add a new value node at the uppermost level in the context of the DynamicView view, enter the following program code in the method wdDoInit():

SAP Online Help

Dynamic Programming in Web Dynpro 11

wdDoInit()

public void wdDoInit() { //@@begin wdDoInit() //Dynamically create a context node IWDNodeInfo node = wdContext.getNodeInfo().addChild( "DynamicNode", null, true, true, false, false, false, true, null, null, null); //@@end }

You could declare this context node at design time.

2. To dynamically add the value attributes belonging to the form input fields to the DynamicNode node just created, add the following program code to the method wdDoInit():

wdDoInit() public void wdDoInit() { //@@begin wdDoInit() //Dynamically create a context node IWDNodeInfo node = wdContext.getNodeInfo().addChild( "DynamicNode", null, true, true, false, false, false, true, null, null, null); // “Create“ backend connection to SomeBackEnd.java SomeBackEnd theBackend = new SomeBackEnd(); // loop through all fields of the Object[] fields containing the // FieldDescriptors for (int index=0; index < theBackend.getNumberFields(); index++) { // ... and simply create the required context attribute SomeBackEnd.FieldDescriptor fld = theBackend.getField(index); node.addAttribute(fld.getName(),fld.getType()); } //@@end

SAP Online Help

Dynamic Programming in Web Dynpro 12

}

The class SomeBackEnd.java is in the project template under TutWD_Dynamic src packages com sap tut wd Dynamic and contains the example data for the form input fields.

Result You have dynamically set up the context for the form.

Next step: Dynamically Creating the Form [page 12]

Dynamically Creating the Form

In every Web Dynpro view controller, the method wdDoModifyView is implemented; it is called by the Web Dynpro runtime environment for modification of the view layout. For all visible views, this takes place at a time immediately before the closing response rendering.

wdDoModifyView(…) contains the following parameters:

• firstTime of the type boolean: This is true only if wdDoModifyView wis called for the first time during the life cycle of the corresponding view.

• view: Reference to the layout controller of the view.

• wdThis: Reference to the IPrivate interface of the view controller . wdThis allows access to the controller context; it also allows triggering outbound plugs and events and access to action objects as well as controllers used.

• wdContext: Reference to the root context node of the view controller (for the current context).

In order to adhere to the MVC paradigms, this method should be used solely for dynamic creation of user interface elements. This means that you are not allowed - in the method wdDoModifyView - to call outbound plugs, issue messages, or write to the context. Furthermore, no access to user interface elements in the event handler code is allowed – that is, no references to user interface elements that were used in the controller code can be stored here.

Prerequisites In the layout of the DynamicView, user interface elements that were already statically declared exist. In the following steps, the form input fields for the user interface element InputGroup are added dynamically.

SAP Online Help

Dynamic Programming in Web Dynpro 13

The example data for the form fields are stored in the class SomeBackEnd.java. They contain information on how to dynamically build the following form:

Procedure Since the user interface elements to be created dynamicaly are to be entered into the statically declared group InputGroup, you will require a pointer to these. In addition, an instance of the class SomeBackEnd will be required in order to access the information of the individual user interface elements. This information is contained in the array FieldDescriptor and processed in a for loop. In addition to the respective user interface element, a corresponding text field is created. The text field and the user interface element are created at the end using addChild() of the InputGroup. ...

1. In the wdDoModifyView method, add the following (yet incomplete) source code:

wdDoModifyView() public static void wdDoModifyView(IPrivateDynamicView wdThis, IPrivateDynamicView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime) { //@@begin wdDoModifyView //Dynamic UI creation // This flag is set to TRUE when this method is called the // first time. Since Web Dynpro runs stateful on the server // it is necessary to create the UI elements only once per // view instance. if (firstTime) { // get container for inputfields and labels IWDGroup theGroup = (IWDGroup)view.getElement("InputGroup"); // establish backend connectvity SomeBackEnd theBackend = new SomeBackEnd(); // loop through all fields for(int index=0; index<theBackend.getNumberFields(); index++ )

SAP Online Help

Dynamic Programming in Web Dynpro 14

{ // get field meta data SomeBackEnd.FieldDescriptor fld = theBackend.getField(index); IWDUIElement theUIElement = null; IWDLabel theLabel = null; //Create UI Elements: //To be continued // add UI elements to container theGroup.addChild(theLabel); theGroup.addChild(theUIElement); } } //@@end }

The user interface elements are created in the if(firstTime) block because they only need to be created once.

Error source: The group that contains the input fields must have the ID group.

In the following steps, the user interface elements are created on the basis of the information in FieldDescriptor. This includes input fields, radio buttons, a checkbox, and a selection list.

Creating the Input Field 2. To create an input field, add the following program code under the comment “//

Create UI Elements”.

wdDoModifyView() // loop through all fields for(int index=0; index<theBackend.getNumberFields(); index++) { // get field meta data SomeBackEndTest.FieldDescriptor fld = theBackend.getField(index); WDUIElement theUIElement = null; IWDLabel theLabel = null; //Create UI Elements: // create input field if(fld.getUIType().equals("InputField")) { IWDInputField theInput = (IWDInputField) view .createElement(IWDInputField.class,"inp"+index); // bind value to attribute created in wdDoInit theInput.bindValue("DynamicNode." +

SAP Online Help

Dynamic Programming in Web Dynpro 15

fld.getName()); theInput.setLength(20); theUIElement = theInput; }

An input field with the ID: “inp” + (index of the “for“ loop) and length “20” is created. This field is mapped against the corresponding context attribute that is stored in the DynamicNode.

Error source: The dynamically created source node must have the name DynamicNode and the context attribute must have the name fld.getName().

Creating the Checkbox 3. To create the checkbox, enter the following program code in the wdDoModifyView.

wdDoModifyView() if(fld.getUIType().equals("InputField")) { ... } // create checkbox else if (fld.getUIType().equals("CheckBox")) { IWDCheckBox theCheckBox = (IWDCheckBox) view .createElement(IWDCheckBox.class,"inp"+index); // bind value to attribute created in wdDoInit theCheckBox.bindChecked("DynamicNode." + fld.getName()); theUIElement = theCheckBox; }

A checkbox with the ID: “inp” + (index of the “for“ loop) is created. This field is mapped against the corresponding context attribute that is stored in the DynamicNode.

Creating the Selection List 4. To create the selection list, enter the following program code:

wdDoModifyView() if(fld.getUIType().equals("InputField")) { ... } else if (fld.getUIType().equals("CheckBox")) { ... } else if (fld.getUIType().equals("DropDownByKey")) { IWDDropDownByKey theDropDown = (IWDDropDownByKey) view.createElement(IWDDropDownByKey.class, "inp"+index); // bind value to attribute created in wdDoInit theDropDown.bindSelectedKey("DynamicNode."

SAP Online Help

Dynamic Programming in Web Dynpro 16

+ fld.getName()); theDropDown.setWidth("113"); theUIElement = theDropDown; }

A selection list with the ID: “inp” + (index of the “for“ loop) and length 113px is created. This field is mapped against the corresponding context attribute that is stored in the DynamicNode. The context attributes for a dropdown list required as type a Simple type; this can be found in the package com.sap.workshop.dynamicprogramming.simpletypes.

Creating the Radio Buttons 5. To create a radio button, enter the following program code in wdDoModifyView.

wdDoModifyView() if(fld.getUIType().equals("InputField")) { ... } else if (fld.getUIType().equals("CheckBox")) { ... } else if (fld.getUIType().equals("DropDownByKey")) { ... } else if (fld.getUIType() .equals("RadioButtonGroupByKey")) { IWDRadioButtonGroupByKey theRadioGroup = (IWDRadioButtonGroupByKey) view.createElement( IWDRadioButtonGroupByKey.class, "inp"+index); // bind value to attribute created in wdDoInit theRadioGroup.bindSelectedKey("DynamicNode."+ fld.getName()); //theRadioGroup.setColCount(2); theUIElement = theRadioGroup; }

A group with the ID: “inp” + (index of the “for“ loop) is created. This group is mapped against the corresponding context attribute that is stored in the DynamicNode.

Creating the Label and the Quick Info All user interface elements have in common the fact that they contain appropriate labels and quick info texts.

6. To dynamically created the labels and quick info, enter the following program code:

wdDoModifyView() if(fld.getUIType().equals("InputField")) { ... } else if (fld.getUIType().equals("CheckBox"))

SAP Online Help

Dynamic Programming in Web Dynpro 17

{ ... } else if (fld.getUIType().equals("DropDownByKey")) { ... } else if (fld.getUIType().equals("RadioButtonGroupByKey")) { ... } // set a tooltip theUIElement.setTooltip(fld.getTooltip()); // create label theLabel = (IWDLabel)view .createElement(IWDLabel.class,"lbl"+index); IWDGridData layout = (IWDGridData) theLabel .createLayoutData(IWDGridData.class); layout.setVAlign(WDCellVAlign.TOP); theLabel.setText(fld.getLabel()); // bind label to input field for accessibility and // usability reasons theLabel.setLabelFor(theUIElement.getId()); // add UI elements to container theGroup.addChild(theLabel); theGroup.addChild(theUIElement); } } //@@end }

A label with the ID: “ibl” + (index of the “for“ loop) is created. To ensure that the vertical alignment of the label is top, a GridLayout with the alignment Top is assigned to the label. To ensure there is freedom of barriers and also to ensure maintenance ability, the corresponding user interface element is assigned to the label using setLabelFor().

Next step: Dynamically Creating Pushbuttons with Corresponding Actions [page 17]

Dynamically Creating Pushbuttons with Appropriate Actions

If the maximum number of pushbuttons is not known at design time, you can create these at runtime together with the corresponding action. Since it is not possible to dynamically create event handlers in the view controller, dynamically created actions must use an event handler declared already at design time. Mapping an event parameter from the event source (the user interface element) to the signature of the event handler in the view controller is termed as Parameter Mapping in the Web Dynpro.

SAP Online Help

Dynamic Programming in Web Dynpro 18

Procedure 1. To dynamically add pushbuttons from the Container-UI-Element ActionContainer, enter

the following program code into the method wdDoModifyView underneath the first for loop.

wdDoModifyView() ... // add UI elements to container theGroup.addChild(theLabel); theGroup.addChild(theUIElement); } // The buttons are displayed within the container the // "actionContainer" IWDTransparentContainer theActionContainer = (IWDTransparentContainer)view.getElement( "ActionContainer"); // loop through all actions for (int index = 0; index < theBackend.getNumberActions(); index++) { // get action meta data SomeBackEnd.OperationDescriptor op = theBackend.getAction(index); // Create button and set some attributes IWDButton theButton = (IWDButton)view.createElement( IWDButton.class, "btn"+index); theButton.setTooltip(op.getTooltip()); theButton.setText(op.getDisplayText()); // To be continued... theActionContainer.addChild(theButton); } } //@@end }

The pushbuttons should be entered in the ActionContainer already statically declared.

Error source: The container for actions must contain the ActionContainer ID. (see also the Properties view in the layout editor).

You will find information on the pushbuttons in the theBackend object. Through getNumberActions(), you get the number of pushbuttons to be created, and through getAction() you get information on each action. In this way, an ID, a quick info, and a text can be assigned to each pushbutton.

SAP Online Help

Dynamic Programming in Web Dynpro 19

So far, all the required pushbuttons have been created. However, these do not yet contain any actions or event handlers. Event handler cannot be dynamically created in the Web Dynpro, but only statically defined. For this reason, statically define the following action handler for the various pushbuttons:

2. Switch to the Actions tab page.

3. Choose the New pushbutton and enter GenericAction as the name. Choose Next to confirm your entries.

4. Assign a parameter to the action by choosing New. Enter Command as the name and choose string as type. Confirm with Finish.

5. Switch to the Implementation tab page.

6. In order to create a new action and to map this to a pushbutton, enter the following program code in wdDoModifyView():

wdDoModifyView() theButton.setText(op.getDisplayText()); // Create an action. This becomes important in case // the enabling state of buttons using the same event // handler should be different. The enabling state of // a button is controlled by action.isEnabled. Thus // it is possible to have several actions pointing to // the same event handler but using different enabling // states. IWDAction theAction = wdThis.wdCreateAction( IPrivateDynamicView.WDActionEventHandler .GENERIC_ACTION, ""); theButton.setOnAction(theAction); // The event handler has to know which button was // pressed since we only have a single generic // event handler. By means of parameter mapping we can // supply an individual parameter for each button // to the event handler. theButton.mappingOfOnAction().addParameter( "Command",op.getName()); theActionContainer.addChild(theButton); } } //@@end }

Using wdThis.wdCreateAction( eventhandler, text), you can create a new action. An event handler and a text must be passed to this action. Since the event handler cannot be created dynamically, the event handler declared statically onActionGenericAction beforehand is assigned.

Using setOnAction(…), the dynamically created action is assigned to the onAction event of the pushbutton user interface element.

To differentiate between the pushbuttons, the Command parameter is added to the onAction event of the pushbutton UI element:

SAP Online Help

Dynamic Programming in Web Dynpro 20

theButton.mappingOfOnAction().addParameter("Command", op.getName()). The value of the additional event parameter Command is passed from the Web Dynpro runtime environment to the parameter with the same name in the action event handler onActionGenericAction.

Next step: Action Handling [page 20]

Action Handling

In SomeBackEnd.java, there are two pushbuttons – Save and Delete. For reasons of simplicity, the functions are known at design time and can thus be implemented in the event handler onActionGenericAction().

If the user confirms an action by clicking Save, a log that displays the data he entered is to appear beside the input fields.

If the user clicks Delete, the user inputs are deleted and the log will disappear.

The user interface elements for the log were already declared statically. Only their visibility changed.

SAP Online Help

Dynamic Programming in Web Dynpro 21

Procedure So that the contents of the log, are displayed, a context attribute for storing the text is declared.

To change the visibility properties of the log, an additional context attribute of the Visibility type is required.

Enhance Context ...

1. Switch to the Context tab page.

2. Create the following context attributes:

Context Element

Type Property Value

Result Value attribute

type string

Visible Value attribute

type com.sap.ide.webdynpro. uielementdefinitions.Visibility

Context Binding

3. Switch to the Layout tab page.

4. Select the interface element ProtocolGroup (RootUIElementContainer ProtocolGroup)

5. In the Properties view, bind the property visible to the context attribute Visible.

6. Select the interface element result (RootUIElementContainer ProtocolGroup)

result).

7. In the Properties view, bind the property visible to the context attribute Visible.

Enhance wdDoInit()

8. At the beginning, the ProtocolGroup should not be made visible in the application. For this reason, set the visibility property in the wdDoInit() method to false.

9. Switch to the Implementation tab page and add the following program code in wdDoInit():

wdDoInit()

...

SAP Online Help

Dynamic Programming in Web Dynpro 22

wdContext.currentContextElement().setVisible(WDVisibility.NONE); //@@end

}

Implement onGenericAction()

The onAction event for the pushbuttons Save and Delete is handled in the view controller of the onActionGenericAction() method. Due to the parameter mapping performed in the step Dynamically Creating Pushbuttons with Corresponding Actions [page 17], the value of the Command parameter depends on which pushbutton was operated. If Save was chosen, the Command is “save”; if Delete was chosen, the Command is “delete".

Both during reading and deleting user inputs, dynamically created context attributes and context nodes must be accessed. For this purpose, the IDs stored in the object of the type SomeBackEnd are required.

10. Add the following program code to the event handler onActionGenericAction():

onActionGenericAction() public void onActionGenericAction( com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent, java.lang.String Command ) { //@@begin onActionGenericAction(ServerEvent) SomeBackEnd theBackend = new SomeBackEnd(); SomeBackEnd.FieldDescriptor fld; IWDNode node = wdContext.currentContextElement().node() .getChildNode("DynamicNode", 0); IWDNodeElement nodeElement = node.getCurrentElement(); if(Command.equals("save")){ //To be continued } else if(Command.equals("delete")){ //To be continued } //@@end }

The basic frame for the event handler onActionGenericAction() is defined.

Error sources:

i. The context node must have been named exactly (DynamicNode) during dynamic creation.

ii. During parameter mapping, the value save or delete must have been assigned to the parameter Command.

11. Implement the functions for Save by adding the following program code in the block if(Command.equals(„save“)):

onActionGenericAction() ... if(Command.equals("save")){

SAP Online Help

Dynamic Programming in Web Dynpro 23

String result = "Your data was successfully saved:" + "\n\r"; for (int index = 0; index < theBackend.getNumberFields(); index++) { fld = theBackend.getField(index); Object value = nodeElement .getAttributeValue(fld.getName()); if (value == null) value = "<null>" ; result = result + fld.getName() + " : " + value.toString() + "\n"; } wdContext.currentContextElement() .setVisible(WDVisibility.VISIBLE); wdContext.currentContextElement().setResult(result); } else if(Command.equals("delete")){ ...

In the result string, the log for the user input is stored. This value is stored in the last step in the Result context attribute.

So that the user input is read, the dynamically created context attributes are used for iteration; these were determined by the number of user interface elements. Through the call of the generic method getAttributeValue(String name) of the interface IWDNodeElement, the value of the required context attribute can be accessed.

Error source: the context attribute must have been named exactly during dynamic creation.

So that the user interface element named ProtocolGroup is displayed, the context attribute Visible is set to visible (WDVisibility.VISIBLE).

12. Implement the functions for Delete by adding the following program code in the block else if(Command.equals("delete") to the following program code:

onActionGenericAction() ... else if(Command.equals("delete")){ for (int index = 0; index < theBackend.getNumberFields(); index++) { fld = theBackend.getField(index); nodeElement.setAttributeValue(fld.getName(), fld.getInit()); } wdContext.currentContextElement() .setVisible(WDVisibility.NONE); } //@@end }

SAP Online Help

Dynamic Programming in Web Dynpro 24

To delete the user inputs and set the input fields to initial value. The dynamically created context attributes are again used for iteration and the value is reset.

Error source: the context attribute must have been named [fld.getName()] during dynamic creation.

The log is again set to invisible by assigning the value WDVisibility.NONE to the context attribute Visible.

Next step: Executing the Application TutWD_Dynamic_Init [page 24]

Executing the Application TutWD_Dynamic_Init

Now that you have reached this stage, you can start the fully developed example application in the Web Browser as described below.

Prerequisites You have made sure that the SAP J2EE Engine has been launched.

Procedure ...

Save all Metadata

1. Save the current status of the metadata for your project.

Rebuild Project 2. In the Web Dynpro Explorer, open the context menu for the project node

TutWD_Dynamic_Init and choose Rebuild Project.

Deploy new archive and run

3. In the Web Dynpro Explorer, open the context menu for the application object DynamicApp and choose Deploy new archive and run.

Result After the Deploy and run, the Web Dynpro application opens up automatically in the Web Browser.

SAP Online Help

Dynamic Programming in Web Dynpro 25

Test your Web Dynpro application by filling out the form and clicking the Save pushbutton.

Click the Delete pushbutton and the inputs will be deleted.