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

Minecraft 1.20.2 - Popular sandbox build...
Minecraft allows players to build constructions out of textured cubes in a 3D procedurally generated world. Other activities in the game include exploration, gathering resources, crafting, and combat... Read more
HoudahSpot 6.4.1 - Advanced file-search...
HoudahSpot is a versatile desktop search tool. Use HoudahSpot to locate hard-to-find files and keep frequently used files within reach. HoudahSpot is a productivity tool. It is the hub where all the... Read more
coconutBattery 3.9.14 - Displays info ab...
With coconutBattery you're always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in... Read more
Keynote 13.2 - Apple's presentation...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more
Apple Pages 13.2 - Apple's word pro...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 13.2 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more

Latest Forum Discussions

See All

Square Enix commemorates one of its grea...
One of the most criminally underused properties in the Square Enix roster is undoubtedly Parasite Eve, a fantastic fusion of Resident Evil and Final Fantasy that deserved far more than two PlayStation One Games and a PSP follow-up. Now, however,... | Read more »
Resident Evil Village for iPhone 15 Pro...
During its TGS 2023 stream, Capcom showcased the Following upcoming ports revealed during the Apple iPhone 15 event. Capcom also announced pricing for the mobile (and macOS in the case of the former) ports of Resident Evil 4 Remake and Resident Evil... | Read more »
The iPhone 15 Episode – The TouchArcade...
After a 3 week hiatus The TouchArcade Show returns with another action-packed episode! Well, maybe not so much “action-packed" as it is “packed with talk about the iPhone 15 Pro". Eli, being in a time zone 3 hours ahead of me, as well as being smart... | Read more »
TouchArcade Game of the Week: ‘DERE Veng...
Developer Appsir Games have been putting out genre-defying titles on mobile (and other platforms) for a number of years now, and this week marks the release of their magnum opus DERE Vengeance which has been many years in the making. In fact, if the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 22nd, 2023. I’ve had a good night’s sleep, and though my body aches down to the last bit of sinew and meat, I’m at least thinking straight again. We’ve got a lot to look at... | Read more »
TGS 2023: Level-5 Celebrates 25 Years Wi...
Back when I first started covering the Tokyo Game Show for TouchArcade, prolific RPG producer Level-5 could always be counted on for a fairly big booth with a blend of mobile and console games on offer. At recent shows, the company’s presence has... | Read more »
TGS 2023: ‘Final Fantasy’ & ‘Dragon...
Square Enix usually has one of the bigger, more attention-grabbing booths at the Tokyo Game Show, and this year was no different in that sense. The line-ups to play pretty much anything there were among the lengthiest of the show, and there were... | Read more »
Valve Says To Not Expect a Faster Steam...
With the big 20% off discount for the Steam Deck available to celebrate Steam’s 20th anniversary, Valve had a good presence at TGS 2023 with interviews and more. | Read more »
‘Honkai Impact 3rd Part 2’ Revealed at T...
At TGS 2023, HoYoverse had a big presence with new trailers for the usual suspects, but I didn’t expect a big announcement for Honkai Impact 3rd (Free). | Read more »
‘Junkworld’ Is Out Now As This Week’s Ne...
Epic post-apocalyptic tower-defense experience Junkworld () from Ironhide Games is out now on Apple Arcade worldwide. We’ve been covering it for a while now, and even through its soft launches before, but it has returned as an Apple Arcade... | Read more »

Price Scanner via MacPrices.net

New low price: 13″ M2 MacBook Pro for $1049,...
Amazon has the Space Gray 13″ MacBook Pro with an Apple M2 CPU and 256GB of storage in stock and on sale today for $250 off MSRP. Their price is the lowest we’ve seen for this configuration from any... Read more
Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for $199.99 including free shipping. Their price is $50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for $1249 shipped. That’s $250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for $2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a $350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to $350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a $250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for $699 including free shipping. Their price is $100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take $150 o...
Verizon is offering a $150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for $379 for a limited time. B&H’s price is $70 off Apple’s MSRP, and it’s the lowest price... Read more

Jobs Board

Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a 4-star senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a 4-star rated senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! Read more
Optometrist- *Apple* Valley, CA- Target Opt...
Optometrist- Apple Valley, CA- Target Optical Date: Sep 23, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 796045 At Target Read more
Senior *Apple* iOS CNO Developer (Onsite) -...
…Offense and Defense Experts (CODEX) is in need of smart, motivated and self-driven Apple iOS CNO Developers to join our team to solve real-time cyber challenges. 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.