The Java EE 6 Tutorial, Volume I

Properties for SelectItems Composed of SelectItem Instances

You can populate the SelectItems with SelectItem instances programmatically in the backing bean.

  1. In your backing bean, create a list that is bound to the SelectItem component.

  2. Then define a set of SelectItem objects, set their values, and populate the list with the SelectItem objects.

Here is an example code snippet from a backing bean that shows how to create a SelectItems property:

import javax.faces.component.SelectItem;
...
protected ArrayList options = null;
protected SelectItem newsletter0 =
     new SelectItem("200", "Duke’s Quarterly", "");
...
//in constructor, populate the list
options.add(newsletter0);
options.add(newsletter1);
options.add(newsletter2);
...
public SelectItem getNewsletter0(){
    return newsletter0;
}

void setNewsletter0(SelectItem firstNL) {
    newsletter0 = firstNL;
}
// Other SelectItem properties

public Collection[] getOptions(){
    return options;
}
public void setOptions(Collection[] options){
    this.options = new ArrayList(options);
}

The code first initializes options as a list. Each newsletter property is defined with values. Then, each newsletter SelectItem is added to the list. Finally, the code includes the obligatory setOptions and getOptions accessor methods.