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.
[code lang=”java”]
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;}
}
}[/code]
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”
[code lang=”html”]
<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>
[/code]
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.
[code lang=”html”]
<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>
[/code]
Thank you very much!
Thanks.
It is working great for me.
Good blog – this helped me.