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!!

37 comments:

  1. why there is a delete button for each row?
    not possible to use just one ?

    ReplyDelete
    Replies
    1. Yes, both Add and Delete button can be shared by all rows in the datatable.
      It is just for easy demo purpose.
      To use only one Add/Delete button in the datatable, it is an additional step to capture the current row index to be deleted.

      Delete
  2. Hi Kiran,thank you very much for the nice post, how can i add new row in the datatable using primefaces, when the Add button pressed a new empty editable row should be displayed in which user can enter the data.Please help me i am really struck with this.

    ReplyDelete
    Replies
    1. Hi Anasuya,

      with the above sample code, simply change the and tag to and .
      it should works, unless your dataTable value is a datamodel, then I think the implementation is slightly different.

      Delete
    2. is
      <p:dataTable /> and <p:column />

      Delete
    3. Hi kian,thanks for the reply.Yes i am using dataModel to populate data into data table.someone suggested me that i can create a empty list and when the add button is clicked i can show a empty row from the list and when user enters data and click save then i can save the data into database table.could you please let me know how to implement this..
      Thank you.

      Delete
    4. Hi Anasuya,
      If use List as the value holder, the implementation should be same as my sample code.
      The only missing thing is you need a save action to get the list from datatable then pass it to your DAO to save.

      To save the list into database, you need a button to invoke the "save" action in managed bean.
      public void save() {
      dao.save(carList);
      }

      And I tested, the add new row action in the sample code above is applicable to dataModel as well because dataModel required a List as value holder.

      Delete
  3. So I want to delete multiple selection(checkbox) and delete one button this rows How can I do?
    Thanks...

    ReplyDelete
    Replies
    1. It depends on what JSF implementation you are using.
      It would be slightly difference on how datatable capturing the selection.
      generally, It should be a selection list in your backing bean.
      just get the selection list in the delete method, and execute delete action.

      public void deleteMultiple {
      for(Object selectedObject : selectionList) {
      carList.remove(selectedObject);
      }
      }

      Delete
  4. Hi Kian,

    I am unable to create an empty row in the data table when it is loaded . In your code you are populating the table initially by creating 2 car objects.In my code I have created new car object in the constructor but datatable is not created with one empty row.please suggest

    ReplyDelete
    Replies
    1. Hi Kavitha,

      I guess your list is not initialized.
      if this is not the root cause, could you please post some code here.

      Delete
  5. package com.chip.bean;

    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;

    import javax.faces.application.FacesMessage;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.faces.context.FacesContext;
    import javax.faces.event.ActionEvent;

    import org.primefaces.event.CellEditEvent;
    import org.primefaces.event.SelectEvent;


    import com.chip.bean.Chip;


    @ManagedBean
    @SessionScoped
    public class ChipBean implements Serializable {



    //private List chipList;


    private String chipSetNumber;
    private String description;

    private List chipBom;

    public String getChipSetNumber() {
    return chipSetNumber;
    }




    public void setChipSetNumber(String chipSetNumber) {
    this.chipSetNumber = chipSetNumber;
    }




    public String getDescription() {
    return description;
    }




    public void setDescription(String description) {
    this.description = description;
    }





    public ChipBean() {

    chipBom=new ArrayList ();
    //chipList=new ArrayList();

    populateChip(chipBom);
    }

    public List getChipBom() {
    return chipBom;
    }


    public void setChipBom(List chipBom) {
    this.chipBom = chipBom;
    }




    public void addChipBom()
    {
    ChipBomBean bomBean=new ChipBomBean();


    chipBom.add(bomBean);

    }


    public void removeChipBom(ChipBomBean b)
    {


    if(chipBom.size()>1)
    chipBom.remove(b);

    }

    public void populateChip(List list) {
    ChipBomBean b1=new ChipBomBean();
    b1.setCorePart("a");
    b1.setIpart("c");
    b1.setPackaging("d");
    b1.setQuantity("e");
    b1.setAllocation("f");

    list.add(b1);
    }




    }

    ReplyDelete
    Replies
    1. I din't see any problem in your code.
      Then I try to execute the above code.
      and I managed to populate initial value in the datatable and also add new row in the datatable as well

      Delete
  6. In populateChip method I am creating ChipBomBean instance ,cant I create empty row without that, I mean with creating instance.

    ReplyDelete
    Replies
    1. I commented the populateChip in the constructor, it is working fine
      public ChipBean() {
      chipBom=new ArrayList ();
      //chipList=new ArrayList();
      //populateChip(chipBom);
      }

      Delete
  7. thanks...can you please let me know how to check atleast a row exists with the data in the data table

    ReplyDelete
    Replies
    1. below are my code in xhtml, and i used ChipBean as my managedBean.

      <p:dataTable

          id="table02"

          value="#{chipBean.chipBom}"

          var="chip" >

          <p:column>

              <f:facet name="header"><h:outputText value="core part" /> </f:facet>

              <h:inputText value="#{chip.corePart}" />

          </p:column>

          <p:column>

              <f:facet name="header"><h:outputText value="i part" /> </f:facet>

              <h:inputText value="#{chip.ipart}" />

          </p:column>

      </p:dataTable>

      <p:commandButton action="#{chipBean.addChipBom}" value="Add" update=":form:panel" />

      Delete
  8. hi kian,

    How to add a row with radio button dynamically in datatable of jsf

    ReplyDelete
  9. hi kian,

    How to add or remove a row with radio button dynamically in datatable of jsf

    ReplyDelete
    Replies
    1. Hi Kavitha,

      would like to know what is your JSF implementation, because it would be different on how to get the selected record.

      Delete
  10. Hi Kian,

    Initally the datatable will be empty with one row which also has radio button as one of the column selected by

    defalut and add/remove button next to every row in the data table.

    when I click the add button new row will be added along with the radio button.

    .Unable to use group by with in the column of data table.

    I have tested by using , but all radio buttons are selected.

    How to select only one radio button in the data table.

    help needed asap.

    ReplyDelete
    Replies
    1. Hi,
      Actually I'm asking what JST u r using. Eg, myfaces, richfaces.
      I guess u r using myfaces?
      I will try to figure out a solution for u.

      Delete
  11. Replies
    1. Hi Kavitha,
      If you are using PF, i think the selection could be easily get from the radio selection as shown in PF showcase
      http://www.primefaces.org/showcase/ui/datatableRowSelectionRadioCheckbox.jsf.
      just curious why you need to code the radio button manually.

      Delete
  12. Hi Kian,
    I am aware of this example,but here we need to implement datamodel inorder to use single selection,what my

    doubt is that is there any other way to select a single radio button without using data model.

    users req is that whatever row is selected by the user that particular row has to be used for business logic.

    ReplyDelete
    Replies
    1. Hi Kavitha,
      without datamodel still can add selection.
      just need to add selection and rowKey attribute

      <p:dataTable

          id="table01"

          value="#{datatableBean.carList}"

          var="car"

          selection="#{datatableBean.selectedCar}"

          rowKey="#{car}">

      </p:dataTable>

      Delete
  13. Hi Kian,
    Thanks for the reply

    tried with rowkey and working fine.The problem I am having is that first selected radio button in the datatable is
    getting cleared after clicking add row button.

    I am setting the first radio button in the datable it is getting selected but after adding the new row to the datable the

    first row selected radio button is getting cleared.

    please let me know how can I resolve this problem.

    Can you please reply asap.

    ReplyDelete
    Replies
    1. Hi,
      Mine is working fine and the selected record is not cleared.
      can you share your "Add" button code here.

      Delete
  14. In the constructor I am creating empty row added to the table and after that I am setting setSelectCorePart

    (chipCreationBean.getChipBom().get(0));, where it sets the radio button for the first row . but after adding new row

    or after I search for the data in the first column , first row the radio button selection is getting cleared


    //
    public String addChipBom(){



    this.chipCreationBean.getChipBom().add(new ChipBomBean());


    return "";
    }

    ///



















    ReplyDelete
  15. This comment has been removed by a blog administrator.

    ReplyDelete
  16. This comment has been removed by a blog administrator.

    ReplyDelete
  17. please let me know where can I send my html code as it is not allowing me to paste

    ReplyDelete
  18. Hi Kian,

    I have sent mail with code to your gmail.
    Please let me know , I got stuck and cant proceed further.

    ReplyDelete
  19. Hi Kian,

    I have sent mail with html code

    can you please look and let me know

    Regards
    Kavitha

    ReplyDelete
  20. Hi Kian,

    Can you share your code that has worked for you.

    Regards
    Kavitha

    ReplyDelete

LinkWithin

Related Posts Plugin for WordPress, Blogger...