7/15/13

Primefaces Dropdown with Pagination & Filter

Hi Folks,

I would like to share my another POC task in JSF with you all.

 "Primefaces Dropdown with Pagination & Filter "

Dropdown with Filter and Pagination which sounds like component available of the shelves but not really.  Prime-faces offers various components which are quite rich in UI and ease of use. They provide variation in Dropdown SelectOneMenu in prime-faces , one such variation is filter inside the dropdown. But they don't support pagination in that. It is also difficult to customize the dropdown by rendering a custom paginator inside it, as the entire drop down UI becomes poor. 

I tried a cross combination which will provide expected feature without using Dropdown  The main idea of dropdown  is collapsible with a list inside, so we tried Accordion Panel which offers collapsible feature and used a data-table inside that which provides paginator along with lazy-data-model. Now i have to provide a filter for searching  inside the list, so i have created a text-input component in the column header with Ajax support to update the Data-table with new set of data.  So now we have the filter and paginator for the list and since it is in accordion panel , the container is collapsible.




Important Code snippets : 

customcomponent.xhtml :

This is a simple jsf page with primefaces Datatable and acoordian panel.

<p:accordionPanel style="width: 275px !important;"  >
       <p:tab title="Select the required value"  >
            <p:dataTable style="width: 100px!important; height: 200px!important;padding-left: -50px! 
important;" lazy="true"  id="multiCars" var="fet" value="#{myDropDownBean.lazyModel}"
paginator="true" rows="10" paginatorPosition="bottom"
            selection="#{myDropDownBean.dtc}"  selectionMode="single" rowKey="#{fet.nme}"
            paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink}
{CurrentPageReport} {NextPageLink} {LastPageLink}" >
 <p:ajax event="rowSelect" listener="#{myDropDownBean.onRowSelect}">
                        </p:ajax>
                        <p:ajax event="rowUnselect" listener="#{myDropDownBean.onRowUnselect}" />
                        <p:column style="width: 100px!important;" >
                            <f:facet name="header">         
                                <p:inputText  value="#{myDropDownBean.txtSearch}">
                                    <p:ajax event="keyup" listener="#{myDropDownBean.serachMe}" update="multiCars"/>
                                </p:inputText>
                            </f:facet>
                              #{fet.name}
                        </p:column>
               </p:dataTable>
        </p:tab>
 </p:accordionPanel>

The lines below provides the header with input text and will act as a filter with ajax call.
 
  <p:column style="width: 100px!important;" >
                            <f:facet name="header">         
                                <p:inputText  value="#{myDropDownBean.txtSearch}">
                                    <p:ajax event="keyup" listener="#{myDropDownBean.serachMe}" update="multiCars"/>
                                </p:inputText>
                            </f:facet>
                              #{fet.name}
  </p:column>



MyDropDownBean.java :

This is the class which is going to provide the required feature.

The variable to store the filter value provided via TextInput.

private String txtSearch="";

    public String getTxtSearch() {
        return txtSearch;
    }

    public void setTxtSearch(String txtSearch) {
        this.txtSearch = txtSearch;
    }

Action Listner Method that will be called from Ajax event of the textinput,

public void serachMe(){

        System.out.println("this is text box value bean...."+getTxtSearch());
          lazyModel = new LazyDataModel<BeanforCheckbox>() {
                    public List<BeanforCheckbox> load(int first, int pageSize, String sortField, SortOrder
sortOrder, Map<String, String> filters) {
                List<BeanforCheckbox> lazyCars = populateLazyvalueSearch(pageSize, first,getTxtSearch()
);
                return lazyCars;
            }
        };
        lazyModel.setRowCount(cnt);
    }
}

List<BeanforCheckbox> populateLazyvalueSearch(int limit, int offset,String txt) {
        List<BeanforCheckbox> d = null;
    try {
                d = new DbClassCheck().selectRecordsSearch(limit, offset,txt);
                cnt=d.size();
        } catch (Exception e) {
            e.printStackTrace();
    }
        return d;
    }

Full Code : 
customcomponent.xhtml

