I got a field on a parent object used to store count for child's record. I want it to update its own value whenever the child's record are inserted or deleted.what will be the possible code for that ,should I write a trigger or I can achieve this with formula field .
2 Answers
If the relationship between the parent and Child is master/detail you can use a roll up summary field, with the aggregation type of Count. This would be your best option. If it is a lookup relationship, you would need to create a trigger on the child record that would traverse to the parent, then count all of the children and then update the parent. A formula field would not work. If you are new to coding, I would suggest that you use the master/detail roll up if at all possible, and if not, I would recommend that you leverage the DLRS (Declarative Lookup Rollup Summary) package developed by Andrew Fawcett (https://developer.salesforce.com/page/Declarative_Rollup_Summary_Tool_for_Force.com_Lookup_Relationships) which provides a somewhat automated way to do this, without writing your own code.
You can write a trigger for this. Check my trigger code i used for the same. i update one custom field on account object which counts the total number of contacts related to account object. if you need more help then let me know.
trigger CountContactsnew on Contact (after insert,after delete, after Undelete,after update) {
List acclistid = new List();
if(Trigger.isInsert || Trigger.isUndelete){
for(Contact con : Trigger.new){
acclistid.add(con.accountid);
}
}
if(Trigger.isDelete){
for(Contact con :Trigger.old){
acclistid.add(con.accountid);
}
}
if(Trigger.isUpdate){
for(Contact con :Trigger.old){
acclistid.add(con.accountid);
}
}
List<Account> acclist = new List<Account>();
for(Account acc : [select Contact_Recs__c ,(select id from Contacts)from Account where id =: acclistid]){
acc.Contact_Recs__c = acc.Contacts.size();
acclist.add(acc);
}
try{
update acclist;
}Catch(Exception e){
system.debug('Exception :'+e.getMessage());
}
}