You need to sign in to do that
Don't have an account?

hi can anyone help me in writing helper/handler code for the following trigger? I am new to trigger and facing problems in writng the class....This trigger is supposed to update a field on Account record page which will show the number of related contacts
trigger contactTrigger on Contact (before insert,after insert,before update,after update,after undelete,after delete)
{
if(trigger.isAfter){
List<Contact> contactList = new List<Contact>();
Set<Id> accountIdSet= new Set<Id>();
if(trigger.isDelete){
contactList=Trigger.old;
}else{
contactList=Trigger.new;
}
for(Contact con :contactList){
if(con.AccountId!=null){
accountIdSet.add(Con.AccountId);
}
if(Trigger.isUpdate){
Contact oldContact = (Contact)Trigger.oldMap.get(con.Id);
if(oldContact.AccountId != con.AccountId){
accountIdSet.add(oldContact.AccountId);
}
}
}
List<Account> accountList = [SELECT Id,Name,Number_Of_Contacts__c,(select Id,Name From Contacts)
FROM Account
WHERE Id IN:accountIdSet];
for(Account acc: accountList){
List<Contact> relatedContacts = acc.Contacts;
if(relatedContacts !=null){
acc.Number_Of_Contacts__c = relatedContacts.size();
}else{
acc.Number_Of_Contacts__c=0;
}
}
update accountList;
}
}
{
if(trigger.isAfter){
List<Contact> contactList = new List<Contact>();
Set<Id> accountIdSet= new Set<Id>();
if(trigger.isDelete){
contactList=Trigger.old;
}else{
contactList=Trigger.new;
}
for(Contact con :contactList){
if(con.AccountId!=null){
accountIdSet.add(Con.AccountId);
}
if(Trigger.isUpdate){
Contact oldContact = (Contact)Trigger.oldMap.get(con.Id);
if(oldContact.AccountId != con.AccountId){
accountIdSet.add(oldContact.AccountId);
}
}
}
List<Account> accountList = [SELECT Id,Name,Number_Of_Contacts__c,(select Id,Name From Contacts)
FROM Account
WHERE Id IN:accountIdSet];
for(Account acc: accountList){
List<Contact> relatedContacts = acc.Contacts;
if(relatedContacts !=null){
acc.Number_Of_Contacts__c = relatedContacts.size();
}else{
acc.Number_Of_Contacts__c=0;
}
}
update accountList;
}
}
Try Below Code
Please Mark It As Best Answer If it Helps Thank You!
All Answers
Try Below Code
Please Mark It As Best Answer If it Helps Thank You!