Monday 30 September 2013

Using selectOneMenu in Primefaces

Question:
I had two tables. Staff and Department. Staff is related to Department by manyToOne respectively. On the Staff form, I have a dropdown(selectOneMenu) which has all the departments. For each shown department I want to get the primary key which I can Insert into the Staff table as the foreign key.
So I had two things to cater for here. First, displaying the list of Departments in the drop down, Second, Obtaining the primary key of the selected department for the purposes of Staff-department Forein key.

Response.
After days of hutsle in trying to use selectOneMenu, today i finally get it. I tried a number of things but this is what finally worked.



The first argument will be the value, and the second will be the displayed label
 Step 1: selectOneMenu in primeFaces page.
<p:selectOneMenu value="#{staffBacking.deptId}">
       <f:selectItem itemValue="#{null}" itemLabel="Select">
        <f:selectItems value="#{staffBacking.selectItems}" >
</p:selectOneMenu>

Step 2: The backing bean for the page contained this method
//Static data
public List<SelectItem> getSelectItems() {
        selectItems.add(new SelectItem(1, "Development"));
        selectItems.add(new SelectItem(2, "Administrative"));
        return selectItems;
    }

//data From database
public List<SelectItem> getSelectItems() {
        for(int i = 0; i < getDf().findAll().size(); i++){
            selectItems.add(new SelectItem(getDf().findAll().get(i).getDeptId(), getDf().findAll().get(i).getDeptName()));
        }
        return selectItems;
    }


The was also a setter and a getter for deptId i.e. getDeptId(), setDeptId(String departmentId). This will hold the value from the value attribute of selectOneMenu

Step 3:  Set the department id value to the current object of Department and then add the staff. Below is the method that persists the staff.

public void addStaff(){
        getDept().setDeptId(Integer.parseInt(getDeptname()));
        getStaff().setDepartmentdeptId(dept);
        getSf().create(staff);
    }

No comments:

Post a Comment