Sunday, March 24, 2013

How to add/remove row in datatable

JSF Datatable is a data driven component, total number of table row depends on number of records in datamodel that is binding to the datatable.

Thus, to add/remove a row in datatable is actually an action to add/remove record in the datamodel.

Steps:
1. Prepare the value object / entity.
Value Object or Entity for datatable

2. create SessionScope managedBean
Create SessionScope managedBean

3. create the value holder for datatable in the managedBean.
datatable's value holder

4. prepare the data to display in datatable. In runtime, data could be loaded from database.
Preparing sample data

5. create the actions to add and remove record.
 Add action and Remove Action

6. invoke the actions in XHTML.
<h:panelGroup id="panel">
    <h:dataTable
        id="table01"
 value="#{datatableBean.carList}"
 var="car" >
 <h:column>
     <f:facet name="header">Brand</f:facet>
     <h:inputText value="#{car.brand}" />
        </h:column>
 <h:column>
     <f:facet name="header">Model</f:facet>
     <h:inputText value="#{car.model}" />
 </h:column>
 <h:column>
     <f:facet name="header">Action</f:facet>
     <h:commandButton value="Add" 
                action="#{datatableBean.addCar}">
         <f:ajax execute=":form:panel" render=":form:panel" />
     </h:commandButton>
     <h:commandButton value="Delete" 
action="#{datatableBean.removeCar(car)}" >
         <f:ajax execute=":form:panel" render=":form:panel" />
     </h:commandButton>
 </h:column>
    </h:dataTable>
</h:panelGroup>bbb

7. same concept could be apply to other JSF implementations, eg, Primefaces, Richfaces.

Output:
Output of Add/Remove row datatable

Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...