Advertisement
Guest User

Untitled

a guest
Jul 12th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. trigger UpdateContactCountOnAccount on Contact (after insert, after update, after delete)
  2. {
  3. Set<Id> AccountIds = new Set<Id>();
  4.  
  5. if(!Trigger.isDelete)
  6. {
  7. for (Contact ct : Trigger.new)
  8. {
  9. if(Trigger.isInsert && ct.AccountId != null)
  10. {
  11. AccountIds.add(ct.AccountId);
  12. }
  13. if(Trigger.isUpdate)
  14. {
  15. if(ct.AccountId==null && Trigger.oldMap.get(ct.Id).AccountId != null)
  16. {
  17. AccountIds.add(Trigger.oldMap.get(ct.Id).AccountId);
  18. }
  19. if(ct.AccountId!=null && Trigger.oldMap.get(ct.Id).AccountId != null
  20. && ct.AccountId != Trigger.oldMap.get(ct.Id).AccountId)
  21. {
  22. AccountIds.add(ct.AccountId);
  23. AccountIds.add(Trigger.oldMap.get(ct.Id).AccountId);
  24. }
  25. if(ct.AccountId!=null && Trigger.oldMap.get(ct.Id).AccountId == null)
  26. {
  27. AccountIds.add(ct.AccountId);
  28. }
  29. }
  30. }
  31. }
  32. else
  33. {
  34. for (Contact ct : Trigger.old)
  35. {
  36. if(Trigger.isDelete && ct.AccountId != null)
  37. {
  38. AccountIds.add(ct.AccountId);
  39. }
  40. }
  41. }
  42.  
  43. List<Account> AcctToUpdate = new List<Account>();
  44. for (AggregateResult ar: [Select Count(Id) ContactCount, AccountId
  45. from Contact where AccountId IN: AccountIds GROUP BY AccountId])
  46. {
  47. Account tmp = new Account(Id=(Id)ar.get('AccountId'), No_of_Contacts__c=(Decimal)ar.get('ContactCount'));
  48. AcctToUpdate.add(tmp);
  49. }
  50. if(AcctToUpdate.size()>0)
  51. update AcctToUpdate;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement