Friday, April 30, 2010

How to use apex variable for total records in Visualforce

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:
  1. Lets do it off Contacts
  2. 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:&nbsp;
    </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
 

6 comments:

  1. Don't think so....

    From the SF Notes on apex:variable

    Note: < apex:variable > does not support reassignment inside of an iteration component, such as < apex:dataTable > or < apex:repeat >. The result of doing so, e.g., incrementing the < apex:variable > as a counter, is unsupported and undefined.

    ReplyDelete
    Replies
    1. Yes, you are correct. I have also seen that increment of the variable is not possible in iteration component.

      Delete
    2. apex:variable works in apex:repeat in spite of the SF notes. Someone also showed it works for another repeating element, but not for apex:dataTable.

      Delete
  2. Why can't you use queryResult.size() store in a variable in the class and display that variable on the page?

    Also in VF page you can do:

    ReplyDelete
    Replies
    1. apex:outputText value={!queryResult.size}

      Delete
  3. great example dear
    but how can i use nested loop in visualforce

    ReplyDelete