Hi,
Controller:
public class GroupingExampleController
{
private List<Account> allAccs {get; set;}
public List<GroupWrapper> groups {get; set;}
public String groupFieldName {get; set;}
public List<SelectOption> groupOptions {get; set;}
public GroupingExampleController()
{
allAccs=[select id, Name, BillingStreet, BillingCity, BillingCountry, Type,
(select id, Name, Email, Phone from Contacts limit 5)
from Account
where Type != null
limit 10];
groupFieldName='Type';
setupGrouping();
groupOptions=new List<SelectOption>();
groupOptions.add(new SelectOption('Name', 'Name'));
groupOptions.add(new SelectOption('BillingCity', 'BillingCity'));
groupOptions.add(new SelectOption('BillingCountry', 'BillingCountry'));
groupOptions.add(new SelectOption('Type', 'Type'));
}
public PageReference regroup()
{
setupGrouping();
return null;
}
private void setupGrouping()
{
Map<String, List<Account>> groupedMap=new Map<String, List<Account>>();
for (Account acc : allAccs)
{
String key=String.valueof(acc.get(groupFieldName));
if ( (null==key) || (0==key.length()) )
{
key='Undefined';
}
List<Account> groupedAccs=groupedMap.get(key);
if (null==groupedAccs)
{
groupedAccs=new List<Account>();
groupedMap.put(key, groupedAccs);
}
groupedAccs.add(acc);
}
groups=new List<GroupWrapper>();
for (String key : groupedMap.keySet())
{
GroupWrapper gr=new GroupWrapper();
groups.add(gr);
gr.accs=groupedMap.get(key);
gr.groupedVal=key;
}
}
public class GroupWrapper
{
public List<Account> accs {get; set;}
public String groupedVal {get; set;}
public Integer count {get {return accs.size(); } set;}
}
}
Visualforce page:-
<apex:page controller="GroupingExampleController" tabstyle="Account">
<apex:form >
<apex:pageBlock >
Group By: <apex:selectList value="{!groupFieldName}" size="1">
<apex:selectOptions value="{!groupOptions}" />
</apex:selectList> <apex:commandButton value="Go" action="{!regroup}"/>
<table border="0">
<apex:repeat value="{!Groups}" var="group">
<tr>
<td colspan="3"><b>{!groupFieldName}:{!group.GroupedVal}</b> - {!group.count} records</td>
</tr>
<apex:repeat value="{!group.accs}" var="acc">
<tr>
<td width="30px"></td>
<td colspan="2"><b>Account:</b>{!acc.Name}</td>
</tr>
<apex:repeat value="{!acc.Contacts}" var="cont">
<tr>
<td width="30px"></td>
<td width="30px"></td>
<td><b>Contact:</b>{!cont.Name}</td>
</tr>
</apex:repeat>
</apex:repeat>
</apex:repeat>
</table>
</apex:pageBlock>
</apex:form>
</apex:page>
Thanks