Like the options tag, the optionsCollection tag can get its label/value pairs from a collection or an object that contains a collection. In either case, the collection or the object containing a collection must be a scoped object so that it can be accessed by custom tags. Two applications, app03c and app03d, provide examples of how to use optionsCollection in the two scenarios.
The productForm action form in the app03c application has the categoryList property:
public ArrayList getCategoryList() {
ArrayList colorList = new ArrayList(3);
colorList.add(new LabelValueBean("Computer", "Com"));
colorList.add(new LabelValueBean("Camera", "Cam"));
colorList.add(new LabelValueBean("Mobile Phone", "MP"));
return colorList;
}
You can then use this to populate a select tag with the categoryList property:
<html:select property="category">
<html:optionsCollection name="productForm"
property="categoryList"/>
</html:select>
Alternatively, if the collection is in the containing object, you can remove the name property. In this case, the name attribute takes the value of the enclosing action form.
<html:select property="category"> <html:optionsCollection property="categoryList"/> </html:select>
Both will be translated into:
<select name="category"> <option value="Com">Computer</option> <option value="Cam">Camera</option> <option value="MP">Mobile Phone</option> </select>
The app03d application demonstrates how to use optionsCollection with a collection. Suppose you have the following code in an application listener that creates an ArrayList of LabelValueBean objects named productList and adds it to the ServletContext object:
ArrayList productList = new ArrayList(3);
productList.add(new LabelValueBean("Computer", "co"));
productList.add(new LabelValueBean("Television", "tv"));
productList.add(new LabelValueBean("Radio", "ra"));
servletContext.setAttribute("productList", productList);
You can then use this select tag that gets its options from the productList collection in the ServletContext object.
<html:select property="category">
<html:optionsCollection name="productList" label="label"
value="value"/>
</html:select>
Or, if you are getting the label from a property named label and the value from a property named value in the object that represents an option, you can remove the label and value attributes:
<html:select property="category"> <html:optionsCollection name="productList"/> </html:select>
In the app03d application, the select and optionsCollection tags will be rendered as:
<select name="category"> <option value="co">Computer</option> <option value="tv">Television</option> <option value="ra">Radio</option> </select>