1

how to create a map that contains the account and list of corresponding contacts then we have to display this map on a VF page.

4

So you can create a map. this map can contain Account and there related contact records.

Like

map<Account, List<Contact>> mapAccountToContacts = new map<Account, List<Contact>>();

SO basically if you are using this map in your vf page then this variable should be in get set property

public class myClaass{
public map<Account, List<Contact>> mapAccountToContacts {get;set;}

  public myClaass(){
    mapAccountToContacts = map<Account, List<Contact>>();
    // query here and add into this map
  }
} 

If you just wanted to display these records then use private set This is reduce view state and you can't update records from page.

And add the values in map. You can use subquery to get the contacts related to each Account record.

And then you can assign to map.

for(Account objAcc :[SELECT Name, (SELECT FirstName, LastName FROM Contacts) FROM Account])
{
    mapAccountToContacts.put(objAcc, objAcc.Contacts);
}

In VF page. You need 2 apex:repeat. One apex:repeat to iterate over map and another apex:repeat to iterate over list contacts that are associated with each Account record.

<apex:repeat value="{!mapAccountToContacts}" var="mapAccKey">
    Account Name: {!mapAccKey.Name}

    <apex:repeat value="{!mapAccountToContacts[mapAccKey]}" var="con">
    Contacts First Name :{!con.LastName}
    Contacts Last Name  :{!con.LastName} 
    </apex:repeat>
</apex:repeat>
10
  • it is showing error create apex property classname.mapAccountToContacts
    – lee
    Mar 9 '16 at 10:23
  • it is showing nothing in vf page
    – lee
    Mar 9 '16 at 10:37
  • VF page- <apex:page controller="MapOnVf"> <apex:repeat value="{!Mmap}" var="a"> Account Name:{!a.name} <apex:repeat value="{!Mmap[a]}" var="c"> Contact Last Name:{!c.lastName} </apex:repeat> </apex:repeat> </apex:page>
    – lee
    Mar 9 '16 at 10:37
  • @lee have you queried Account and added all the values in map ..??????
    – Ratan Paul
    Mar 9 '16 at 10:38
  • VF- PAGE: <apex:page controller="MapOnVf"> <apex:repeat value="{!Mmap}" var="a"> Account Name:{!a.name} <apex:repeat value="{!Mmap[a]}" var="c"> Contact Last Name:{!c.lastName} </apex:repeat> </apex:repeat> </apex:page> controller:- public class MapOnVf { public Map<account,List<contact>> Mmap {get;set;} public void getMapOnvf(){ for(Account acc :[SELECT Name, (SELECT FirstName, LastName FROM Contacts) FROM Account]) { Mmap.put(acc, acc.Contacts); } } } but it is showing nothing
    – lee
    Mar 9 '16 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.