1

What am I not doing right?

@Named("utilityController")
@RequestScoped
public class UtilityController {
    public DataModel<Result> getResultSample() {
        Result[] resultSample = new Result[11];
        //Populate the array
        return new ArrayDataModel<>(resultSample);
    }
}

In The JSF:

<h:dataTable id="sampleResult" value="#{utilityController.resultSample}" var="item" styleClass="table table-bordered table-striped table-hover table-condensed" >
    <h:column>
        <f:facet name="header">SN</f:facet>
        #{utilityController.resultSample.rowIndex}
    </h:column>
    <h:column>
        <f:facet name="header">Subject</f:facet>
        #{item.subject.name}
    </h:column>
    ....
</h:dataTable>

enter image description here

The rowIndex always returns 0 as can be seen above. Please can some help me pin point what I am doing wrongly

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Paullo
  • 2,038
  • 4
  • 25
  • 50

1 Answers1

3

What am I not doing right?

Creating the model in a getter method. Never do that. All getter methods should look like this:

public DataModel<Result> getResultSample() {
    return resultSample;
}

The getter method is invoked on every iteration round. You're basically clearing out the model from the previous iteration round and returning a brand new one, with all state (such as current row index) reset to default value.

Move that job to bean's @PostConstruct method.

private DataModel<Result> resultSample;

@PostConstruct
public void init() {
    Result[] results = new Result[11];
    // ...
    resultSample = new ArrayDataModel<Result>(results);
}

public DataModel<Result> getResultSample() {
    return resultSample;
}

As to your concrete functional requirement, you can also just reference UIData#getRowIndex() without wrapping the value in a DataModel.

public Result[] getResults() { // Consider List<Result> instead.
    return results;
}
<h:dataTable binding="#{table}" value="#{bean.results}" var="result">
    <h:column>#{table.rowIndex + 1}</h:column>
    <h:column>#{result.subject.name}</h:column>
</h:dataTable>

Note that I incremented it with 1 as it's 0-based while humans expect an 1-based index.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks @BalusC, your second suggestion seems like a perfect one, I looking the link and will revert shortly – Paullo Jul 12 '15 at 14:07
  • WoooW this is working perfectly well with the binding approach. But please @BalusC where is the table object coming from? I did not define it any where yet it has the rowIndex and what other attributes could it possibly have? – Paullo Jul 12 '15 at 14:19
  • Click the `UIData` link in my answer for the javadoc. All `getXxx()` methods are also available in EL this way. I also added a third "see also" link explaining the `binding` attribute. – BalusC Jul 12 '15 at 14:25
  • Thanks once more @BalusC those links have been very useful – Paullo Jul 12 '15 at 14:42