20 December 2008

How to populate a select box (drop down) in Seam with values in List

This post is using Seam 2.1.1. Seam alleviates the pain to deal with UISelect and in the example below, we display a list of exams and the user selects an exam.

The code shown below is part of  the Seam backing bean with the name examscheduler. It retrieves list of exams and populates in examsToSelect List. Also please note that I have omitted the getter setter for private Exam exam here.

    @Out(required=false)
    List<Exam> examsToSelect;

    @Factory("examsToSelect")
    public void populateValues(){
        examsToSelect=em.createNamedQuery("Exam.findAll").getResultList();
    }
   private Exam exam;

Now the UI part,
<h:selectOneMenu id="exam" value="#{examscheduler.exam}">
 <s:selectItems value="#{examsToSelect}" var="exam" label="#{exam}"
           noSelectionLabel="select..." />
     <s:convertEntity />
</h:selectOneMenu>

And finally the configuration in component.xml
<ui:jpa-entity-loader entity-manager="#{em}" />
and the xmlns at the top as an attribute of components (if we have not specified one already for ui)
xmlns:ui="http://jboss.com/products/seam/ui"


Note: I had overridden the default name entityManager