Friday, 9 February 2018

Roll up Trigger

trigger RollUptrg on Contact(after insert, after update, after delete, after undelete){
Set<id> accIds = new Set<Id>();
    if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete){
for(Contact con: trigger.new){
if(con.AccountId != null){
accids.add(con.AccountId);
}
}
}
    if(trigger.isUpdate || trigger.isDelete){
        for(contact con: trigger.old){
if(con1.AccountId != null){
accids.add(con.AccountId);
}
}
    }
if(accids.size()>0){
List<Account> lst = [Select id, number_of_contacts__c,(Select id from Contacts) from Account where id in: accids];
for(Account acc : lst){
acc.number_of_contacts__c = acc.contacts.size();
}
update lst;
}
}

No comments:

Post a Comment