function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
wlevywlevy 

Aggregate query result in VF page

I need to display a single summary value on my VF page. Given the following apex code, how do I display "Total"?

 

I'm new to apex and VF so maybe I have the wrong approach altogether.

 

private String myVar;

myVar = 'something';

 

private List<AggregateResult> summary;

public List<AggregateResult> getSummary;

 

summary = [select sum(Total__c) Total from MyTable__c where Foo__c = :myVar];

 

VF:

<td>{!Summary.Total}</td>

 

When I save my work I get this error: Unknown property 'VisualforceArrayList.Total'

 

Best Answer chosen by Admin (Salesforce Developers) 
kennedymankennedyman

It's because "Summary" is a list of aggregate results objects.

 

So you need to get the first one, so Summary[0], but then you need to extract the total from that.

 

So, take a look at this: http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_agg_fns.htm

All Answers

kennedymankennedyman

It's because "Summary" is a list of aggregate results objects.

 

So you need to get the first one, so Summary[0], but then you need to extract the total from that.

 

So, take a look at this: http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_agg_fns.htm

This was selected as the best answer
wlevywlevy

Got it ....

 

private String myVar;

myVar = 'something';

private AggregateResult summary;

private Double summaryResult;

public Double getSummaryResult() {return summaryResult;}

 

summary = [select sum(Total__c) Total from MyTable__c where Foo__c = :myVar][0];  // The "[0]" is optional

summaryResult = Double.valueOf(summary.get('Total'));

 

VF:

<apex:outputField value="{!SummaryResult}"</apex:outputField>

 

kennedymankennedyman

Yes, exactly.

 

The "[0]" is not really optional in this case, without it you'll get an error. 

wlevywlevy

Thanks kennedyman, that bit of documentation is what I was seeking. As you can see I found a solution at about the same time you posted. :)

wlevywlevy

Oddly enough, my solution works with or without the [0]. I wonder why. Is it because my query can only return a single record?

kennedymankennedyman

Hmm, perhaps. I've never tried it, to be honest.