Reputation: 8334
I'm using JSF 2.0 I have a problem to set Values of inputTexts to a table of double.
I can do this :
<h:inputText value="#{myBean.table[0]}" />
But, I would like to do it in a loop like that:
<c:forEach var="i" begin="0" end="#{myBean.inputsNumber}">
<h:inputText value="#{myBean.table[i]}" /> <br/>
</c:forEach>
<h:commandButton action="#{myBean.calculate}" value="Calculate" />
Result: #{myBean.result}
Here is my backing bean :
@ManagedBean
@SessionScoped
public class MyBean {
private double[] table;
private double result;
public MyBean() {
table = new double[100];
}
public void calculate() {
for (int i = 0; i < table.length; i++) {
result += table[i];
}
}
public double[] getTable() {
return table;
}
public int getInputsNumber() {
return table.length;
}
public double getResult() {
return result;
}
}
I tried to bind all components to an array of HtmlInputText
, but I could not solve it.
i got this exception : ClassCastException
Upvotes: 1
Views: 2906
Reputation: 1108722
There are 2 problems:
The <c:forEach end>
is inclusive. You need to take 1 off from it, otherwise you end up with ArrayIndexOutOfBoundsException
when submitting.
<c:forEach var="i" begin="0" end="#{myBean.inputsNumber - 1}">
A better approach is however to just iterate over the array itself and get the index by varStatus
.
<c:forEach items="#{myBean.table}" varStatus="loop">
<h:inputText value="#{myBean.table[loop.index]}" />
</c:forEach>
A double in EL is treated as Double
, not as double
. So you need Double[]
instead of double[]
, otherwise you end up with ClassCastException
when submitting.
private Double[] table;
Upvotes: 3