You need to sign in to do that
Don't have an account?
CBN
Help me to Write Test Class for below Trigger using @Testsetup
trigger countContact on Contact (after insert, after update, after delete, after undelete)
{
Set<Id> setAccountIds = new Set<Id>();
//Whenever your working with After Undelete operation you can access data through
//Trigger.new or Trigger.newMap but not with Trigger.old or Trigger.oldmap variables
if(Trigger.isInsert || Trigger.isUndelete || Trigger.isUpdate)
{
for(Contact con : Trigger.new)
{
setAccountIds.add(con.AccountId);
}
}
if(Trigger.isDelete)
{
//if you use Trigger.new below in place of Trigger.old you will end up with
//System.NullPointerException:Attempt to de-reference a null object
for(Contact con : Trigger.old)
{
setAccountIds.add(con.AccountId);
}
}
List<Account> listAccs = [Select id,name,Total_No_Of_Contacts__c ,(Select id from contacts) from Account where Id in : setAccountIds];
for(Account acc :listAccs)
{
acc.Total_No_Of_Contacts__c = acc.contacts.size();
}
List<Account> listAccs1 = [Select id,name,No_of_active_contacts__c ,(select id from contacts where Contact_Roll__c = True) from Account where Id in : setAccountIds];
for(Account acc1 :listAccs1)
{
acc1.No_of_active_contacts__c = acc1.contacts.size();
}
update listAccs;
update listAccs1;
}
{
Set<Id> setAccountIds = new Set<Id>();
//Whenever your working with After Undelete operation you can access data through
//Trigger.new or Trigger.newMap but not with Trigger.old or Trigger.oldmap variables
if(Trigger.isInsert || Trigger.isUndelete || Trigger.isUpdate)
{
for(Contact con : Trigger.new)
{
setAccountIds.add(con.AccountId);
}
}
if(Trigger.isDelete)
{
//if you use Trigger.new below in place of Trigger.old you will end up with
//System.NullPointerException:Attempt to de-reference a null object
for(Contact con : Trigger.old)
{
setAccountIds.add(con.AccountId);
}
}
List<Account> listAccs = [Select id,name,Total_No_Of_Contacts__c ,(Select id from contacts) from Account where Id in : setAccountIds];
for(Account acc :listAccs)
{
acc.Total_No_Of_Contacts__c = acc.contacts.size();
}
List<Account> listAccs1 = [Select id,name,No_of_active_contacts__c ,(select id from contacts where Contact_Roll__c = True) from Account where Id in : setAccountIds];
for(Account acc1 :listAccs1)
{
acc1.No_of_active_contacts__c = acc1.contacts.size();
}
update listAccs;
update listAccs1;
}
All Answers
I haven't Tested it but you can try something like this
Please mark this answer as correct if it solves your Purpose.
Thanks!