Monday, March 5, 2012

prime faces dynamic data table columns jsf


Step 1. Create a class item

public class Item {
 
  private String value;

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }
 
}

Step 2. Create Managed Bean


@ManagedBean(name = "contentController")
@SessionScoped
public class ContentController {

  private List<item[]> contentList = new ArrayList<item[]>();
  private List<string> columnNames = new ArrayList<string>();

  public ContentController() {
  
  
    columnNames.add("Name");
    columnNames.add("Age");
  
    Item[] child = new Item[columnNames.size()];
    Item item = new Item();
    item.setValue("Alanis");
    child[0]= item; //First Row first column
  
    item = new Item();
    item.setValue("36");
    child[1]= item; //First Row second column
  
    contentList.add(child); //Adding first row
  
    child = new Item[columnNames.size()];
    item = new Item();
    item.setValue("Sachin");
    child[0]= item; //Second Row first column
  
    item = new Item();
    item.setValue("39");
    child[1]= item; //Second Row second column
  
    contentList.add(child); //Adding second row

  }
 

  public List<string> getColumnNames() {
    return columnNames;
  }

  public void setColumnNames(List<string> columnNames) {
    this.columnNames = columnNames;
  }

  public List<item[]> getContentList() {
    return contentList;
  }

  public void setContentList(List<item[]> contentList) {
    this.contentList = contentList;
  }
}



3. Create the jsf view



<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:p="http://primefaces.org/ui"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
  <body>
        <h:form id="form1"  >

          <p:dataTable id="dataTableContent" var="list" value="#{contentController.contentList}" rowIndexVar="rowIndex">                    
            <p:columns value="#{contentController.columnNames}" columnIndexVar="colIndex" var="item" >
              <f:facet name="header">
                <h:outputText value="#{item}"/>
              </f:facet>
              <h:outputText value="#{list[colIndex].value}"/>
            </p:columns>
          </p:dataTable>
        </h:form>

  </body>
</html>

No comments:

Post a Comment