<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>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form>
              <p:accordionPanel style="width: 275px !important;"  >
                <p:tab title="Select the required value"  >
            <p:dataTable style="width: 100px!important; height: 200px!important;padding-left: -50px!important;" lazy="true"  id="multiCars" var="fet" value="#{myDropDownBean.lazyModel}" paginator="true" rows="10" paginatorPosition="bottom"
                         selection="#{myDropDownBean.dtc}"  selectionMode="single" rowKey="#{fet.name}"
                                 paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}" >
                        <p:ajax event="rowSelect" listener="#{myDropDownBean.onRowSelect}">

                        </p:ajax>
                        <p:ajax event="rowUnselect" listener="#{myDropDownBean.onRowUnselect}" />
                      
                        <p:column style="width: 100px!important;" >
                            <f:facet name="header">
                               
                                <p:inputText  value="#{myDropDownBean.txtSearch}">
                                    <p:ajax event="keyup" listener="#{myDropDownBean.serachMe}" update="multiCars"/>
                                </p:inputText>

   

                            </f:facet>
                              #{fet.name}
                        </p:column>
                    </p:dataTable>
                      </p:tab>
            </p:accordionPanel>
        </h:form>
    </h:body>
</html>


MyDropDownBean.java :

package beanclass;

import java.io.IOException;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import org.primefaces.model.*;

@ManagedBean
@ViewScoped
public class MyDropDownBean implements Serializable {

    private String name;
    private BeanforCheckbox dtc;
    private List<columnModel> columns;
    private ArrayList<BeanforCheckbox> multipledtc = new ArrayList<BeanforCheckbox>();
    private String columnName;
    private boolean head = false;
    private MultiBean mb = null;
    public boolean glb = false;
private String txtSearch="";

    public String getTxtSearch() {
        return txtSearch;
    }

    public void setTxtSearch(String txtSearch) {
        this.txtSearch = txtSearch;
    }
    public boolean isHead() {
        if (glb) {
            head = mb.isChk();
        }
        System.out.println("inside ishad---");
        return head;
    }

    public void setHead(boolean head) {
        this.head = head;
    }

    public BeanforCheckbox getDtc() {
        return dtc;
    }
    private LazyDataModel<BeanforCheckbox> lazyModel;

    public void setLazyModel(LazyDataModel<BeanforCheckbox> lazyModel) {
        this.lazyModel = lazyModel;
    }

    public LazyDataModel<BeanforCheckbox> getLazyModel() {

        return lazyModel;
    }

    public void setDtc(BeanforCheckbox dtc) {
        this.dtc = dtc;
    }
    private ArrayList<DataTableClass> alist = new ArrayList<DataTableClass>();

    public ArrayList<DataTableClass> getAlist() {
        return alist;
    }

    public ArrayList<BeanforCheckbox> getMultipledtc() {
        return multipledtc;
    }

    public void setMultipledtc(ArrayList<BeanforCheckbox> multipledtc) {
        this.multipledtc = multipledtc;
    }

    @PostConstruct
    public void onload() {
        mb = new MultiBean();
        alist.add(new DataTableClass("1", "raghu", "jsf", 1));


        System.out.println("---fffff----------" + lazyModel.getRowCount());
        //createDynamicColumns();
    }

    public String getNamenew() {
        return namenew;
    }

    public void setNamenew(String namenew) {
        this.namenew = namenew;
    }
    private String namenew;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<columnModel> getColumns() {
        return columns;
    }

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public MyDropDownBean(String name) {
        this.name = name;
    }

