Iterate Map data type in Salesforce Visualforce Page

Iterate Map data type in Salesforce Visualforce Page

apex:repeat tag can be used to iterate map data type in Salesforce Visualforce page.

Sample Code:

Visualfore Page:

<apex:page controller="SampleVFPageController">
    <apex:repeat value="{!mapAccNameContactList}" var="objAcc">
        Account Name: {!objAcc}<br/>
        <apex:repeat value="{!mapAccNameContactList[objAcc]}" var="objCon">
            Contact Name: {!objCon.FirstName} {!objCon.LastName}<br/>
        </apex:repeat>
    </apex:repeat>
</apex:page>

Apex Controller:

public class SampleVFPageController {
	
    public Map < String, List < Contact > > mapAccNameContactList { get; set; }
    
    public SampleVFPageController() {
    
    	mapAccNameContactList = new Map < String, List < Contact > >();  
        
        for ( 
            Account objAcc : [ 
                SELECT Name, 
                ( 
                    SELECT FirstName, LastName 
                    FROM Contacts 
                ) 
                FROM Account 
                LIMIT 5 
            ] 
        ) {
            mapAccNameContactList.put( objAcc.Name, objAcc.Contacts );
        }
        
        System.debug(
            'mapAccNameContactList is' +
            mapAccNameContactList
        );
    
    }

}

Output:

Leave a Reply