[SalesForce] Display an aggregate result on a visualforce page

I try to display on my visualforce page the result of a soql query (an aggregate result precisely).

Here is my controller (a partof it) :

public List<AggregateResult> somme {get; set;}
public Integer total {get; set;}

public Controller2(){
somme = [select SUM(Montant_total_calcule__c)total from Commande__c where Id IN :sCommandeId];

for(AggregateResult ar : somme){
total = (Integer) ar.get('total');
}

}

And the part of my page :

<apex:form>
<apex:pageBlockTable value="{!somme}" var="s">
<apex:column>Montant total : </apex:column>
<apex:column value="{!s.total}"></apex:column>
</apex:pageBlockTable>
</apex:form>

If anyone can help me, I got an error on my visualforce page : Invalid field total for SObject AggregateResult
I don't know how to fix it… And how to make my code working.

Thanks !

Best Answer

The AggregateResult object is like a Map and so to access the values you need to use map syntax in the Visualforce:

<apex:column value="{!s['total']}"></apex:column>

PS

Here is a working example of using the map syntax:

<apex:page controller="MyController">
    <apex:pageBlock>
        <apex:pageBlockTable value="{!results}" var="r">
            <apex:column value="{!r['aaa']}"/>
            <apex:column value="{!r['bbb']}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

public with sharing class MyController {
    public AggregateResult[] results {
        get {
            return [select AccountId aaa, count(Id) bbb from Contact group by AccountId];
        }
    }
}