Notice of Proprietary Rights The software and documentation are copyrighted by and proprietary to Isomorphic Software, Inc. (―Isomorphic‖). Isomorphic retains title and ownership of all copies of the software and documentation. Except as expressly licensed by Isomorphic in writing, you may not use, copy, disseminate, distribute, modify, reverse engineer, unobfuscate, sell, lease, sublicense, rent, give, lend, or in any way transfer, by any means or in any medium, the software or this documentation. 1. These documents may be used for informational purposes only. 2. Any copy of this document or portion thereof must include the copyright notice. 3. Commercial reproduction of any kind is prohibited without the express written consent of Isomorphic. 4. No part of this publication may be stored in a database or retrieval system without prior written consent of Isomorphic. Trademarks and Service Marks Isomorphic Software, Smart GWT, SmartClient and all Isomorphic-based trademarks and logos that appear herein are trademarks or registered trademarks of Isomorphic Software, Inc. All other product or company names that appear herein may be claimed as trademarks or registered trademarks of their respective owners. Disclaimer of Warranties THE INFORMATION CONTAINED HEREIN IS PROVIDED ―AS IS‖ AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT AND ONLY TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
Contents Contents ................................................................................... i How to use this guide .............................................................. iii Why Smart GWT? ..................................................................... v More than Just Widgets – A Complete Architecture ......................v Eliminates Cross-Browser Testing and Debugging.........................v Complete Solution ......................................................................... vi Open, Flexible Architecture .......................................................... vi 1. Overview.............................................................................. 1 Architecture ..................................................................................... 1 Capabilities and Editions of Smart GWT ....................................... 2 2. Installation ......................................................................... 3 Starting a New Project .................................................................... 3 Adding Smart GWT to an Existing Project..................................... 3 Server Configuration (optional) ..................................................... 4 3. Exploring .............................................................................5 Smart GWT Showcase .................................................................... 5 Smart GWT Java Doc ..................................................................... 6 Smart GWT Developer Console...................................................... 6 4. Visual Components ............................................................ 11 Component Documentation & Examples ...................................... 11 Drawing, Hiding, and Showing Components ................................ 12 Size and Overflow .......................................................................... 12 Handling Events ............................................................................ 13 5. Data Binding ...................................................................... 15 Databound Components ............................................................... 15 Fields ............................................................................................. 16 DataSources .................................................................................. 20 Customized Data Binding............................................................. 23 DataSource Operations ................................................................ 24 DataBound Component Operations ............................................. 26 Data Binding Summary ................................................................ 27 6. Layout .............................................................................. 28 Component Layout ....................................................................... 28 Container Components ................................................................ 30
Version 2.3
i
Contents
Smart GWT Quick Start
Form Layout .................................................................................. 31 7. Data Integration ................................................................33 DataSource Requests .................................................................... 33 Smart GWT Server Framework .................................................... 34 DSRequests and DSResponses ..................................................... 35 Request and Response Transformation ....................................... 35 Criteria, Paging, Sorting and Caching .......................................... 37 Authentication and Authorization ............................................... 38 Relogin.......................................................................................... 39 8. Smart GWT Server Framework ........................................ 40 DataSource Generation ................................................................ 40 Server Request Flow ..................................................................... 43 Direct Method Invocation ............................................................ 45 DMI Parameters ........................................................................... 46 Adding DMI Business Logic ......................................................... 46 Returning Data ............................................................................. 49 Queuing & Transactions ............................................................... 50 Queuing, RESTHandler, and SOAs .............................................. 52 Operation Bindings ...................................................................... 52 Declarative Security...................................................................... 54 Declarative Security Setup ........................................................... 56 Dynamic Expressions (Velocity) ...................................................57 SQL Templating............................................................................ 60 SQL Templating — Adding Fields ................................................ 63 Why focus on .ds.xml files? ...................................................... 65 Custom DataSources .................................................................... 66 9. Extending Smart GWT ...................................................... 68 New Components ......................................................................... 68 New Form Controls ...................................................................... 69 Switching Theme .......................................................................... 70 Customizing Themes ..................................................................... 71 10. Tips.................................................................................... 73 Beginner Tips ............................................................................... 73 Architecture Tips .......................................................................... 73 HTML and CSS Tips ..................................................................... 74 11. Evaluating Smart GWT ...................................................... 76 Which Edition to Evaluate ........................................................... 76 Evaluating Performance ................................................................ 77 Evaluating Interactive Performance ............................................ 79 Evaluating Editions and Pricing................................................... 80 A note on supporting Open Source ...............................................81 Contacts ................................................................................. 82
ii
Version 2.3
How to use this guide The Smart GWT Quick Start Guide is designed to introduce you to the Smart GWT™ web presentation layer. Our goals are:
To have you working with Smart GWT components and services in a matter of minutes.
To provide a conceptual framework, with pointers to more detail, so you can explore Smart GWT in your areas of interest.
This guide is structured as a series of brief chapters, each presenting a set of concepts and hands-on information that you will need to build Smart GWT-enabled web applications. These chapters are intended to be read in sequence—earlier chapters provide the foundation concepts and configuration for later chapters. This is an interactive manual. You will receive the most benefit from this guide if you are working in parallel with the Smart GWT SDK—following the documented steps, creating and modifying the code examples, and finding your own paths to explore. You may want to print this manual for easier reference, especially if you are working on a single-display system. We assume that you are somewhat acquainted with basic concepts of web applications (browsers, pages, tags), object-oriented programming (classes, instances, inheritance), and user interface development (components, layout, events). However, you do not need deep expertise in any specific technology, language, or system. If you know how to navigate a file system, create and edit text files, and open URLs in a web browser, you can start building rich web applications with Smart GWT today. If you can’t wait to get started, you can skip directly to Installation (Chapter 2) to create a Smart GWT project and begin Exploring (Chapter 3) and Visual Components (Chapter 4). But if you can spare a few minutes, we recommend reading the introductory chapters first, for the bigger picture of Smart GWT goals and architecture. Thank you for choosing Smart GWT, and welcome.
Version 2.3
iii
Why Smart GWT? Smart GWT helps you to build and maintain more usable, portable, efficient web applications faster, propelled by an open, extensible stack of industry-tested components and services. In this chapter we explore the unique traits of the Smart GWT platform that set it apart from other technologies with similar purpose.
More than Just Widgets – A Complete Architecture Smart GWT provides an end-to-end application architecture, from UI components to server-side transaction handling. The examples included with Smart GWT demonstrate the simplicity that can only be achieved by a framework that addresses both server- and client-side architectural concerns to deliver globally optimal solutions. Smart GWT‘s UI components are carefully designed to maximize responsiveness and minimize server load, and Smart GWT‘s server components are designed around the requirements of high-productivity user interfaces. Even if you adopt only part of the Smart GWT solution, you benefit from an architecture that takes into account the entire problem you need to solve, not just a part of it. Every integration point in the Smart GWT platform has been designed with a clear understanding of the requirements you need to fulfill, and, the solutions built into Smart GWT provide a ―blueprint‖ for one way of meeting those requirements.
Eliminates Cross-Browser Testing and Debugging Smart GWT provides a clean, clear, object-oriented approach to UI development that shields you from browser bugs and quirks.
Version 2.3
v
Why Smart GWT?
Smart GWT Quick Start
Even if you need to create a totally unique look and feel, Smart GWT‘s simplified skinning and branding requires only basic knowledge of page styling, and you never have to deal with browser layout inconsistencies. In contrast, lower-level frameworks that provide a thin wrapper over browser APIs can‘t protect you from the worst and most destructive of browser issues, such as timing-dependent bugs and memory leaks. Smart GWT‘s powerful, component-oriented APIs give Smart GWT the flexibility to use whatever approach works best in each browser, so you don‘t have to worry about it. This allows Smart GWT to make a simple guarantee: if there is a crossbrowser issue, it's our problem, not yours.
Complete Solution Smart GWT offers a complete presentation layer for enterprise applications: everything you need for the creation of full-featured, robust, high-productivity business applications. The alternative—throwing together partial solutions from multiple sources—creates a mish-mash of different programming paradigms, inconsistent look and feel, and bizarre interoperability issues that no single vendor can solve for you. Whether you are a software vendor or enterprise IT organization, it never makes sense to build and maintain a UI framework of your own, much less to own ―glue code‖ tying several frameworks together. A single, comprehensive presentation framework gives you a competitive advantage by enabling you to focus on your area of expertise.
Open, Flexible Architecture Because Smart GWT is built entirely with standard web technologies, it integrates perfectly with your existing web content, applications, portals, and portlets. You can build a state-of-the-art application from scratch, or you can upgrade existing web applications and portals at your own pace, by weaving selected Smart GWT components and services into your HTML pages. By giving you both options, Smart GWT allows you to address a broader range of projects with a single set of skills. You can even reuse existing content and portlets by embedding them in Smart GWT user interface components. Smart GWT allows a smooth evolution of your existing web applications—you aren‘t forced to start over. Next, Smart GWT is fully open to integration with other technologies. On the client, you can seamlessly integrate Java applets, Flash/Flex modules, vi
Version 2.3
Smart GWT Quick Start
Why Smart GWT?
ActiveX controls and other client technologies for 3D visualization, desktop integration, and other specialized functionality. On the server, Smart GWT provides flexible, generic interfaces to integrate with any data or service tier that you can access through Java code. Finally, Smart GWT is completely extensible, all the way down to the web standards on which the system is constructed. If you can‘t do something ―out of the box,‖ you can build or buy components that seamlessly extend Smart GWT in any manner you desire.
Version 3.0 vii
1. Overview Architecture The Smart GWT architecture spans client and server, enabling Rich Internet Applications (RIAs) that communicate transparently with your data and service tiers. Client GUI Rendering & Interactivity Local Operations
Server Data Providers DataSource Schema Metadata and Operations
DataSource Binding
Communication Layer Web Browser
HTTP(S) XMLHttp
Communication Layer
Application Server
Within the web browser, Smart GWT provides a deep stack of services and components for rich HTML5 / Ajax applications. For those using a Java-based server, Smart GWT provides a server-side framework that can be added to any existing Java web application. The client- and server-based components have a shared concept of DataSources, which describe the business objects in your application. By working from a single, shared definition of the data model, client- and server-side components can coordinate closely to deliver much more sophisticated functionality ―out of the box‖ than either a standalone client-based or server-based solution can deliver. For example, validation rules are declared within the DataSource—these rules are then enforced client-side by Smart GWT Ajax components, and server-side by Smart GWT server components. Similarly, the set of valid operations on an object is declared in a DataSource, and this single declaration controls client-side behaviors like whether an editing interface is enabled, and controls security checks on the server for safe enforcement of business rules.
Version 2.3
1
Overview
Smart GWT Quick Start
Using a DataSource as a shared data definition also greatly reduces redundancy between your user interface code and server-side code, increasing agility and reducing maintenance effort. DataSources can be derived on-the-fly or as a batch process from other, pre-existing sources of metadata, such as annotated Java Beans and XML Schema, further reducing system-wide redundancy. This concept of a DataSource as a shared client-side data definition can be used with or without the optional Smart GWT Java server components. However, if you do not use the Smart GWT server components, all serverside functionality of DataSources must be implemented and maintained by your team. Finally, note that Smart GWT does not require that you adopt this entire architecture. You may choose to integrate with only the layers and components that are appropriate for your existing systems and applications.
Capabilities and Editions of Smart GWT Smart GWT comes in several editions, and the features included in each of the editions are described on the SmartClient.com website at http://www.SmartClient.com/product The portions of this document that make use of Smart GWT server components require the Pro license or above. None of the features demonstrated in this document require more than a Pro license. If you have downloaded the LGPL version, we recommend downloading the commercial trial version for use during evaluation. Prototypes built on the commercial edition can be converted to the LGPL version without wasted effort, but the reverse is not true—using the LGPL version for evaluation requires you to expend effort implementing functionality that is already part of the commercial version. For more details, see Chapter 11, Evaluating Smart GWT.
2
Version 2.3
2. Installation Starting a New Project To get started quickly, use the ―built-in-ds‖ sample project included in the Smart GWT SDK under samples/built-in-ds. Within this directory, see the README.txt file for instructions to import the project into the Eclipse IDE or to run the project from the command line using Apache ant. Several other sample projects are provided that demonstrate integration with popular Java technologies. However, because it is the simplest and represents Smart GWT best practices, we recommend starting with the ―built-in-ds‖ project unless you have a specific need to do otherwise. See Chapter 11, Evaluating Smart GWT, for details. Do not start by importing the Showcase project. The Showcase is designed to host several hundred short-lived miniapplications and to demonstrate a variety of data binding approaches. It is not structured like a normal application and does not represent best practices for normal applications.
Adding Smart GWT to an Existing Project If you wish to install Smart GWT into a pre-existing project, see the stepby-step setup guide (http://www.smartclient.com/smartgwtee/javadoc/ com/smartgwt/client/docs/SgwtEESetup.html). For purposes of this Quick Start, we strongly recommend using one of the sample projects, which have a pre-configured, embedded server and database.
Version 2.3
3
Installation
Smart GWT Quick Start
Server Configuration (optional)
You do not need to perform any server configuration for this Quick Start. However, if you choose to complete exercises in later chapters by connecting to an existing database, follow these additional steps:The Smart GWT Admin Console provides a graphical interface to configure database connections, create database tables from DataSource descriptors, and import test data. Note: Requires Smart GWT Server framework. To use the Admin Console, in your gwt.xml file, include the following imports:
After adding these imports you then call com.smartgwtee.tools.client.SCEE.openDataSourceConsole(). IButton adminButton = new IButton("Admin Console"); adminButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { com.smartgwtee.tools.client.SCEE.openDataSourceConsole(); } }); adminButton.draw();
Note: If you are using Pro, the method to call is com.smartgwtpro.tools.client.SCPro.openDataSourceConsole().
Make the corresponding adjustment for Power edition as well.
Other server settings are exposed for direct configuration in the samples in the server.properties file. The server.properties file should be in your Eclipse CLASSPATH. Typically you do this by copying the file to the top of your src folder, so that Eclipse deploys it into war/WEB-INF/ classes.
Settings that apply to servlets can be applied via the standard web.xml file. See the JavaDoc for each servlet for details. If you have any problems installing or starting Smart GWT, try the Smart GWT Developer Forums at forums.smartclient.com.
4
Version 2.3
3. Exploring Smart GWT Showcase To start exploring, visit the Smart GWT EE Showcase at: http://www.smartclient.com/smartgwtee/showcase/ The Showcase is your best starting point for exploring Smart GWT capabilities and code. For each example in the Showcase, you can view the source code by clicking on the View Source button in the upper right side of the example pane. A second Showcase, focusing on capabilities common to both the LGPL and Pro/EE editions, exists at: http://www.smartclient.com/smartgwt/showcase/ For all samples related to data binding, data loading and data integration, focus on the samples in the EE Showcase while you are learning. The data integration samples in the LGPL Showcase focus on concerns that become irrelevant if you adopt Smart GWT Pro or better. To replicate the functionality of a Showcase sample in your own project, copy and paste code from the View Source window. Do not copy code from the samples/showcase folder in the Smart GWT SDK, as this code is designed specifically for running inside the specialized Showcase environment. The View Source window shows source code designed for standalone use.
Version 2.3
5
Visual Components
Smart GWT Quick Start
Smart GWT Java Doc The core documentation for Smart GWT is the Smart GWT JavaDoc. You can access the Smart GWT JavaDoc in any of the following ways: Online: smartclient.com/smartgwtee/javadoc/ (client reference) smartclient.com/smartgwtee/server/javadoc/ (server reference) In the SDK: docs/javadoc (client reference) docs/server (server reference)
There are two special packages in the client reference:
com.smartgwt.client.docs contains conceptual overviews covering cross-cutting concerns that apply to multiple Smart GWT classes and packages. These appear in JavaDoc as Java Interfaces in order to allow interlinking with normal JavaDoc reference. Do not import this package—it is informational only.
com.smartgwt.client.docs.serverds is reference for all properties that may be specified in .ds.xml file (see the Data Binding chapter). Do not import this package—it is informational only.
Smart GWT Developer Console The Smart GWT Developer Console is a suite of development tools implemented in Smart GWT itself. The Console runs in its own browser window, parallel to your running application, so it is always available in every browser and in every deployment environment. Features of the Developer Console include:
logging & runtime diagnostics
runtime component inspection
tracing and profiling
To use the Developer Console, complete the following steps: 1. In your *.gwt.xml file, inherit the module com.smartgwt.tools.SmartGwtTools.
6
Version 2.3
Smart GWT Quick Start
Visual Components
2. Open the Developer Console by typing the URL javascript:isc.showConsole() into the URL bar of the hosted mode browser or any standard browser. The following window will appear:
Popup blocker utilities may prevent the Developer Console from appearing, or browser security settings may disallow JavaScript URLs. Holding the Ctrl key while opening the console will bypass most popup blockers. Creating a bookmark for a JavaScript URL will allow you to execute it by clicking on the bookmark. The Results tab of the Developer Console provides:
Diagnostic messages logged by Smart GWT or your application code through the Smart GWT logging system. The Logging Preferences menu allows you to enable different levels of diagnostics in over 30 categories, from Layout to Events to Data Binding.
Smart GWT component statistics. As you move the mouse in the current application, the ID of the current component under the mouse pointer is displayed in this area.
Version 3.0 7
Visual Components
Smart GWT Quick Start
The Watch pane of the Developer Console displays a tree of Smart GWT user interface components in the current application. With the built-in-ds application running, this pane appears as follows:
In the Watch tab, you may:
8
Click on any item in the tree to highlight the corresponding component in the main application window with a flashing, red-dotted border.
Version 2.3
Smart GWT Quick Start
Visual Components
Right-click on any item in the tree for a menu of operations on that component.
Click on the ―hidden,‖ ―undrawn,‖ and ―generated‖ checkboxes to reveal additional components which are not currently visible, or are internally generated subcomponents of the Smart GWT components you have created.
The RPC tab shows requests for data issued by Smart GWT components.
Enable this tab by checking the ―Track RPCs‖ checkbox. This tool shows you:
Which component issued the request
What logical type of request it was (such as a DataSource ―update‖ request)
A logical view of the request and response objects (instead of the raw HTTP request)
Version 3.0 9
Visual Components
Smart GWT Quick Start
The Developer Console is an essential tool for all Smart GWT application developers and should be open whenever you are working with Smart GWT. For easy access, you should create a toolbar link to quickly show the Console: In Firefox/Mozilla: 1. Show your Bookmarks toolbar if it is not already visible (View > Toolbars > Bookmarks Toolbar). 2. Go to the Bookmarks menu and pick Manage Bookmarks… 3. Click the New Bookmark button and enter ―javascript:isc.showConsole()” as the bookmark Location, along with whatever name you choose. 4. Drag the new bookmark into the Bookmarks Toolbar folder. In Internet Explorer: 1. Show your Links toolbar if it is not already visible (View > Toolbars > Links). 2. Type ―javascript:isc.showConsole()” into the Address bar. 3. Click on the small Isomorphic logo in the Address bar and drag it to your Links toolbar. 4. If a dialog appears saying ―You are adding a favorite that may not be safe. Do you want to continue?” click Yes. 5. If desired, rename the bookmark (―isc” is chosen as a default name) The Developer Console is associated with a single web browser tab or window at any time. If you have shown the console for a Smart GWT application in one browser window, and then open an application in another browser window, you must close the console before you can show it from the new window.
10
Version 2.3
Smart GWT Quick Start
Visual Components
4. Visual Components Smart GWT provides two families of visual components for rich web applications:
Independent visual components, which you create and manipulate directly in your applications.
Managed form controls, which are created and managed automatically by their ―parent‖ form or editable grid.
This chapter provides basic usage information for the independent components only. Managed form controls are discussed in more detail in Chapter 5, Data Binding, and especially Chapter 6, Layout.
Component Documentation & Examples Visual components encapsulate and expose most of the public capabilities in Smart GWT, so they have extensive documentation and examples in the Smart GWT SDK: Smart GWT Java Doc—For component interfaces (APIs), see http://www.smartclient.com/smartgwtee/javadoc/com/ smartgwt/client/widgets/package-summary.html. Form controls are covered in: http://www.smartclient.com/smartgwtee/javadoc/com/ smartgwt/client/widgets/form/fields/package-summary.html Component Code Examples—For live examples of component usage, see the Smart GWT Showcase: http://www.smartclient.com/smartgwt/showcase . To view the code for these examples, click on the ―View Source‖ button in the upper right corner of the tab. The remainder of this chapter describes basic management and manipulation of independent visual components only. For information on the creation and layout of managed form controls, see Chapter 5, Data Binding, and Chapter 6, Layout, respectively.
Version 3.0 11
Visual Components
Smart GWT Quick Start
Drawing, Hiding, and Showing Components To cause a Smart GWT component to draw (create its appearance via HTML), call draw(). Label labelHello = new Label("Hello World"); labelHello.draw();
Components can subsequently be hidden and re-shown as a user navigates between different parts of the application, using these APIs:
hide()
show()
For example, to hide the label that was just drawn: labelHello.hide();
UI components built into GWT itself (under the com.google.gwt package) are typically made visible by calling RootPanel.get().add(widget). This is not the recommend approach for Smart GWT widgets. See Chapter 10, Tips, for more information.
Size and Overflow The most basic properties for a visual component involve its size and overflow:
width
height
overflow
Width and height allow either integer values, representing a number of pixels, or percentage values expressed as a String (such as "50%"), representing a percentage of the container‘s size (the entire web page, or another Smart GWT component). For example: Label labelHello = new Label ("Hello World"); labelHello.setWidth(10);
In this example, the specified width is smaller than the contents of the label, so the text wraps and ―overflows‖ the specified size of the label. This behavior is controlled by the overflow property, which is managed automatically by most components. You may want to change this setting
12
Version 2.3
Smart GWT Quick Start
Visual Components
for Canvas, Label, DynamicForm, DetailViewer, or Layout components, whose contents you want to clip or scroll instead. To do this, set the overflow property to ―hidden‖ (clip) or ―auto‖ (show scrollbars when needed). For example: import com.smartgwt.client.types.Overflow; Label labelHello = new Label ("Hello World"); labelHello.setWidth(10); labelHello.setOverflow(Overflow.HIDDEN);
This will show a 10 pixel wide Label for which the text ―Hello World‖ is clipped. In most applications, you will place your components into layout managers which dynamically determine their size and position. Chapter 6, Layout, introduces the Smart GWT Layout managers, which you can use to automatically size, position, and reflow your components at runtime.
Handling Events Smart GWT applications implement interactive behavior by responding to events generated by their environment or user actions. You can provide the logic for hundreds of different events by implementing event handlers. The most commonly used Smart GWT events include:
Click
(for buttons and menu items)
RecordClick
(for list grids and tree grids)
Changed
(for form controls)
TabSelected
(for tabsets)
If a Smart GWT component has support for a given type of event, it will implement a Java interface HasEventNameHandlers such as HasClickHandlers. These interfaces allow registration of an EventHandler object that receives an Event object when the event occurs. For example: import com.smartgwt.client.widgets.Button; Button btn = new Button("Click me"); btn.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { // respond to the event here } });
Version 3.0 13
Visual Components
Smart GWT Quick Start
The Event object your event handler receives has methods that allow you to retrieve information about the current event. For example, the RecordClickEvent has a getRecord()method that allows you to retrieve the Record that was clicked. In addition to methods on Event objects, information common to many types of events is available from static methods on the central EventHandler class in the package com.smartgwt.client.util. For more information on available Smart GWT events, see:
14
Smart GWT JavaDoc—Component-specific APIs under com.smartgwt.client.widgets.
Version 2.3
5. Data Binding Databound Components You can bind certain Smart GWT components to DataSources, which provide their structure and contents. The following visual components are designed to display, query, and edit structured data: Visual Component
Query & Display Data
Edit Data
DynamicForm
ListGrid
TreeGrid
Calendar
DetailViewer
TileGrid
ColumnTree
Databound components provide you with both automatic and manual databinding behaviors. For example:
Automatic behavior—A databound ListGrid will generate Fetch operations when a user scrolls the list to view more records.
Manual behavior—You can call removeSelectedData() on a databound ListGrid to perform Remove operations on its datasource. This chapter outlines the client-side interfaces that you may use to configure databound components and interact with their underlying DataSources. Chapter 7, Data Integration, outlines the interfaces for server-side integration of DataSources with your data and service tiers.
Visual Components
Smart GWT Quick Start
Fields Fields are the building blocks of databound components and DataSources. There are two types of field definitions:
Component fields provide presentation attributes for databound visual components (such as width and alignment of columns in a table). Component fields are discussed immediately below.
DataSource fields provide metadata describing the objects in a particular datasource (such as data type, length, and required).
Component fields display as the following sub-elements of your databound components:
16
Component
Fields
DynamicForm
form controls
ListGrid
columns & form controls
TreeGrid
columns & form controls
Calendar
event duration and description
ColumnTree
columns & form controls
DetailViewer
rows within blocks
TileGrid
rows within tiles
CubeGrid (Analytics option)
facets (row & column headers)
Version 3.0
Smart GWT Quick Start
Visual Components
You can specify the displayed fields of a visual component via the setFields() method, which takes an array of objects defining the fields for that component. For example: ListGrid grid = new ListGrid(); ListGridField salutationField = new ListGridField(); salutationField.setName("salutation"); salutationField.setTitle("Title"); ListGridField firstNameField = new ListGridField(); firstNameField.setName("firstname"); firstNameField.setTitle("First Name"); ListGridField lastNameField = new ListGridField(); lastNameField.setName("lastname"); lastNameField.setTitle("Last Name"); grid.setFields(salutationField, firstNameField, lastNameField); grid.draw();
Note that ListGridField actually has shortcut constructors that simplify this, for example: ListGridField salutationField = new ListGridField ("salutation", "Title");
Try running the example code above. When you load it in your web browser, you should see a ListGrid that looks like this:
Version 3.0 17
Visual Components
Smart GWT Quick Start
The name property of a field is the special key that connects that field to actual data values. To add records to the fields, add this code to the ListGrid definition above: ListGridRecord record1 = new ListGridRecord(); record1.setAttribute("salutation", "Ms"); record1.setAttribute("firstname","Kathy"); record1.setAttribute("lastname","Whitting"); ListGridRecord record2 = new ListGridRecord(); record2.setAttribute("salutation", "Mr"); record2.setAttribute("firstname","Chris"); record2.setAttribute("lastname","Glover"); ListGridRecord record3 = new ListGridRecord(); record3.setAttribute("salutation", "Mrs"); record3.setAttribute("firstname","Gwen"); record3.setAttribute("lastname","Glover"); grid.setData(new ListGridRecord[] { record1, record2, record3 });
Now when you load this example, you should see:
This approach is appropriate mainly for lightweight, readonly uses (that is, for small, static lists of options). When your components require dynamic data operations, data-type awareness, support for large datasets, or integration with server-side DataSources, you will use the setDataSource() method instead to bind them to DataSource objects. See DataSources later in this chapter for details.
18
Version 3.0
Smart GWT Quick Start
Visual Components
The basic properties of field definitions (name, title) in the ListGrid above are the same as the properties used across other components that support data binding. For example, this very similar code creates a DynamicForm for working with the same Records: import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.FormItem; DynamicForm form = new DynamicForm(); TextItem salutationItem = new TextItem(); salutationItem.setName("salutation"); salutationItem.setTitle("Title"); TextItem firstNameItem = new TextItem(); firstNameItem.setName("firstname"); firstNameItem.setTitle("First Name"); TextItem lastNameItem = new TextItem(); lastNameItem.setName("lastname"); lastNameItem.setTitle("Last Name"); form.setFields(new FormItem[] { salutationItem, firstNameItem, lastNameItem }); form.draw();
This will display as:
For complete documentation of field properties (presentation attributes) for ListGrid and DynamicForm, see:
DataSources Smart GWT DataSource objects provide a presentation-independent, implementation-independent description of a set of persistent data fields. DataSources enable you to:
Share your data models across multiple applications and components, and across both client and server.
Display and manipulate persistent data and data-model relationships (such as parent-child) through visual components (such as TreeGrid).
Execute standardized data operations (fetch, sort, add, update, remove) with built-in support on both client and server for data typing, validators, paging, unique keys, and more.
Leverage automatic behaviors including data loading, caching, filtering, sorting, paging, and validation.
A DataSource descriptor provides the attributes of a set of DataSource fields. DataSource descriptors can be specified in XML format or created in Java code. The XML format is interpreted and shared by both client and server, while DataSources created in Java are used by the client only. Note that use of the XML format requires the Smart GWT Server. The Smart GWT Server can also derive DataSources from existing sources of metadata formats such as Java Beans or SQL schema – see Chapter 8, Smart GWT Server Framework, for details. There are four basic rules to creating XML DataSource descriptors: 1. Specify a unique DataSource ID attribute. The ID will be used to bind to visual components, and as a default name for objectrelational (table) bindings and test data files. 2. Specify a field element with a unique name (unique within the DataSource) for each field that will be used in a databound UI component. 3. Specify a type attribute on each field element (see the code sample that follows for supported data types). 4. Mark exactly one field with primaryKey="true". The primaryKey field must have a unique value in each data object (record) in a DataSource. A primaryKey field is not required for read-only DataSources, but it is a good general practice to allow for future add, update, or remove data operations.
20
Version 3.0
Smart GWT Quick Start
Visual Components
Following these rules, a DataSource descriptor for personal contacts might look as follows: MsMrMrsEmployedUnemployed
title="Follow up"
type="sequence" /> type="text" >
type="text" type="text" type="date" type="text"
/> /> /> >
type="text" length="2000" /> type="boolean" />
To load this DataSource: 1. Save the XML as contacts.ds.xml in your project, under war/ds. This is the default location that the Smart GWT server framework looks for DataSource descriptors. 2. Add a
In your Java code, access the DataSource like this: DataSource contactsDS = DataSource.get("contacts");
You can now supply this DataSource to the components via the setDataSource() method. The complete code for a page that binds a grid and form to this DataSource is: DataSource contactsDS = DataSource.get("contacts"); ListGrid grid = new ListGrid(); grid.setDataSource(contactsDS); DynamicForm form = new DynamicForm(); form.setLeft(300); // avoid overlap form.setDataSource(contactsDS);
Version 3.0 21
Visual Components
Smart GWT Quick Start
In this example, the grid and form components are now automatically generating component fields based on DataSource fields. Note that the form has chosen specific controls for certain fields—it does so based on the following rules: Field attribute
Form control
valueMap provided
SelectItem (dropdown)
type boolean
CheckboxItem (checkbox)
type date
DateItem (date control)
length > 255
TextAreaItem (large text box)
You can override these choices by setting the editorType attribute on the tag in the .ds.xml file to the Java classname of the desired FormItem. Other common DataSource field properties include:
22
Property
Values
name
Unique field identifier (required on every DataSource field)
Defaults to true; specifies whether this field should be hidden from the end user. When hidden, it will not appear in the default presentation, and it will not appear in any field selectors (such as the column picker menu in a ListGrid).
detail
Defaults to true; specifies whether this field is a ―detail‖ that should not be shown by default in multi-record summary views such as a ListGrid.
required
―true‖ | ―false‖; applies validation on both client and server to verify that the field is non-blank.
valueMap
An array of values, or an object containing storedValue:displayValue pairs.
editorType
FormItem class to use when editing this field (in any DataBoundComponent).
Version 3.0
Smart GWT Quick Start
Visual Components
primaryKey
Defaults to true; specifies whether this is the field that uniquely identifies each record in this DataSource (that is, it must have a unique value for each record). Each DataSource must have exactly one field with primaryKey="true". The primaryKey field is often specified with type="sequence" and hidden="true", to generate a unique internal key for rapid prototyping.
foreignKey
A reference to a field in another DataSource (dsName.fieldName).
rootValue
For fields that establish a tree relationship (by foreignKey), this value indicates the root node of the tree.
For more information on DataSources and a complete reference of properties that may be set in .ds.xml files, see
Smart GWT JavaDoc: com.smartgwt.client.docs.serverds Do not import this package—it is informational only. For DataSource usage examples, see the descriptors in samples\ showcase\war\ds. These DataSources are used in various Smart GWT SDK examples, including the Smart GWT EE Showcase. For an example of a DataSource relationship using foreignKey, see the TreeGrid example in the Smart GWT EE Showcase (TreeGrid UI) and samples\showcase\war\ds\ employees.ds.xml (associated DataSource).
Customized Data Binding You can also combine DataSource binding and component-specific field definitions. Smart GWT merges your component field definitions and DataSource field definitions by using the name property of the fields to match component fields with DataSource fields. In this case, component field definitions specify presentation attributes specific to that component, while the DataSource field definitions specify data attributes and presentation attributes common to all DataBoundComponents.
Version 3.0 23
Visual Components
Smart GWT Quick Start
By combining component-specific fields and DataSource fields, you can share data model attributes and common presentation attributes across all components, while still allowing full customization of individual components for a specific use case. For example, a ListGrid component might specify a shorter title attribute for more compact display (―Percentage‖ represented as ―%‖). Components can also have additional fields not defined in the DataSource. For example, a user registration form might have a second password field to ensure that the user has typed his password correctly. By default, a component with both fields and a DataSource will only show the fields defined on the component, in the order they are defined on the component. To change this behavior, use setUseAllDataSourceFields(true). Now, all DataSource fields will be shown unless you provide a component field definition where you have called setHidden(true). For an example of customized binding, see Forms → Validation → Customized Binding in the Smart GWT Showcase. For more information on the layout of managed form controls, see the section Form Layout in Chapter 6.
DataSource Operations Smart GWT provides a standardized set of data operations that act upon DataSources:
24
Operation Methods
Description
Fetch
fetchData(…)
Retrieves records from the datasource that match the provided criteria.
Add
addData(…)
Creates a new record in the datasource with the provided values.
Update
updateData(…)
Updates a record in the datasource with the provided values.
Remove
removeData(…)
Deletes a record from the datasource that exactly matches the provided criteria.
Version 3.0
Smart GWT Quick Start
Visual Components
These methods each take three parameters:
a data object containing the criteria for a Fetch or Filter operation, or the values for an Add, Update, or Remove operation
a callback expression that will be evaluated when the operation has completed
a properties object containing additional parameters for the operation—timeout length, modal prompt text, and so on (see DSRequest in the Smart GWT Reference for details)
You may call any of these four methods directly on a DataSource object or on a databound ListGrid or TreeGrid. For example, the following code saves a new Record to the contactDS DataSource and displays a confirmation when the save completes: import com.smartgwt.client.data.DSCallback; import com.smartgwt.client.data.DSResponse; Record contact = new Record(); contact.setAttribute("salutation", "Mr."); contact.setAttribute("firstname", "Steven"); contact.setAttribute("lastname", "Hudson"); DSCallback callback = new DSCallback() { public void execute(DSResponse response, Object rawData, DSRequest request) { Record savedContact = response.getData()[0]; SC.say(savedContact.getAttribute("firstname")+ "added to contact list"); } }; contactDS.addData(contact,callback);
DataSource operations will only execute successfully if the DataSource is bound to a persistent data store. You can create relational database tables from a DataSource .ds.xml file by using the Import DataSources section in the Smart GWT Admin Console. For integration with pre-existing business logic or non-SQL persistence systems, see Chapter 7, Data Integration.
Version 3.0 25
Visual Components
Smart GWT Quick Start
DataBound Component Operations In addition to the standard DataSource operations listed above, you can perform Add and Update operations from databound form components by calling the following DynamicForm methods: Method
Description
editRecord()
Starts editing an existing record
editNewRecord()
Starts editing a new record
saveData()
Saves the current edits (add new records; update existing records)
Databound components also provide several convenience methods for working with the selected records in components that support selection, such as ListGrid: Convenience Method listGrid.removeSelectedData() dynamicForm.editSelectedData(listGrid) detailViewer.viewSelectedData(listGrid) Each sample in the samples directory in the SDK shows the most common DataBoundComponents interacting with DataSources.
26
Version 3.0
Smart GWT Quick Start
Visual Components
Data Binding Summary This chapter began by introducing Databound Components, to build on the concepts of the previous chapter, Visual Components. However, in actual development, DataSources usually come first. The typical steps to build a databound user interface with Smart GWT components are: 1. Create DataSource descriptors (.ds.xml files), specifying data model (metadata) properties in the DataSource fields. 2. Back your DataSources with an actual data store. The Smart GWT Admin Console GUI can create and populate relational database tables for immediate use. Chapter 7, Data Integration, describes the integration points for binding to other object models and data stores. 3. Load DataSource descriptors in your Smart GWT-enabled pages using a standard