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

青春壹個敷衍的年華 提交于 2019-12-11 02:48:33

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/8523303/how-do-i-display-the-results-of-an-aggregate-soql-query-on-a-visualforce-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!