How to detect first or last iteration of apex:repeat

I currently have some VisualForce which uses an <apex:repeat/> element and inserts commas in between the items like so:

<apex:variable var="idx" value="{!0}"/>
<apex:repeat value="{!items}" var="item">
    <apex:outputPanel rendered="{!NOT(idx == 0)}">, </apex:outputPanel>
    <apex:outputPanel>
        <apex:outputText value="{!item.Name}" />
    </apex:outputPanel>
    <apex:variable var="idx" value="{!idx + 1}" />
</apex:repeat>

However, today I noticed in the documentation that this is explicitly unsupported and is a case of undefined behavior:

<apex:variable> does not support reassignment inside of an iteration component, such as <apex:dataTable> or <apex:repeat>. The result of doing so, e.g., incrementing the <apex:variable> as a counter, is unsupported and undefined.

(Source: https://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_variable.htm)

So my question is this: if the syntax I’m using is not supported (even though it does work), then how can I render this comma-delimited data in a way that is supported, using only VisualForce? Is this possible?

Answer

I rethought and this seems the best way so deleting the previous contents:

  1. Create a map<account,index>

  2. Put the account, index and also populate the last index in your method, and check if the index = last index and render the ,

Page:

<apex:page controller="testing_repeat_controller" sidebar="false">
<apex:repeat value="{!Itemsforuser}" var="item">    
    <apex:outputPanel >
        <apex:outputText value="{!item.Name}"/>
        {!IF(account_index_map[item] == lastindexofaccount,'',',')}
    </apex:outputPanel>
</apex:repeat>
</apex:page>

Controller:

public class testing_repeat_controller {
    public integer indexofaccount {get;set;}
    public integer lastindexofaccount {get;set;}
    public map<account,integer> account_index_map {get;set;} 
    public testing_repeat_controller(){
        indexofaccount      = 0;
        lastindexofaccount  = 0;
        account_index_map = new map <account,integer>();
    }
    public List<account> getItemsforuser(){
        list<account> acc_list = [select id,name from account limit 10];
        lastindexofaccount = acc_list.size();
        for(account a: acc_List){        
            indexofaccount = indexofaccount +1;
            account_index_map.put(a,indexofaccount);
        }
        return acc_List;
    }
}

Output:

abc ,abc ,TEST ,test123 ,abc ,abc ,abc ,TEST ,Test_Pass ,abc

Attribution
Source : Link , Question Author : user2221343 , Answer Author : Adrian Larson

Leave a Comment