1

Are you able to display the element number value in a visualforce repeat. For eg:

<apex:repeat var="li" value="{!list}">
 <p>{!fieldOne}<p>
 <p>{!fieldTwo}<p>
 <p>list[0]<p> <--  How can I display 0 here?
</apex:repeat>

Thanks in advance!

2 Answers 2

2

Just output Li as it holds each value of apex:repeat iteration variable list

<apex:repeat var="li" value="{!list}">
 <p>{!fieldOne}<p>
 <p>{!fieldTwo}<p>
 <p>{!li}<p> <--  How can I display 0 here?
</apex:repeat>

and if your intention is to display the index of the list then you do it using apex:variable

<apex:variable value="{!0}" var="rowNum"/>

    <apex:repeat var="li" value="{!list}">
     <p>{!fieldOne}<p>
     <p>{!fieldTwo}<p>
     <p>{!rowNum}<p> <--  How can I display 0 here?
     <apex:variable var="rowNum" value="{!rowNum + 1}"/>
    </apex:repeat>
3
  • N.B. variables are not intended to be used in iterators, and may have undesirable side effects.
    – sfdcfox
    May 28, 2018 at 13:45
  • @sfdcfox, if you can post a better answer I will delete mine. The correct and accurate answer has to be accepted as it will get referred in the future as well
    – RedDevil
    May 28, 2018 at 14:39
  • @RedDevil I gave you +1 anyways, but it's something you may want to avoid using in the future.
    – sfdcfox
    May 28, 2018 at 16:03
1

The officially supported way is to use a wrapper class or a list of numbers.

List of Indexes

<apex:repeat var="index" value="{!listIndexes}">
  <p>{!listVar[index]['fieldOne']}<p>
  <p>{!listVar[index]['fieldTwo']}<p>
  <p>{!index}<p>
</apex:repeat>

Where listIndexes might come from a method like this:

public Integer[] getListIndexes() {
  Integer size = listVar.size();
  Integer[] results = new Integer[size];
  for(Integer index = 0; index < size; index++) {
    results[index] = index;
  }
  return results;
}

Wrapper

This is as simple as defining a wrapper for the list. You can even relatively seamlessly convert your wrapper on the fly as an accessor:

public class Wrapper {
  public Integer rowNum { get; set; }
  public SObject record { get; set; }
  public Wrapper(Integer rowNum, SObject record) {
    this.rowNum = rowNum;
    this.record = record;
  }
}
public Wrapper[] getWrappedItems() {
  Integer size = listVar.size();
  Wrapper[] results = new Wrapper[size];
  for(Integer index = 0; index < size; index++) {
    results[index] = new Wrapper(index, listVar[index]);
  }
  return results;
}

This results in the following Visualforce:

<apex:repeat var="wrapper" value="{!wrappedItems}">
  <p>{!wrapper.record.field1}<p>
  <p>{!wrapper.record.field2}<p>
  <p>{!wrapper.rowNum}<p>
</apex:repeat>
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .