Hobione's Weblog

Living & Breathing in Web 2.0 Era

JSF: f:selectItem vs. javax.faces.model.SelectItem

Let me explain what works and then I will tell you what not works. ListModel has a list type of javax.faces.model.SelectItem:


public class TrainingSessionsListModel extends ListModel{

 private List<SelectItem> availableSlotSelectItems;

 public List<SelectItem> getSessionNumberSelectItems() {

 if (this.sessionNumberSelectItems == null){
    sessionNumberSelectItems = new ArrayList();
    for(int i = 100; i < 1000; i++){
       SelectItem selectItem = new SelectItem(i,Integer.toString(i));
       sessionNumberSelectItems.add(selectItem);
    }
 }
 return sessionNumberSelectItems;
 }
 }

&#91;/sourcecode&#93;
<p style="margin-bottom:12pt;">xhtml now referring to the above list model class to get the list and set the value to TrainingSessionsDTO.sessionNumber property:</p>


<td>
 <ice:selectOneMenu id="sessionNumber" partialSubmit="true" value="#{
trainingSessionsListModel.TrainingSessionsDTO.sessionNumber}" required="true">

<f:selectItem itemLabel="#{msgs.select}" itemValue="" />
 <f:selectItems value="#{trainingSessionsListModel.sessionNumberSelectItems}"/>

 </ice:selectOneMenu></td>

Here is the transfer object with getter and setter.

 public class TrainingSessionsDTO extends TransferSupport implements Transfer,
 Serializable {

 String sessionNumber;

 //getter and setter .......

 }

sessionNumber

The above works fine, no problem but if I change the xhtml to these it wont work.

<ice:selectOneMenu id="sessionNumber" partialSubmit="true" value="#{
trainingSessionsListModel.TrainingSessionsDTO.sessionNumber}" required="true">
 <f:selectItem itemLabel="#{msgs.select}" itemValue="" />

 <f:selectItem itemLabel="100" value="100" />
 <f:selectItem itemLabel="200" value="200" />
 <f:selectItem itemLabel="300" value="300" />
 </ice:selectOneMenu></td>

Exception:
java.lang.String cannot be cast to javax.faces.model.SelectItem

Solution:

<f:selectItem itemLabel="100" itemValue="100" />
<f:selectItem itemLabel="200" itemValue="200" />
<f:selectItem itemLabel="300" itemValue="300" />

The value is meant to send in a SelectItem object and not a String. This should eliminate the exception you are seeing. Here is my beautiful finished work (form and datatable):
trainingsessionform

May 1, 2009 - Posted by | Java Server Faces

4 Comments »

  1. Great example. Thanks for posting.

    Phil

    Comment by Phil | July 30, 2009 | Reply

  2. […] JSF: f:selectItem vs. javax.faces.model.SelectItem May 2009 1 comment […]

    Pingback by 2010 in blog review « Hobione's Weblog | January 7, 2011 | Reply

  3. thank you…………….!

    Comment by pradip garala | April 19, 2011 | Reply

  4. In slide 42nd there is an simple example about SelectItem.

    And thanks for your example, too.

    Comment by John Ortiz | July 6, 2012 | Reply


Leave a comment