1. Create a Custom Field No_Of_Contats on Account Object
2. When ever new Contact is created or deleted update the
no_of_contacts fields with no of contacts that exits for the parent records
trigger contactsTriggers on Contact (after insert,after delete) {
if(Trigger.isInsert && Trigger.isAfter)
TriggerContact.increment(Trigger.New);
else
TriggerContact.increment(Trigger.Old);
}
public class TriggerContact {
public static void increment(List<Contact> cons){
set<Id> accid=new Set<id>();
for(Contact c:cons){
accId.add(c.AccountId);
}
List<Account> accs=[select id,No_of_contacts__c ,(select id from Contacts ) from Account where id in:accId];
for(Account a:accs){
a.no_of_contacts__c=a.contacts.size();
}
update accs;
}
}
2. When ever new Contact is created or deleted update the
no_of_contacts fields with no of contacts that exits for the parent records
trigger contactsTriggers on Contact (after insert,after delete) {
if(Trigger.isInsert && Trigger.isAfter)
TriggerContact.increment(Trigger.New);
else
TriggerContact.increment(Trigger.Old);
}
public class TriggerContact {
public static void increment(List<Contact> cons){
set<Id> accid=new Set<id>();
for(Contact c:cons){
accId.add(c.AccountId);
}
List<Account> accs=[select id,No_of_contacts__c ,(select id from Contacts ) from Account where id in:accId];
for(Account a:accs){
a.no_of_contacts__c=a.contacts.size();
}
update accs;
}
}
No comments:
Post a Comment