10
votes

I need to add a row to my datatable on click of a button - "Add Employee".

The datatable shows the records corresponding to a fixed list of Employees in the bean.

What I am doing is, on click of the "Add Employee" button , I am adding an empty record of Employee to the empList.

Is there any better way to do this?

Thanks.

3
On click of the "Add Employee" button, accept the input from the user in various fields. On submit, add the details to the list in the bean and do ajax update on datatable. Datatable will be refreshed as per the employee list in the bean. - rags
@rags is it possible without refreshing the datatable? - Shikha Dhawan
ajax update is required as the new details are added to the list and available in the bean - rags

3 Answers

4
votes

Either you open a dialog or a popup when clicking the add button. Then fill in the required fields (attached to a employee object. And when saving/submit you add that object to your list of employee objects. And rerender the datatable. Or you can initially add an empty emploee object to your list. Showing it in the datatable with inputfields. On add, you add the new employee to the list and rerender the list.

4
votes

list_Recs is list of records and shown in the data table.

<p:dataTable id="myTable" value="#{myBean.list_Recs}" selectionMode="single" var="myTableVar" selection="#{myBean.currentRec}">
    <p:ajax event="rowSelect" listener="#{myBean.handleRowSelect}" update=":myForm:myPanel"/>
    <p:column>
        <f:facet name="header">
            <h:outputLabel value="Field 1" />
        </f:facet>
        <h:outputLabel value="#{myTableVar.Field1}"/>
     </p:column>

     <p:column>
         <f:facet name="header">
             <h:outputLabel value="Field 2" />
         </f:facet>
         <h:outputLabel value="#{myTableVar.Field2}" />
     </p:column>

     <f:facet name="footer">
         <p:commandButton value="New" action="#{myBean.prepareForInsert}" update=":myForm:myPanel"/>
     </f:facet>
</p:dataTable>

<h:panelGrid id="myPanel" columns="2" >
    <h:outputLabel value="Field 1"/>
    <p:inputText id="fld1" value="#{myBean.newRec.field1}" />
    <h:outputLabel value="Field 2"/>
    <p:inputText id="fld2" value="#{myBean.newRec.field2}" />
    <p:commandButton action="#{myBean.createAction}" value="Submit" update="myGrowl myTable" />
</h:panelGrid>

When New button is clicked, create an emty instance of newRec in prepareForInsert routine of myBean. So that myPanel is filled with blanks in the fields. On Submit, add the newRec to list_Recs and the new record is diplayed in the data table because of the update on myTable. Hope this helps.

3
votes

A different option would be to show an empty employee in the footer facet of your datatable and add it to your list if the user clicks the add button. With this you can ensure that only correctly filled employee objects/entities are added to your list.