Advertisement
Guest User

Untitled

a guest
Dec 29th, 2014
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. trigger ContactCountOnAccount on Contact (after insert, after update, after delete) {
  2. Set<Id> AccountIds = new Set<Id>();
  3. List<Account> AccountsToUpdate = new List<Account>();
  4. for(Contact c : trigger.new){
  5. AccountIds.add(c.AccountId);
  6. }
  7. if(trigger.isUpdate || trigger.isdelete){
  8. for(Contact o : trigger.old){
  9. AccountIds.add(o.AccountId);
  10. }
  11. }
  12. map<Id, Account> MapAcc = new map<Id, account>([SELECT id, No_of_Contacts__c FROM Account WHERE Id IN : AccountIds]);
  13. List<Account> LstAcc = New List<Account>([SELECT Id, No_of_Contacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :AccountIds]);
  14. for(Account acc : LstAcc){
  15. MapAcc.get(acc.id).No_of_Contacts__c = acc.contacts.size();
  16. AccountsToUpdate.add(MapAcc.get(acc.id));
  17. }
  18. update AccountsToUpdate;
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement