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 

Trigger for Contact count on Account

ManojjenaManojjena
Hi Sai ,

Try with beow 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 : Trigger.new){
            if(con.AccountId != null)
                accountIdSet.add(con.AccountId);     
        }
    }If(Trigger.isDelete){
       for(Contact con: Trigger.old){
            if(con.AccountId != null)
                accountIdSet.add(con.AccountId);        
        }
    }
   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')));
    }
    try{
      update accListToUpdate;
    }catch(DmlException de){
      System.debug(de);
    }
}

Thanks 
Manoj
Vijay NagarathinamVijay Nagarathinam
Hi Sai,

If you are using Master detail relationship means you can acheive your task using Rollup summary field.
Vijay NagarathinamVijay Nagarathinam
Try the follwing links.

http://www.29lessons.com/2014/06/how-to-write-trigger-count-of-contacts.html

http://salesforce.stackexchange.com/questions/63282/apex-trigger-on-contact-to-update-field-on-account
Vijay NagarathinamVijay Nagarathinam
Hi Manoj,

Try the following code.
 
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.new)       
        accontIds.add(p.accountId);
    }   
     
    if(trigger.isDelete) 
    { 
        for(Contact p:trigger.old)       
        accontIds.add(p.accountID);
     }  

    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;
}