Last active
August 20, 2018 12:11
-
-
Save dhruv-soft/5721224 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trigger ContactsOnAccount on Contact (after insert, after delete,after undelete,after update) { | |
Set<Id> aId = new Set<Id>(); | |
if(Trigger.isInsert || Trigger.isUndelete){ | |
for(Contact opp : Trigger.New){ | |
aId.add(opp.AccountId); | |
} | |
List<Account> acc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:aId]; | |
List<Contact> con = [select id from contact where AccountId in :aId]; | |
for(Account a : acc){ | |
a.No_of_Contacts_in_SFDC__c=con.size(); | |
}update acc; | |
} | |
if(Trigger.isDelete){ | |
for(Contact opp : Trigger.old){ | |
aId.add(opp.AccountId); | |
} | |
List<Account> acc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:aId]; | |
List<Contact> con = [select id from contact where AccountId in :aId]; | |
for(Account a : acc){ | |
a.No_of_Contacts_in_SFDC__c=con.size(); | |
}update acc; | |
} | |
if(Trigger.isUpdate){ | |
Set<Id> OldAId = new Set<Id>(); | |
for(Contact opp : Trigger.new){ | |
if(opp.AccountId != Trigger.oldMap.get(opp.id).AccountId || opp.Primary_Contact__c != Trigger.oldMap.get(opp.id).Primary_Contact__c) | |
aId.add(opp.AccountId); | |
OldAId.add(Trigger.oldMap.get(opp.id).AccountId); | |
} | |
if(!aId.isEmpty()){ | |
//for new Accounts | |
List<Account> acc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:aId]; | |
//For New Account Contacts | |
List<Contact> con = [select id from contact where AccountId in :aId]; | |
/* | |
This is For Old Contacts Count | |
*/ | |
//for Old Accounts | |
List<Account> Oldacc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:OldAId]; | |
//For Old Account Contacts | |
List<Contact> OldCon = [select id from contact where AccountId in :OldAId]; | |
//For New Accounts | |
for(Account a : acc){ | |
a.No_of_Contacts_in_SFDC__c=con.size(); | |
}update acc; | |
//For Old Accounts | |
for(Account a : Oldacc){ | |
a.No_of_Contacts_in_SFDC__c=OldCon.size(); | |
}update Oldacc; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I found this very ointeresting. But, could you explain what is the field Primary_Contact__c?
Thanks,
Skender