Category Archives: Visualforce

Showing Aggregate Result In VisualForce Page

Suppose by some Custom logic, you’ve already calculated  Count of Contacts for each Account. Your Account has two record Type ‘Bus Rec Type’ and ‘Person Rec Type’. Now on Visual force page you want to display  Total number of Contacts’ for each Record Type.

Now Count of Contacts for each record type can be easily found using aggregate Query on Controller But we sometimes get stuck how to display Aggregate Result in Visual force Page

The Answer of this problem is : Wrapper Class You’ve to add Result of Aggregate Query in ‘List of objects of Wrapper Class’. and then show the result in VF page.

Showing below how we can do it, using above example Below is Your VF Page : It is showing list in VF Page.

<apex:page controller="AccAggregat">
<apex:datatable value="{!wlist}" var="a" >
<apex:column headerValue="Recordtype by Name " value="{!a.Rtype }" />
<apex:column headerValue="CountValue" value="{!a.count}" />


Now code of controller: 

public class AccAggregat {

Public aggregateResult[] agresult;
public list<WrapperClass> wlist{get;set;}

public AccAggregat() {

//This Query calculating Aggregate Result 
agresult = [select recordType.Name RecType, sum(Count_of_Contacts__c) Allcon 
from Account group by recordType.Name];
//Here we're populating  list of Wrapper class with Data from Aggregate result
//We'll use this wrapper class list in VF Page

wlist = new list<WrapperClass>();
For ( aggregateResult ag :agresult)
wlist.add(new WrapperClass((String)ag.get('RecType'), (Decimal)ag.get('Allcon')));

//This is wrapper class containing data to be shown on VF page
public class WrapperClass
public string Rtype{get;set;}
public Decimal count{get;set;}

Public WrapperClass( string Recordtype, Decimal cnt)
this.Rtype = RecordType;
this.count = cnt;

Few points to Remember:

  1.  In Wrapper Class,  use getter and setter for variables, which are shown on VF page.
  2. Note syntax to create new object, which is added in List of wrapper list:
  3. Note also syntax to get result  from Aggregate Object : ag.get(‘RecType’)

wlist.add(new WrapperClass((String)ag.get(‘RecType’), (Decimal)ag.get(‘Allcon’)));