    public MyDropDownBean() {
try{
        lazyModel = new LazyDataModel<BeanforCheckbox>() {

            /**
             * Dummy implementation of loading a certain segment of data.
             * In a real application, this method should load data from a datasource
             */
            public List<BeanforCheckbox> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
                // logger.log(Level.INFO, "Loading the lazy car data between {0} and {1}", new Object[]{first, (first+pageSize)});

                //Sorting and Filtering information are not used for demo purposes just random dummy data is returned
                //lazyModel.setRowCount(0);
                List<BeanforCheckbox> lazyCars = populateLazyvalue(pageSize, first);
                System.out.println("lazyCars-----" + lazyCars.size());
                return lazyCars;
            }
        };
        lazyModel.setRowCount(new DbClassCheck().getRecordCount());
}
catch(Exception er){
    er.printStackTrace();
}
    }

    public void onRowSelect(SelectEvent event) {
        try {
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void onRowUnselect(UnselectEvent event) {
        try {
            //   FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void view(BeanforCheckbox d) {
    
        System.out.println("d--view-->" + d.isCheck());

        boolean flag = false;
        if ((d.isCheck() == false) && (mb.isChk())) {
            multipledtc = new ArrayList<BeanforCheckbox>();
            mb.setChk(false);

            lazyModel = new LazyDataModel<BeanforCheckbox>() {

          
            public List<BeanforCheckbox> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
               
                List<BeanforCheckbox> lazyCars = populateLazyvalue(pageSize, first);
                System.out.println("lazyCars-----" + lazyCars.size());
                return lazyCars;
            }
           @Override
            public void setRowIndex(int rowIndex) {
              
               System.out.println("row index..............");
                if (rowIndex == -1 || getPageSize() == 0) {
                    super.setRowIndex(-1);
                } else {
                    super.setRowIndex(rowIndex % getPageSize());
                }
            }
            @Override
            public BeanforCheckbox getRowData(String url) {
                for (BeanforCheckbox list : lazyModel) {
                    if (url.equals(list.getName())) {
                        return list;
                    }
                }
                return null;
            }
        };
        lazyModel.setRowCount(30);

        }

        if (multipledtc.size() > 0) {
            for (int i = 0; i < multipledtc.size(); i++) {
                BeanforCheckbox d1 = multipledtc.get(i);
                if (d.getName().equalsIgnoreCase(d1.getName())) {
                    flag = false;
                    if (d1.isCheck() == false) {
                        multipledtc.remove(i);
                    }
                    break;
                } else {
                    flag = true;
                }
            }
        } else {
            flag = false;
            if (d.isCheck()) {
                multipledtc.add(d);
            }
        }
        if (flag) {
            multipledtc.add(d);
        }

    }

 

    public void redirectInput() {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("inputdisplay.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    List<BeanforCheckbox> populateLazyvalue(int limit, int offset) {
        System.out.println("inside populate--->" + limit + "--offset---->" + offset);

        List<BeanforCheckbox> d = null;
        try {
            cnt=new DbClassCheck().getRecordCount();
            System.out.println("cnt value----->"+cnt);
            d = new DbClassCheck().selectRecords(limit, offset);
            for (int i = 0; i < d.size(); i++) {
                BeanforCheckbox bc = d.get(i);
                for (int j = 0; j < multipledtc.size(); j++) {
                    System.out.println("inside j loop");
                    BeanforCheckbox bc1 = multipledtc.get(j);
                    if (bc1.getName().equalsIgnoreCase(bc.getName())) {
                        System.out.println("inside j's if-----" + bc1.isCheck());
                        d.remove(i);
                        d.add(i, bc1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return d;
    }

    public void selectAll() {

        System.out.println("inside select all updated........");
        boolean bl = true;
        if (mb.isChk()) {
            mb.setChk(false);
        } else if (mb.isChk() == false) {
            mb.setChk(true);
        }
        mb.setChk(isHead());
        glb = true;
        lazyModel = new LazyDataModel<BeanforCheckbox>() {

            /**
             * Dummy implementation of loading a certain segment of data.
             * In a real application, this method should load data from a datasource
             */
            public List<BeanforCheckbox> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
                // logger.log(Level.INFO, "Loading the lazy car data between {0} and {1}", new Object[]{first, (first+pageSize)});

                //Sorting and Filtering information are not used for demo purposes just random dummy data is returned
                //lazyModel.setRowCount(0);
                List<BeanforCheckbox> lazyCars = populateLazyvaluecheck(pageSize, first);
                // System.out.println("lazyCars-----" + lazyCars.size());
                return lazyCars;
            }
        };

        lazyModel.setRowCount(cnt);

    }

    List<BeanforCheckbox> populateLazyvaluecheck(int limit, int offset) {
        System.out.println("inside populateLazyvaluecheck--->" + limit + "--offset---->" + offset);
        System.out.println("flg value updated----->" + isHead());
        List<BeanforCheckbox> d = null;
        try {
            if (isHead()) {
                d = new DbClassCheck().selectRecordstrue(limit, offset);
                multipledtc = (ArrayList<BeanforCheckbox>) d;
            } else {
                d = new DbClassCheck().selectRecords(limit, offset);
                multipledtc = (ArrayList<BeanforCheckbox>) d;
            }
  cnt=d.size();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }
int cnt=0;
    List<BeanforCheckbox> populateLazyvalueSearch(int limit, int offset,String txt) {
        System.out.println("inside populateLazyvaluecheck--->" + limit + "--offset---->" + offset);
        System.out.println("flg value updated----->" + isHead());
        List<BeanforCheckbox> d = null;
        try {
        
                d = new DbClassCheck().selectRecordsSearch(limit, offset,txt);
        
                cnt=d.size();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }

    public void serachMe(){
        System.out.println("this is text box value bean...."+getTxtSearch());
          lazyModel = new LazyDataModel<BeanforCheckbox>() {

            /**
             * Dummy implementation of loading a certain segment of data.
             * In a real application, this method should load data from a datasource
             */
            public List<BeanforCheckbox> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
                // logger.log(Level.INFO, "Loading the lazy car data between {0} and {1}", new Object[]{first, (first+pageSize)});

                //Sorting and Filtering information are not used for demo purposes just random dummy data is returned
                //lazyModel.setRowCount(0);
                List<BeanforCheckbox> lazyCars = populateLazyvalueSearch(pageSize, first,getTxtSearch());
                // System.out.println("lazyCars-----" + lazyCars.size());
                return lazyCars;
            }
        };

        lazyModel.setRowCount(cnt);
    }
}


DbClassCheck.java : 

package beanclass;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DbClassCheck {

    List<BeanforCheckbox> selectRecords(int lim,int off) throws SQLException{
        Connection con=null;
         Statement st = null;
         ResultSet rs=null;
         List<BeanforCheckbox> d=null;
        try{
         Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testing?zeroDateTimeBehavior=convertToNull", "root", "root");
            st=con.createStatement();
            rs=st.executeQuery("select name,description,status,id from testnew limit "+lim+" offset "+off);
            d = new ArrayList<BeanforCheckbox>();
             while (rs.next()) {
            //    System.out.println("dddd");
                d.add(new BeanforCheckbox(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4),false));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
         finally{
             if(con!=null){
                 con.close();
             }
         }
         return d;
    }
    List<BeanforCheckbox> selectRecordstrue(int lim,int off) throws SQLException{
        Connection con=null;
         Statement st = null;
         ResultSet rs=null;
         List<BeanforCheckbox> d=null;
        try{
         Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testing?zeroDateTimeBehavior=convertToNull", "root", "root");
            st=con.createStatement();
            rs=st.executeQuery("select name,description,status,id from testnew limit "+lim+" offset "+off);
            d = new ArrayList<BeanforCheckbox>();
             while (rs.next()) {
             //   System.out.println("dddd");
                d.add(new BeanforCheckbox(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4),true));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
         finally{
             if(con!=null){
                 con.close();
             }
         }
         return d;
    }
     List<BeanforCheckbox> selectRecordsSearch(int lim,int off,String nam) throws SQLException{
        Connection con=null;
         Statement st = null;
         ResultSet rs=null;
         List<BeanforCheckbox> d=null;
        try{
         Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testing?zeroDateTimeBehavior=convertToNull", "root", "root");
            st=con.createStatement();
            rs=st.executeQuery("select name,description,status,id from testnew where name like '%"+nam+"%'limit "+lim+" offset "+off);
            d = new ArrayList<BeanforCheckbox>();
             while (rs.next()) {
             //   System.out.println("dddd");
                d.add(new BeanforCheckbox(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4),true));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
         finally{
             if(con!=null){
                 con.close();
             }
         }
         return d;
    }
     int getRecordCount() throws SQLException{
          Connection con=null;
         Statement st = null;
         ResultSet rs=null;
         int d=0;
        try{
         Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testing?zeroDateTimeBehavior=convertToNull", "root", "root");
            st=con.createStatement();
            rs=st.executeQuery("select count(*) from testnew");

             if (rs.next()) {
             //   System.out.println("dddd");
                d=rs.getInt(1);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
         finally{
             if(con!=null){
                 con.close();
             }
         }
         return d;
     }
   
}

BeanforCheckbox.java :

package beanclass;

import java.io.Serializable;

public class BeanforCheckbox implements Serializable {

    private String name;
    private String roll;
    private String gender;
    private int id;
    private boolean check = false;

    public int getId() {
        return id;
    }

    public boolean isCheck() {
        return check;
    }

    public void setCheck(boolean check) {
        this.check = check;
    }

    public void setId(int id) {
        this.id = id;
    }

    public BeanforCheckbox(String name, String roll, String gender, int id, boolean check) {
        this.name = name;
        this.roll = roll;
        this.gender = gender;
        this.id = id;
        this.check = check;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRoll() {
        return roll;
    }

    public void setRoll(String roll) {
        this.roll = roll;
    }
}
 
Try it and let me know. This is not robust as it just a POC.

No comments:

Post a Comment

Popular Posts