octopish
octopish

Reputation: 59

Saving data from multiple inputtext boxes created by a loop in jsf

Basically, I have an input text box that I want to submit for each item in the array. The code below is cut down to the relevant portions

<c:forEach items="${mybean.mats}" var="mat">
        <p:dataTable var="datarow" value="#{mybean.getDatarows(mat.itemId)}" rowIndexVar="row">
            <p:column>
                <p:inputText value="#{bean.amt}" />
            </p:column>
        </p:dataTable>
    </p:panel>

    <p:commandButton value="Confirm" action="#{mybean.runSubmit}" process="@this" />
</c:forEach>

From what I know, each individual item needs to have its own variable name to save the data in each input text box. I know the method I'm currently using is wrong, so is there another way to save all the data? Perhaps in an array or something?

Upvotes: 1

Views: 1749

Answers (1)

codeturner
codeturner

Reputation: 1053

First, mixing the JSTL c:foreach with a datatable is not recommended. Use ui:repeat instead.

Second, your p:dataTable value has to reference a collection that exists during the lifetime of the backing bean. It looks to me like the call to #{mybean.getDatarows(mat.itemId)} generates a list of items dynamically. That's going to be a problem since your backing bean will need to call the getDatarows when the values are re-applied to the bean on your ajax call runSubmit to save the values. In this case, you will need to save the dynamically created list to the backing bean so that the same collection will match up exactly to the collection used to produce the html.

For example, suppose your backing bean contains the property List<List<Mat>> mats, where the Mat class contains a single property 'dataId'. Then, your EL could be:

<h:form id="input-form">
 <ui:repeat id="mats-repeat" value="#{mats}" var="mat">
  <p:dataTable id="mat-table" value="#{mat}" var="dataObj">
   <p:column>
    <p:inputText id="dataId" value="#{dataObj.dataId}" />
   </p:column>
  </p:dataTable>
 </ui:repeat>
</h:form>

Since the form, repeat, and dataTable components are naming containers, they ensure that any child components are named uniquely. In this case, the first input mat element would be rendered as:

<input id="input-form:mats-repeat:0:mat-table:0:dataId" ...

Upvotes: 1

Related Questions