You need to sign in to do that
Don't have an account?
triggers salesforce
Create field called "Count of Contacts" on Account Object.
When we add the Contacts for that Account then count will populate in the field on Account details page. When we delete the Contacts for that Account, then Count will update automatically.
When we add the Contacts for that Account then count will populate in the field on Account details page. When we delete the Contacts for that Account, then Count will update automatically.
Hi Sriram,
Find the below Solution
TRIGGER
Apex class
if you find this helpful mark it as the best answer.
Hope these will help you in all the condition
//Apex Class triggerhNDLER
public class NoOfContactEventHandlerClass {
public static void counttrigger(contact [] cts){
set<id> accidlist = new set<id>();
for(contact con:cts){
accidlist.add(con.Accountid);
}
list<account> acc = new list<account>();
for(Account a:[select id,Count_No_of_Contact__c,(select id from contacts)from Account where id IN:accidlist]){
a.Count_No_of_Contact__c = a.contacts.size();
acc.add(a);
}
update acc;
}
}
///Trigger on contact
trigger ContactCountOnAccount on Contact (after insert,after update,after delete,after undelete) {
if(trigger.isafter){
if(trigger.isinsert){
NoOfContactEventHandlerClass .counttrigger(trigger.new);
}
}
if(trigger.isafter){
if(trigger.isundelete){
NoOfContactEventHandlerClass .counttrigger(trigger.new);
}
}
if(trigger.isafter){
if(trigger.isupdate){
NoOfContactEventHandlerClass .counttrigger(trigger.new);
}
}
if(trigger.isafter){
if(trigger.isupdate){
NoOfContactEventHandlerClass .counttrigger(trigger.old);
}
}
if(trigger.isafter){
if(trigger.isdelete){
NoOfContactEventHandlerClass .counttrigger(trigger.old);
}
}
}
Thanks
Ajay Patel