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
ganesh kumar 3ganesh kumar 3 

Triggers Question

Display the total no.of contacts into respective account 
dany__dany__
this might help you

trigger count on Contact (after insert ,after delete ,after update )

{
set <id> accid= new set <id>();
list<account> acclist =new list<account>();
list<account> racc =new list<account>();
list<contact> conlist= new list<contact>();
list<contact> rcon=new list<contact>();
map<id,decimal> mp= new map<id, decimal>();
if(trigger.isinsert)
  {
  for(contact con:trigger.new)
    {
    accid.add(con.accountid);
    }
  }
  if(trigger.isdelete)
  {
  for(contact con:trigger.old)
    {
    accid.add(con.accountid);
    }
  }
 if(trigger.isupdate)
  {
  for(contact con:trigger.old)
    {
    accid.add(con.accountid);
    }
  }
 
 acclist =[select id, name from account where id in:accid];
 conlist=[select id,accountid , name from contact where accountid in:accid];
  for(account acc:acclist)
   {
   for(contact c:conlist)
     {
     if(c.accountid==acc.id)
       {
         rcon.add(c);
         mp.put(c.accountid,rcon.size());
       }
     }
     
   }
  if(acclist.size()>0)
    {
    for(account a:acclist)
    
     {
     if (mp.get(a.id)!=null)
       {
       a.no_of_contacts__c=mp.get(a.id);
       }
     }
    } 
    update acclist;
}