Pablo
Pablo

Reputation: 3467

Add loop index in c:forEach tag

before I have been using render time tags(like a4j:repeat,ui:repeat), to create panels based on a collection of items. All of that changed and now I must use c:forEach instead. On each panel I do a lot of AJAX calls and partial updates of the page. That's why I'm using custom id's in order to identify wich components I want to update. So my render attributes are like this:

#{cc.clientId}:pnlRepeat:#{row}:radioAplicar

Where pnlRepeat is the id attribute, and {#row} is the rowKeyVar attribute in the same tag. Now... none of them exists when using c:forEach, hence, I'm getting duplicated id exceptions. I know I could use the varStatus, and create a panel with the #{row} Id, but on the other hand. JSF doesn't let id attributes to evaluate an EL expression. What would be a workaround?. Thanks a lot.

Upvotes: 1

Views: 1112

Answers (1)

maple_shaft
maple_shaft

Reputation: 10463

You should not be trying to base any of your ManagedBean logic or EL expressions on the generated IDs of repeating components like <ui:repeat> or <c:forEach>. Like you already mentioned the EL expression will not let you dynamically evaluate an Id expression, so the appropriate way to deal with these situations where an event is triggered by an individual item within a repeating component is to pass a uniquely identifying value in the form of the <f:attribute> tag.

Using the <f:attribute> tag will put the specified value into the request attributes so that it can be retrieved in your action listener.

<ui:repeat value="..." var="repeatedVar">
  <h:inputText id="newTxt" value="#{repeatedVar}" >
     <f:attribute name="unique_id" value="#{repeatedVar.uniqueId}" />
  </h:inputText>
</ui:repeat>
<h:commandButton actionListener="#{managedBean.someMethod}" ...

And in the action method we can determine what the action or business logic is to be executed on by retrieving that dynamic components attribute.

public void someMethod() {
    String uniqueId = (String) UIComponent.getCurrentComponent(FacesContext.getCurrentInstance()).getAttributes().get("unique_id");
    //Get the unique data object
    //Do some business logic and other stuff...
}

Upvotes: 2

Related Questions