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.
1 Answer
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>
-
it is showing error create apex property classname.mapAccountToContacts– leeCommented Mar 9, 2016 at 10:23
-
-
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>– leeCommented Mar 9, 2016 at 10:37
-
@lee have you queried Account and added all the values in map ..?????? Commented Mar 9, 2016 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– leeCommented Mar 9, 2016 at 10:38