TweetFollow Us on Twitter

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

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »

Price Scanner via MacPrices.net

Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more

Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.