Scenario:
I came across a issue where visualforce does not allow one to Count or Sum records in a page.
One solution would be to add more code to the controller to do a count of the records. Which is ok.
A simple solution is to use the apex variable function in Visualforce.
Solution:
- Lets do it off Contacts
- In your Apex Controller : Create a SOQL query as is:
public class countcontroller{
public List<Contact> queryResult {get;private set;}
public String qryString {get;set;}
public PageReference query(){
qryString = 'SELECT Name, Email, Phone from Contact';
queryResult = Database.query(qryString);
return null;
}
}
Pretty Simple and Straight Forward.
Now for the VF Page and Magic:
You will see I use the apex variable function to do a couple of things:
create a variable
run the query inside that variable counting all the records by 1 within a repeat tag
calling the variable with the total
Kind of like a for Loop but in Visualforce instead of controller.
<apex:page standardcontroller="Contact" extensions="countcontroller">
<table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr height="5">
<td width="35%" class="outsideround_head" align="right">
Total Contacts Returned:
</td>
<td width="8%" class="outside_round_head_value">
<apex:variable var="call" value="{!0}" />
<apex:repeat var="countitall" value="{!queryResult}" >
<apex:variable var="call" value="{!call+1}"/>
</apex:repeat>
<apex:outputText value="{!call}"/>
</td>
</tr>
</table>
</apex:page>
Wallah you have count.
Thanks please give me feedback!!!
Thanks
Check out my Other Salesforce.com Blogs
Salesforce Made Easy
Salesforce Data Migration Made Easy
eTechCareers.com Coming Soon