Search code examples
salesforcevisualforcesoql

How do I display the results of an aggregate SOQL query on a Visualforce page?


I'm very new to Visualforce.

I'm looking at this page here: http://force.siddheshkabe.co.in/2010/11/displaying-aggregate-result-on.html

So when I added this code onto a VisualForce page:

  AggregateResult[] groupedResults  = [SELECT Name, Days__c FROM Contact WHERE Days__c != ];

  for (AggregateResult ar : groupedResults)  {
    System.debug('Name: ' + ar.get('Name') + '\nDays Taken : ' + ar.get('Days__c') + '\n');

But all it does is print the code instead of executing it. What should I be doing? Thanks for any guidance.


Solution

  • The Apex code goes into a custom controller or controller extension. The VisualForce page is a separate file from the controller. The page you referenced doesn't show the VF page. Also, I don't think you can bind VF components to AggregateResult, so you'll need a wrapper class.

    Here's some working code.

    Controller:

    public with sharing class TestController {
    
        public Summary[] Summaries { get; set; }
    
        public TestController() {
            AggregateResult[] results = [
                SELECT Name, Count(Id) Quantity FROM Opportunity GROUP BY Name
            ];
            Summaries = new List<Summary>();
            for (AggregateResult ar : results) {
                Summaries.add(new Summary(ar));
            }
        }
    
        // wrapper class to hold aggregate data
        public class Summary {
            public Integer Quantity { get; private set; }
            public String Name { get; private set; }
    
            public Summary(AggregateResult ar) {
                Quantity = (Integer) ar.get('Quantity');
                Name = (String) ar.get('Name');
            }
        }
    
    }
    

    VF page:

    <apex:page controller="TestController">
        <apex:form >
            <apex:repeat value="{!Summaries}" var="summary">
                {!summary.Name}: {!summary.Quantity}<br/>
            </apex:repeat>
        </apex:form>
    </apex:page>