PrimeFaces 3.4.1 chain combo population from db

Controlling Two or more SelectOneMenu is a well known issue for the programmer. This differ from framework to framework or even from version to version. This example is done using PrimeFaces 3.4.1. In this example both of the SelectOneMenu populate data from MySQL db, the second one will populate based on the selection of first one. Hope you find this useful.

1. chaincombo.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
    <h:head>
        <title>Chain combo</title>
    </h:head>
    <h:body>
        <h:form id="form1">
            <p:panel header="Chain Combo Example" style="width: 500px;">
                <h:panelGrid columns="2">  
                    <h:outputText value="Select Category: " />  
                    <p:selectOneMenu value="#{category.catname}" id="cat" valueChangeListener="#{category.processScat}">  
                        <f:selectItem itemLabel="Select Category" itemValue="" />
                        <f:selectItems value="#{category.categoryName}"/> 
                        <p:ajax update="scat" event="change" />
                    </p:selectOneMenu>
                    <h:outputText value="Select Sub-Category: " />  
                    <p:selectOneMenu value="#{category.subcatname}" id="scat"> 
                        <f:selectItem itemLabel="Select Sub-Category" itemValue="" />
                        <f:selectItems value="#{category.subCategoryName}"/>
                    </p:selectOneMenu>
                </h:panelGrid>                
            </p:panel>
        </h:form>
    </h:body>
</html>

2. Category.java

package beans;

import java.sql.*;
import dao.Database;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;

@ManagedBean(name = "category")
@SessionScoped
public class Category implements Serializable {

    private static final long serialVersionUID = 1L;
    private String catname, subcatname;

    public String getCatname() {
        return catname;
    }

    public void setCatname(String catname) {
        this.catname = catname;
    }

    public String getSubcatname() {
        return subcatname;
    }

    public void setSubcatname(String subcatname) {
        this.subcatname = subcatname;
    }

    public List<SelectItem> getCategoryName() {
        List<SelectItem> cat = new ArrayList<SelectItem>();
        try {
            Connection con = Database.getConnection();
            Statement st = con.createStatement();
            ResultSet rs = null;
            String myQuery = "select items_name from items";

            rs = st.executeQuery(myQuery);
            while (rs.next()) {
                cat.add(new SelectItem(rs.getString("items_name")));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return cat;
    }

    @SuppressWarnings("unchecked")
    public List<SelectItem> getSubCategoryName() {
        List<SelectItem> subcat = new ArrayList<SelectItem>();
        //if (catname != null && !catname.equals("")) {            
        try {
            Connection con = Database.getConnection();
            Statement st = con.createStatement();
            ResultSet rs = null;
            String myQuery = "select sub_items_name from sub_items where items_id=(select items_id from items where items_name='" + catname + "')";
            //System.out.println(myQuery);
            rs = st.executeQuery(myQuery);
            while (rs.next()) {
                subcat.add(new SelectItem(rs.getString("sub_items_name")));
            }

        } catch (Exception ex) {
        }
        // }
        return subcat;
    }

    public void processScat() {
        getSubCategoryName();
    }
}

Output:
Populate second combo upon selecting first combo
Ref:
1. http://www.primefaces.org/showcase-labs/ui/pprSelect.jsf

2. http://stackoverflow.com/questions/6435467/trouble-with-primefaces-3-0-m2-selectonemenu-ajax-behavior

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

24,667` Total Views

4 comments

  • This can also be done without using any listener or valueChangeListener.

    <h:outputText value="Select Category: " />  
    <p:selectOneMenu value="#{category.catname}" id="cat">  
           <f:selectItem itemLabel="Select Category" itemValue="" />
           <f:selectItems value="#{category.categoryName}"/> 
           <p:ajax update="scat" />
    </p:selectOneMenu>
    <h:outputText value="Select Sub-Category: " />  
    <p:selectOneMenu value="#{category.subcatname}" id="scat"> 
            <f:selectItem itemLabel="Select Sub-Category" itemValue="" />
            <f:selectItems value="#{category.subCategoryName}"/>
    </p:selectOneMenu>
    
  • Lebron 9 South Beach

    Thanks a lot for the blog post.Really thank you! Keep writing.thank-ok-it

  • Thank You So Much !!!

  • Amazing tutorial, only remember close DB’s conections :
    try {
    stmt = con.createStatement();
    rset = stmt.executeQuery(MYQUERY);

    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    try {
    rset.close();
    stmt.close();
    con.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

    Greats!!!

Leave a Reply

Your email address will not be published. Required fields are marked *


three − = 2