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

trigger for count in lookup relationship
I I have two custom obj one is called Parent and the other Child..lookup relationship exists between the two obj..i want to count the child records for each parent and update it in a field named "ContactsCount"..I facing some exception error when tryin to insert Child records..below is the code
trigger ConCount on Child__c (after insert) { Set <id> CHildIds = new set<id>(); List<Child__c> ChildList = new List<Child__c>(); List<Child__c> ListCon = new List<Child__c>(); List<Parent__c> ParentList = new List <Parent__c>(); List<Parent__c> ListParent = new List <Parent__c>(); Map<id,integer> ConMap = new map <id,integer>(); if(Trigger.isInsert){ for(Child__c Chil : Trigger.New){ CHildIds.add(Chil.Parentlookup__c);} ParentList = [select id, name from Parent__c where id IN :CHildIds]; ChildList = [select id,name , Parentlookup__c from Child__c where Parentlookup__c IN :CHildIds]; for(Parent__c P :ParentList){ Listcon.clear(); for(Child__c C : ChildList){ if(C.Parentlookup__c == P.id){ ListCon.add(C); ConMap.put(P.id,ListCon.size()); } }} if(ParentList.size()>0){ for(Parent__c Pa : ParentList){ if(ConMap.size()>0){ Pa.ContactsCount__c = ConMap.get(Pa.id); ListParent.add(Pa); }}} if(ListParent.size()>0) update ListParent; }}
Please find the below code :
Apex Trigger Apex Class
It will also work if some child parent gets changed or child gets deleted.
Thanks
Pranav
All Answers
Please check below code and update your code
Let us know if this will help you
Try the below Code.
trigger ConCount on Child__c (after insert) {
for(Parent__c Parent:Trigger.New){
List<Child__c> ChildList = [select id from Child__c where Parentlookup__c=:Parent.Id];
Integer Count = ChildList.Size();
Parent.ContactsCount = Count;
update Parent;
}
}
\
Thanks
Vinuthh S
Please find the below code :
Apex Trigger Apex Class
It will also work if some child parent gets changed or child gets deleted.
Thanks
Pranav