In this example, we will learn how to use PickList of PrimeFaces. PickList is used for transferring data between two different collections.
JSF page
src/main/webapp/index.xhtml<h:body style="margin-left:50px">
<h2>PrimeFaces PickList Example</h2>
<h:form>
<p:pickList value="#{pickListBean.listModel}"
var="emp"
itemLabel="#{emp.name} (#{emp.dept})"
itemValue="#{emp}"
converter="empConverter"/>
<p:commandButton value="Submit"
update="display" />
<h:panelGrid id="display" columns="1">
<h3>Employees source list:</h3>
<ui:repeat value="#{pickListBean.listModel.source}" var="emp">
<h:outputText value="#{emp.name} (#{emp.dept})"/>
<br/>
</ui:repeat>
<h3>Employees target list:</h3>
<ui:repeat value="#{pickListBean.listModel.target}" var="emp">
<h:outputText value="#{emp.name} (#{emp.dept})"/>
<br/>
</ui:repeat>
</h:panelGrid>
</h:form>
</h:body>
The manage bean
@ManagedBean
@RequestScoped
public class PickListBean {
private DualListModel<Employee> listModel;
@PostConstruct
public void init() {
//initial unselected list
List<Employee> sourceList = Arrays.asList(
new Employee("1", "Jim", "IT"),
new Employee("2", "Sara", "Sale"),
new Employee("3", "Tom", "Admin"),
new Employee("4", "Diana", "IT")
);
//initial selected list
List<Employee> destinationList = new ArrayList<>();
destinationList.add(new Employee("5", "Jessica", "Sale"));
listModel = new DualListModel<>(new ArrayList<>(sourceList), destinationList);
}
public DualListModel<Employee> getListModel() {
return listModel;
}
public void setListModel(DualListModel<Employee> listModel) {
this.listModel = listModel;
}
}
public class Employee {
private String id;
private String name;
private String dept;
.............
}
@FacesConverter(value = "empConverter")
public class PickListEmpConverter implements Converter {
@Override
public Object getAsObject(FacesContext fc, UIComponent comp, String value) {
DualListModel<Employee> model = (DualListModel<Employee>) ((PickList) comp).getValue();
for (Employee employee : model.getSource()) {
if (employee.getId().equals(value)) {
return employee;
}
}
for (Employee employee : model.getTarget()) {
if (employee.getId().equals(value)) {
return employee;
}
}
return null;
}
@Override
public String getAsString(FacesContext fc, UIComponent comp, Object value) {
return ((Employee) value).getId();
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
Example ProjectDependencies and Technologies Used: - primefaces 6.1 primefaces
- jsf-api 2.2.14:
This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
- jsf-impl 2.2.14:
This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
- jstl 1.2 javax.servlet:jstl
- JDK 1.8
- Maven 3.3.9
|