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

writing a handler class of a trigger
I have written a trigger to count the number of contacts in accounts. Please help me with writing the handler class of it. I have very less knowledge on handler class:
trigger tocountcontactrecords on Contact (after insert) {
set<ID> setID = new set<ID>();
List<Account> ListAccount = new List<Account>();
for(contact con : trigger.new)
{
setID.add(con.AccountID);
}
For(account acc:[select id,name,Numberofcount__c,(select id from contacts) from account where id=:setID])
{
Account Ac1 = new Account();
ac1.Id=acc.Id;
ac1.Numberofcount__c = acc.contacts.size();
Listaccount.add(ac1);
}
update Listaccount;
}
trigger tocountcontactrecords on Contact (after insert) {
set<ID> setID = new set<ID>();
List<Account> ListAccount = new List<Account>();
for(contact con : trigger.new)
{
setID.add(con.AccountID);
}
For(account acc:[select id,name,Numberofcount__c,(select id from contacts) from account where id=:setID])
{
Account Ac1 = new Account();
ac1.Id=acc.Id;
ac1.Numberofcount__c = acc.contacts.size();
Listaccount.add(ac1);
}
update Listaccount;
}
invoke from the trigger
All Answers
invoke from the trigger
trigger transferContact on Contact (after insert, after update, after delete) {
set<ID> accountIds = new Set<Id>();
if(Trigger.isInsert){
for(Contact c : Trigger.New)
accountIds.add(c.accountId);
}
if(Trigger.isUpdate){
for(Contact c : Trigger.New){
if(c.AccountId != Trigger.oldMap.get(c.Id).AccountId){
accountIds.add(c.AccountId);
accountIds.add(Trigger.oldMap.get(c.Id).AccountId);
}
}
}
if(Trigger.isDelete){
for(Contact c : Trigger.old){
accountIds.add(c.AccountId);
}
}
System.debug('Account Ids are ' + accountIds);
HelperClass.countContacts(accountIds);
}
public class HelperClass {
public static void countContacts(set<ID> actIds){
List<Account> actList = [Select Id, (Select Id from Contacts), Shell__NumberOfContacts__c from Account where Id IN :actIds and isDeleted = false];
System.debug('Account Ids are ' + actList);
for(Account a : actList){
a.Shell__NumberOfContacts__c = a.Contacts.size();
}
update actList;
}
}
Use the following code:
Trigger:
trigger ContactCountTrigger on Contact (After insert,after update) {
Set<id> setAccountId=new Set<id>();
if(Trigger.isInsert || Trigger.isUpdate){
for(Contact con:Trigger.New){
setAccountId.add(con.AccountId);
}
}
Trigger Handler:
List<Account> listAcc=[select id,noOfContact__c,(Select id from Contacts)from Account where id in:setAccountId];
for(Account acc:listAcc){
acc.noOfContact__c=acc.contacts.size();
}
update listAcc;
}
There is a custom field I have made for Account object ie. (noOfContact), holding size of contacts present in an account.
Hope this code will solve your query please mark it as best answer if you find it helpful.
Thanks.
Ajay Dubedi
I just found the sollucion for this one.
Trigger should be :
And the class should be :
And it is working without any error. Thanks Vinod btw.