Pre-populate forms

Pre-populating form elements is a very common and important task in a web application. If pre-population is implemented effectively, then a web app becomes both simpler and more robust.

Forms are used for two kinds of operations: editing the database, and defining search criteria.

When editing the database, there are two use cases for forms:

In both cases, the user makes entries in the form, and then submits it for processing, using a POST. If an error is detected, then there is a "return to sender" operation, and the HTML form is redisplayed, with all its items dynamically pre-populated, showing their most recently entered values. Appropriate error messages are also displayed.

(For forms used for input of search criteria, the behavior is similar to the "add" use case described above, with the important difference that the form uses GET instead of POST.)

How can this behavior be implemented most effectively?

One method uses a single custom Populate tag, and is guided by the idea that adding pre-population to a form should have an absolutely minimal affect on the markup used in the case of a regular, static HTML form. This seems very effective, since

An inferior style, commonly seen in frameworks such as Struts and Java Server Faces, replaces the standard HTML tags such as <INPUT> and <SELECT> with a parallel collection of custom tags. Such a style has these disadvantages:

Example

The web4j framework implements such a Populate tag. Here, a JSP uses the <w:populate> tag to wrap the controls of a <FORM> tag that may need dynamic population. Note how the <w:populate> tag simply wraps the body of the form, and represents an absolutely minimal change to the style used in a simple, static HTML form.

<w:populate using="itemForEdit">
 <form action='MemberAction.do' method="post">
  <input name="Id" type="hidden">
  <table align="center">
   <tr>
    <td><label>Name</label> *</td>
    <td><input name="Name" type="text"></td>
   </tr>
   <tr>
    <td><label>Is Active?</label></td>
    <td><input name="Is Active" type="checkbox" value="true"></td>
   </tr>
   <tr>
    <td><label>Disposition</label></td>
    <td>
     <select name="Disposition">
      <option> </option>
      <c:forEach var="item" items="${dispositions}">
        <option value="${item.id}">${item}</option>
      </c:forEach>
     </select>
    </td>
   </tr>

   <tr>
    <td align="center" colspan=2>
     <input type="submit" value="add.edit.button">
    </td>
   </tr>
  </table>
  <tags:hiddenOperationParam/>

 </form>
</w:populate>


See Also :
Prefer JSTL tags
A Web App Framework - WEB4J
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -