Displaying AggregateResult on Visualforce Page : Solved

I wanted to display records from an aggregate query on my visualforce page. I expected this to be pretty staright forward but it turns out there are many ways to get this done and most solutions on the forums were not as straight forward as I expected.

I was storing my results in a list of AggregateResult sobjects. Following is the code of my controller extension.

public class PartnerController {

 private final Account acct;
 private list<AggregateResult> resellers;
 public PartnerController(ApexPages.StandardController stdController){
 this.acct = [select id, name from Account where id=:ApexPages.currentPage().getParameters().get('id')];
 resellers = [SELECT Sold_To_Id__c id, Sold_To__r.Name Name, sum(Price__c) Sales FROM Transaction__c where Sold_By__c = :this.acct.id GROUP BY Sold_To_Id__c, Sold_To__r.Name order by sum(Price__c) desc];
 }
 public list<AggregateResult> resellerlist {
 get { return resellers;}
 }

}

However, you cannot refer to the fields in this sobject inside visualforce using the standard notion. For example the code below will cause an error like “Invalid field Id for Sobject AggregateResult”

<apex:pageBlockTable value="{!resellerlist}" var="o">
<apex:column >
<apex:facet name="header">Id</apex:facet>
{!o.id}</apex:column>
<apex:column >
<apex:facet name="header">Name</apex:facet>
{!o.Name}</apex:column>
<apex:column >
<apex:facet name="header">Sales</apex:facet>
{!o.Sales}</apex:column>
</apex:pageBlockTable>

Instead you should refer to the field in the sobject using the var['fieldname'] notion. Other solutions used a wrapper class and some even mentioned that it is not possible to bind directly to the AggregateResult sobject. For me the example given below works and does not require use of a wrapper class.

<apex:pageBlockTable value="{!resellerlist}" var="o">
<apex:column >
<apex:facet name="header">Id</apex:facet>
{!o['id']}</apex:column>
<apex:column >
<apex:facet name="header">Name</apex:facet>
{!o['Name']}</apex:column>
<apex:column >
<apex:facet name="header">Sales</apex:facet>
{!o['Sales']}</apex:column>
</apex:pageBlockTable>

3 Thoughts on “Displaying AggregateResult on Visualforce Page : Solved

  1. Yousef S on April 6, 2013 at 3:45 am said:

    Thank you very much!

  2. Thanks.
    It is working great for me.

  3. Vijay on June 6, 2013 at 6:03 am said:

    Good blog – this helped me.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation