Reusable WebObjects Components
Volume Number: 18 (2002)
Issue Number: 8
Column Tag: WebObrjects Development
Reusable WebObjects Components
by Tom Woteki
Introduction
One of the more interesting and powerful features of WebObjects is the ability to construct reusable components. However neither the documentation nor any of the available books on WebObjects cover this topic very well. The best discussions are in Professional WebObjects 5.0 with Java (DeMan, et. al. 2001), and the Windows and version 4.5-oriented WebObjects Web Application Construction Kit (Ruzek 2001). Both of these treatments, though instructive, leave a lot to the reader. The common example that both books cover is how to construct a standard template for an application.
This article illustrates how to build reusable components using two examples drawn from a WebObjects application I wrote to maintain records of a wine collection. It also illustrates creating custom component bindings and communications between components using key-value coding. The example components have wide applicability to the maintenance of reference tables and are easily generalized to maintaining any single attribute of a database table.
This article assumes you are familiar with at least the basics of building a WebObjects database application including using interface widgets, forms, actions, data models and display groups.
The Example Problem: Maintaining a Reference Table
A common type of table in a database application is a reference table, that is, a table consisting of two columns: a primary key and the attribute of interest. An example is a table of country names. In my application there are reference tables for wine producing countries, wine regions, wine names and so on. Given such reference tables, an obvious need is to maintain the tables, either to add new records or to update existing records. Because my application uses multiple reference tables, and noting the obvious generality of the situation, I decided to develop some reusable components for maintaining any reference table. We'll see how to use these components in an example application to maintain a reference table of country names.
High-Level Design
The approach I took was to develop two components, each designed to be embedded in a form within a parent component. One component, the "selector", is used either to select an existing record to edit or to initiate insertion of a new record. The other, the "editor", is used to actually edit the selected record or create the new one. The two components communicate with each other through key-value coding whereby the selector passes the user's intent and other information to the editor. We use bindings to designate the specific table and attribute the components should edit.
Figures 1 and 2 show the respective finished products, each embedded in parent components. The selector component in Figure 1 consists only of the WOPopUpButton and the two form buttons "Edit" and "New". The former button initiates an update of a selected record, the latter initiates insertion of a new record. The remaining aspects of the interface, such as the prompt string, pertain to parent components such as the page itself. Similarly, the editor component in Figure 2 consists only of a WOTextField and two form buttons. The separate implementation of the components, apart from communications via key-value coding, and their separation from aspects of the surrounding interface, including the form they are embedded in, maximizes their reusability and adaptability to different interface designs.
Figure 1: The finished selector component in action
Figure 2: The finished editor component in action
Detailed Design
Now let's consider details of the preceding design. First of all, let's name the components we're going to build WOObjectSelector and WOObjectEditor. Viewing Figure 1 it should be clear that we must at least provide WOObjectSelector the list it should display in its WOPopUpButton menu and the page(s) to return when either its "Edit" or "New" buttons are clicked. In this design both buttons will return the same page. We might also want to provide the component a "no selection" string to display when there is no selection in the pop-up. Since we are editing a reference table, you can anticipate that we will bind a WODisplayGroup to the pop-up's display list. And you might anticipate that the return page for the buttons should be some page that encloses WOObjectEditor as a child component. Before we discuss these details, including how to provide WOObjectSelector the information it needs, let's consider what WOObjectEditor needs to do its job.
Viewing Figure 2, we can see that we need to provide the editor at least the data for the attribute of the record we are editing (in our example, the name of a country) plus the return page for the form buttons. Even more is needed, however. First of all it would be helpful to know if we are updating an existing record or inserting a new one. Second, if updating we'll need the record itself, not just the data for the attribute of interest. In order to achieve reusability, we'll provide not only the record, but the key for the attribute as well, so that we can use the powerful generality of key-value coding to update the value of any attribute. Finally, in case of inserting a new record, we'll need to create the record and insert it into the default editing context, so we'll need to provide WOObjectEditor the name of the entity to create as well as the key for the pertinent attribute.
Which component will provide WOObjectEditor the information it needs and how? WOObjectSelector knows whether the user is updating or inserting by means of the button the user clicks. If updating, it also knows the record the user is updating, namely the one corresponding to the item selected in the display list. So, WOObjectSelector is the logical provider of this information. It will do so by invoking the key-value coding method takeValueForKey (which is inherited by any class that extends WOComponent) on the parent page that encloses WOObjectEditor. It will invoke the method for each of a series of keys corresponding to the data needed by WOObjectEditor. The parent page for WOObjectEditor is also the return page for WOObjectSelector's buttons. This page, having received the required values from WOObjectSelector, will set the values needed by WOObjectEditor using API bindings. (Note that assignments specified by API bindings are performed behind the scenes by WebObjects using key-value coding.) Finally, the additional information needed by WOObjectEditor, such as the name of the entity we are working with, will be passed through from the parent page of WOObjectSelector using the same techniques.
Figure 3 neatly summarizes the flow of information and the methods for communicating between components. The parent page of WOObjectSelector passes to it the global context, namely entityName and attributeKey, plus the information the selector specifically needs using API bindings. WOObjectSelector then passes the global context along with other specifics that WOObjectEditor needs, such as the user's selection, to the latter's parent using key-value coding. Finally, the editor component's parent passes the information to it using API bindings.
Figure 3.
Now let's consider the details of each component.
WOObjectSelector
Figure 4 shows the layout and keys for WOObjectSelector. The component consists of a WOPopUpButton and two submit buttons within a table. The keys attributeKey, displayList, entityName, noSelectionString and returnPageName were mentioned previously. Their values are passed into the component by its parent.
The other keys, displayAttribute, displayObject and selectedObject are used locally. displayAttribute is a method that returns the string for each item displayed in the pop up menu; it uses key-value coding to retrieve the string using attributeKey as the key (Listing 1). The key displayObject is the local EOGenericRecord on which the display list iterates and selectedObject stores the user's selection as an EOGenericRecord. Implicit in this is that a WODisplayGroup's array of EOGenericRecords, has been bound to displayList by the parent. The actions editObjectAttribute and insertNewObject are bound to the "Edit" and "New" buttons, respectively.
Figure 4: Details of WOObjectSelector
Figure 5 shows the API editor view of WOObjectSelector with the five keys that must be bound by a parent component. Figure 6 shows how WOObjectSelector is embedded in a form element within its parent page, "Main", in the demo application, and the bindings implemented therein. (Be sure to set up the form for multiple submit buttons.) There is only one key declared in Main, namely a WODisplayGroup associated with the example application's reference table, called "Country", whose attribute of interest is "country".
Listings 2 and 3 show the implementation of the actions invoked by WOObjectSelector's buttons. Each simply creates an instance of the return page using the value bound to returnPageName and then invokes takeValueForKey on the page to set the values that WOObjectEditor will eventually need. As mentioned earlier, every child class of WOComponent inherits this key-value coding method.
There is no custom code for the Main class other than the WODisplayGroup variable countryDisplayGroup, which is bound to an entity called Country in the data model for this example application.
Figure 5: API Editor view of WOObjectSelector
Figure 6: WOObjectSelector laid out in its parent page
WOObjectEditor
Figure 7 shows the layout and keys for WOObjectEditor. The component consists of two WOConditionals, one for the case when the user is updating a record the other for creating a new record. Each conditional consists of a WOTextField and two submit buttons. Four actions are declared in Figure 7, one for each of the buttons. Recall Figure 2. Although the component has four buttons, the user only sees two depending on the choice they made from the selector component.
The keys attributeKey, entityName, insertingNewObject, updatingObject and objectToEdit were mentioned earlier. WOObjectSelector provides their values via the editor component's parent using the aforementioned key-value coding and API binding techniques. The editor's parent component provides the value for returnPageName. In our example we simply return to the Main page. As in WOObjectSelector, the key displayAttribute is a method that returns the display string corresponding to the attribute of objectToEdit that we are updating.
Figure 7: Details of WOObjectEditor
Figure 8 displays the API Editor view of WOObjectEditor with the six keys that must be bound by a parent component. Figure 9 shows how WOObjectEditor is embedded in its parent page, "CountryEditor", in the demo application and the bindings implemented therein. Notice how the Boolean values insertingNewObject and updatingObject are used not only by WOObjectEditor but also by the enclosing page itself to vary the prompt depending on the action the user selected.
Figure 8: API Editor view of WOObjectEditor
Listings 4 and 5 show the implementations for the actions insertNewObject and updateObject. The former creates a new instance of the entity specified by entityName then sets the value of the specified attribute using key-value coding. Upon inserting the new record into the default editing context, it saves the changes. The updateObject method simply sets the new value of objectToEdit using key-value coding, then saves the changes.
Figure 9: WOObjectEditor laid out in a its parent page, CountryEditor
Enhancements and Improvements
Our pair of components is already very useful and highly reusable. However, there are possibilities for improvements. One concerns validation and associated exception handling as follows:
The two action methods insertNewObject and updateObject have built-in validation rules; as written they each enforce a non-null value for every attribute of every entity. This may not be unreasonable in the case of reference tables, but it isn't as flexible as it could be. Moreover, there is no exception handling for the possibility that either insertObject or saveChanges fails. These operations could fail for a variety of reasons including constraints built in to the data model(s) used in a real application.
There are two obvious alternatives to implementing improved validation and exception handling. One is to override the method validationFailedWithException in the page that encloses WOObjectEditor. Every component inherits this method. One would probably implement it in the editor component's parent because the parent knows the context in which validation occurs. Another route would be to subclass and provide the subclass with the required context. I probably would choose the former path since the context is already known there.
Summary
This article has illustrated the design and construction of reusable WebObjects components and inter-component communication using key-value coding. The fully functional components discussed herein are widely applicable to the maintenance of reference tables, a common situation.
Bibliography and References
The interested reader may find the following books useful. Of the three, Ruzek's book is the best, in my opinion. Unfortunately, it is based on WebObjects version 4.5 and emphasizes development under Windows. Nevertheless, much is applicable and the examples are pretty good. DeMan et al's book is based on version 5 and incorporates references to OSX. Their discussion of validation, key-value coding and other important topics is very good. However, the book is a bit rough around the edges in some places perhaps reflecting its multiple authorship and the need for a bit more editing. Feiler's book is the least helpful. After a very long (60 pages) and general introduction, the book finally gets around to discussing OpenBase. For many topics the author merely recapitulates Apple's documentation, for others he provides only the most cursory treatment and no concrete examples.
- DeMan, Michael, Frederico, Gustavo, et. al. Professional WebObjects 5.0 with Java, Wrox Press Ltd., Birmingham, UK, 2001.
- Ruzek, George. WebObjects Web Application Development Kit, Sams Publishing, Indianapolis, 2001
- Feiler, Jesse. Building WebObjects 5 Applications, McGraw-Hill/Osborne, Berkeley, 2002.
Listing 1: WOObjectSelector.java
displayAttribute
public String displayAttribute(){
return (String) displayObject.valueForKey(attributeKey);
}
Listing 2: WOObjectSelector.java
editObjectAttribute
public WOComponent editObjectAttribute(){
/*
The user needs to select some value to edit;
if not, do nothing.
*/
if (selectedObject == null) return null;
WOComponent nextPage =
(WOComponent)pageWithName(returnPageName);
nextPage.takeValueForKey(entityName,"entityName");
nextPage.takeValueForKey(selectedObject,"objectToEdit");
nextPage.takeValueForKey(attributeKey,"attributeKey");
nextPage.takeValueForKey(Boolean.TRUE,"updatingObject");\
nextPage.takeValueForKey(Boolean.FALSE,
"insertingNewObject");
return nextPage;
}
Listing 3: WOObjectSelector.java
insertNewObject
public WOComponent insertNewObject(){
WOComponent nextPage =
(WOComponent)pageWithName(returnPageName);
nextPage.takeValueForKey(entityName,"entityName");
nextPage.takeValueForKey(null,"objectToEdit");
nextPage.takeValueForKey(attributeKey,"attributeKey");
nextPage.takeValueForKey(Boolean.FALSE,"updatingObject");
nextPage.takeValueForKey(Boolean.TRUE,
"insertingNewObject");
return nextPage;
}
Listing 4: WOObjectEditor.java
insertNewObject
public WOComponent insertNewObject() {
if (displayAttribute!=null &&
displayAttribute.length()>0){
/*
the user has entered a non-blank string;
create a new object
*/
EOClassDescription description =
EOClassDescription.classDescriptionForEntityName(
entityName);
EOEnterpriseObject newObject =
description.createInstanceWithEditingContext(null,
null);
newObject.takeValueForKey(displayAttribute,
attributeKey);
EOEditingConext dec =
this.session().defaultEditingContext();
dec.insertObject(newObject);
dec.saveChanges();
}
WOComponent nextPage =
(WOComponent)pageWithName(returnPageName);
return nextPage;
}
Listing 5: WOObjectEditor.java
updateObject
public WOComponent updateObject(){
if (displayAttribute!=null &&
displayAttribute.length()>0){
// the user has entered a non-blank string
objectToEdit.takeValueForKey(displayAttribute,
attributeKey);
this.session().defaultEditingContext().saveChanges();
}
WOComponent nextPage =
(WOComponent)pageWithName(returnPageName);
return nextPage;
}
In addition to being a Macintosh and WebObjects hobbyist developer, Tom Woteki, aka Dr. Wo, is a vice president at TRW Systems. He can be reached at drwo@woteki.com