You are on page 1of 2

# I am Updating Account object field where Name as Number_of_contacts__c count of

all releted contacts.


Apex trigger:
trigger RollUpOnAccount on Contact (after insert,after update,after delete,after
undelete) {
Set<Id> accIDSet=new Set<Id>();
if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete){
for(contact con:trigger.new){
if(con.AccountId!=null) {
accIDSet.add(con.AccountId);
}
}
}
if(trigger.isUpdate || trigger.isDelete ){
for(contact con:trigger.old){
if(con.AccountId!=null){
accIDSet.add(con.AccountId);
}
}
}
if(!accIDSet.isEmpty()){
List<Account> accList=[select id,Number_of_Contacts__c,(select id from
contacts) from Account where Id IN:accIDSet ];
if(!accList.isEmpty()){
List<Account> updateAccList=new List<Account>();
for(Account acc:accList){
Account objacc=new Account
(Id=acc.Id,Number_of_Contacts__c=acc.contacts.size());
updateAccList.add(objacc);
}
if(!updateAccList.isEmpty()){
update updateAccList;
}
}
}
-----------------------------------------------------------------------------------
--
#I am Updating Account object field where Name as Number_of_contacts__c count of
all releted contacts.
trigger RollUpOnAccount1 on Contact (after insert,after update,after delete,after
undelete) {
if(trigger.isInsert || trigger.isUpdate || trigger.isDelete ||
trigger.isUndelete){
countcontact.countcontacts(trigger.new,trigger.old);
}
}
---------->
public class countcontact {
Public static void countcontacts(List<contact> newcontact,List<contact>
oldcontact){
Set<Id> accIDSet=new Set<Id>();
try{
if(newcontact!=null){
for(contact c:newcontact){
accIDSet.add(c.AccountId);
}
}
if(oldcontact!=null){
for(contact c:oldcontact){
accIDSet.add(c.AccountId);
}
}
List<Account> accList=[select id, Number_of_Contacts__c,(select id from
contacts)from Account where Id IN:accIDSet];
if(accList!=null){
for(Account acc:accList){
acc.Number_of_Contacts__c=acc.contacts.size();
}
}
if(!accList.isEmpty()){
update accList;
}
}
catch (exception e){
system.debug('Get Message'+e.getMessage());
}
}
}
-----------------------------------------------------------------------------------
------

You might also like