You need to sign in to do that
Don't have an account?
Kunal Purohit 4
How to write trigger to update count at Account whenever Contact is created/Updated
Hello All,
I am new to developmennt.
We have Number field on Account called Open Contact Count and on Contact we have Status field picklist values as Open In Progress and Completed. Whenever any contact is created/updated with Status as Open related to Account, we need to maintain count of Open contact on related Account. I have written trigger for same but not working. Please give your valuable suggestions.
I am new to developmennt.
We have Number field on Account called Open Contact Count and on Contact we have Status field picklist values as Open In Progress and Completed. Whenever any contact is created/updated with Status as Open related to Account, we need to maintain count of Open contact on related Account. I have written trigger for same but not working. Please give your valuable suggestions.
trigger ChildCount on Contact (after insert,after delete,after update,after undelete) { set<id> accid=new set<id>(); if(trigger.isInsert|| trigger.IsUpdate|| trigger.isUndelete) { for(Contact con:trigger.new) { accid.add(con.AccountId); } } if(trigger.isDelete|| trigger.IsUpdate) { for(Contact Con: trigger.old) { accid.add(con.AccountId); } } list<Account> aclist=[select id, Open_Contact_Count__c,(Select id from Contacts) from Account where id in: accid]; List<Account> acupdate=new list<Account>(); for(Account acc: aclist) { list<contact> clist= acc.Contacts; Account a1=new Account(); Contact c1=new Contact(); a1.Id=acc.Id; a1.Open_Contact_Count__c = clist.size(); acupdate.add(a1); } update acupdate; }
cheers
All Answers
cheers
trigger ContactSumTrigger on Contact (After insert, After delete, After undelete) {
Set<Id> parentIdsSet = new Set<Id>();
List<Account> accountListToUpdate = new List<Account>();
IF(Trigger.IsAfter){
IF(Trigger.IsInsert || Trigger.IsUndelete){
FOR(Contact c : Trigger.new){
if(c.AccountId!=null){
parentIdsSet.add(c.AccountId);
}
}
}
IF(Trigger.IsDelete){
FOR(Contact c : Trigger.Old){
if(c.AccountId!=null){
parentIdsSet.add(c.AccountId);
}
}
}
}
System.debug('#### parentIdsSet = '+parentIdsSet);
List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);
FOR(Account acc : accountList){
List<Contact> contactList = acc.Contacts;
acc.Number_of_Contacts__c = contactList.size();
accountListToUpdate.add(acc);
}
try{
update accountListToUpdate;
}catch(System.Exception e){
}
}
It might help you.