Ever wondered, how many contacts are associated with an account! There are couple of solutions you can achieve that
Method-01
- Use Visualforce and an extension.
- Sample VF Page
<apex:page standardController="account" extensions="contactsOnAccountsExtension"> <apex:outputLabel value="The total number of contacts on Account is: "/> <apex:outputText value="{!sum}"/> </apex:page>
- Apex - Extension controller
public class contactsOnAccountsExtension{ private final Account acct; public Integer sum {get; set;} public contactsOnAccountsExtension(ApexPages.StandardController stdController) { this.acct = (Account)stdController.getRecord(); sum = [SELECT count() FROM Contact WHERE AccountId =:acct.Id]; } }
- Display the VF on Account's detail page
- Click Setup.
- Click App Setup | Customize | Accounts
- Click Page Layouts | then select the layout.
- Select Visualforce pages from the palette and drag the Visualforce page above to an appropriate psition on the layout.
- Save the layout.
Above code is taken from Salesforce knowledge article 000003089
Method-02
Writing a trigger on Contact object.
trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
//---> above handling all states which could see a contact added to or removed from an account
//---> on delete we use Trigger.Old, all else, Trigger.new
List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;
//---> the Set class rocks for finding the unique values in a list
Set<Id> acctIds = new Set<Id>();
for (Contact c : contacts) {
//yes, you can have a contact without an account
if (c.AccountId != null) {
acctIds.add(c.AccountId);
}
}
List<Account> acctsToRollup = new List<Account>();
//****** Here is the Aggregate query...don't count in loops, let the DB do it for you*****
for (Account acc : [SELECT Id, (SELECT Id FROM Contacts)
FROM Account
WHERE Id in: acctIds ]){
Account a = new Account(Id = acc.Id); //---> handy trick for updates, set the id and update
// count contacts
Integer contactcount = 0;
for(Contact c: acc.Contacts) contactcount += 1;
a.ContactCount__c = contactcount;
acctsToRollup.add(a);
}
//----> probably you'll want to do a little more error handling than this...but this should work.
update acctsToRollup;
}
No comments:
Post a Comment