Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trigger ContactCountOnAccount on Contact (after insert, after update, after delete) {
- Set<Id> AccountIds = new Set<Id>();
- List<Account> AccountsToUpdate = new List<Account>();
- for(Contact c : trigger.new){
- AccountIds.add(c.AccountId);
- }
- if(trigger.isUpdate || trigger.isdelete){
- for(Contact o : trigger.old){
- AccountIds.add(o.AccountId);
- }
- }
- map<Id, Account> MapAcc = new map<Id, account>([SELECT id, No_of_Contacts__c FROM Account WHERE Id IN : AccountIds]);
- List<Account> LstAcc = New List<Account>([SELECT Id, No_of_Contacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :AccountIds]);
- for(Account acc : LstAcc){
- MapAcc.get(acc.id).No_of_Contacts__c = acc.contacts.size();
- AccountsToUpdate.add(MapAcc.get(acc.id));
- }
- update AccountsToUpdate;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement