function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sai kumar 49sai kumar 49 

displaying total number of contacts for each account in salesforce?

Hi Sai,

Try with bewo code .
trigger opplineCount  on Contact ( after insert, after update,after delete,after undelete) {
     Set<Id> accountIdSet=new Set<Id>();
     List<Account> accListToUpdate=new List<Account>();
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
        for(Contact con :{
            if(con.AccountId != null)
       for(Contact con: Trigger.old){
            if(con.AccountId != null)
   for(AggregateResult res : [SELECT count(Id)can,AccountId FROM Contact WHERE AccountId IN :accountIdSet group by AccountId]) {
          accListToUpdate.add(new Opportunity(Id=(Id)res.get('AccountId'),Contact_Count__c=(Integer)res.get('can')));
      update accListToUpdate;
    }catch(DmlException de){

kishore cmxkishore cmx
Hi manoj, plz write trigger count the total number of contacts , the number will be display in  no.of contacts field in contact object?
Vijay NagarathinamVijay Nagarathinam
Hi Kishore,

Try the following code, it will be working insert and delete the contact.
trigger countContact on Contact(after insert,after update,after delete)
    set<Id> accontIds = new set<Id>{};    
    list<Account> projIds = new list<Account>();
    if(trigger.isInsert || trigger.isUpdate) 
        for(Contact p:trigger.old)       

    AggregateResult[] groupedResults = [select accountid,count(id) countt from Contact where accountid in :accontIds group by accountid];
    for (AggregateResult ar : groupedResults)        
        projIds.add(new Account(id=(ID)ar.get('accountid'),Count__c = (Integer)ar.get('countt'))); 
    update projIds;

Nagaraju MogiliNagaraju Mogili
Hi Kishore/Manoj,

How can we do the same task using the Apex class and display the Name of the Account and the Number of Contacts in the VF Page.

Could anyone help me on this .... at your earliest possible.

Nagaraju Mogili