You need to sign in to do that
Don't have an account?
kumar 197
Test Class For Number of Contacts on Account???
trigger ContactCount on Contact (after insert, after update, after delete, after undelete) {
if(Trigger.isinsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
ContactCount.countcontacts(trigger.new,trigger.old);
}
}
-----------
public class ContactCount {
public static void countcontacts(List<contact> newcontact,List<contact> oldcontact){
set<id> accids= new set<id>();
try{
if(newcontact !=null){
for(Contact c:newcontact){
if(c.AccountId!=null){
accids.add(c.accountid);
}
}
}if(oldcontact!=null){
for(Contact c:oldcontact){
accids.add(c.accountid);
}
}
List<Account> acc = [Select id, Number_of_Contacts__c,(Select id from Contacts) from Account where id IN: accids];
if(acc!=null){
for(Account accValue:acc){
accValue.Number_of_Contacts__c = accValue.Contacts.size();
}
}
if(!acc.isempty()){
update acc;
}
}
catch(exception e){
System.debug('Get Message'+e.getMessage());
}
}
}
if(Trigger.isinsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
ContactCount.countcontacts(trigger.new,trigger.old);
}
}
-----------
public class ContactCount {
public static void countcontacts(List<contact> newcontact,List<contact> oldcontact){
set<id> accids= new set<id>();
try{
if(newcontact !=null){
for(Contact c:newcontact){
if(c.AccountId!=null){
accids.add(c.accountid);
}
}
}if(oldcontact!=null){
for(Contact c:oldcontact){
accids.add(c.accountid);
}
}
List<Account> acc = [Select id, Number_of_Contacts__c,(Select id from Contacts) from Account where id IN: accids];
if(acc!=null){
for(Account accValue:acc){
accValue.Number_of_Contacts__c = accValue.Contacts.size();
}
}
if(!acc.isempty()){
update acc;
}
}
catch(exception e){
System.debug('Get Message'+e.getMessage());
}
}
}
Try Below Test Class 100% Coverage! Please Mark It As Best Answer If It Helps
Thank You!