06 June 2009

Populate and validate JSF selectOneMenu

Using a backing bean or Seam component (on JBoss), you can easily populate a JSF selectOneMenu (JSF dropdown box server-side control):

<h:selectonemenu id="lstRating" value="#{asset.rating}" required="true" requiredMessage="Rating is required.">
<f:selectitems value="#{asset.ratingItems}" />
<rich:message for="lstRating" styleclass="errors" />

In this example, you have a selectOneMenu with id of lstRating. It gets its SelectItem elements from the asset.ratingItems property on the backing component. The selected item is stored in asset.rating.

  private String rating;
private ArrayList<SelectItem> ratingItems = null;

public ArrayList<SelectItem> getRatingItems(){
ratingItems = new ArrayList<SelectItem>();
ratingItems.add(new SelectItem(null,"Select One..."));
ratingItems.add(new SelectItem("TV-Y", "TV-Y"));
ratingItems.add(new SelectItem("TV-Y7", "TV-Y7"));
ratingItems.add(new SelectItem("TV-G", "TV-G"));
ratingItems.add(new SelectItem("TV-PG", "TV-PG"));
ratingItems.add(new SelectItem("TV-14", "TV-14"));
ratingItems.add(new SelectItem("TV-MA", "TV-MA"));

return ratingItems;

public String getRating(){
return this.rating;

public void setRating(String rating){
this.rating = rating;

In the above code, we declare an ArrayList of SelectItem object type. The getRatingItems() property instantiates the ratingItems ArrayList and populates it with SelectItem objects. Note the first SelectItem has a null value; if the user leaves the dropdown box to this item, the required validator will detect it as a blank value and throw a validation error.


Anonymous said...

Nice, it helped me

Anonymous said...

thanks! btw, I got an error when writing 'requiredmessage' instead of 'requiredMessage'

Alex C said...

Glad it helped. I've changed the spelling of "requiredmessage" to "requiredMessage" to ensure no one runs into issues. By the way, do you remember what the error said?

Anonymous said...

new SelectItem(null,"Select One...") throws a NPE in my case. I think the workaround is new SelectItem("","Select One...")

Anonymous said...

you have to change this ratingItems.add(new SelectItem(null,"Select One..."));
ratingItems.add(new SelectItem("Select One...",null));

and add rerender message for display it so add

Anonymous said...

ah you have to render you message Id not you slect ID sorry