You need to sign in to do that
Don't have an account?
Denyel's Dev
Apex Trigger to Count Related Records
Lowly Admin here who doesn't know a bit of code...I have a custom object Location__c and I need to count the number of Products (Standard object called Product2) associated with that Location. I want the total to appear in a field on the Location object called Current_Lot_Inventory. Would any of you gracious developers be willing to help me out with the Apex needed?
Please use below updated code:
This code is working for me.
Regards,
Ramakant
All Answers
Assuming the Location__c and Product 2 are related to each other through a lookup, you can tweak the below code to suit your requirement
trigger Test on Product2 (after insert, after update) {
Set<Id> LocId = new Set<Id>();
integer no_of_products;
Location__c Loc = new Location__c();
for(Product2 P:trigger.new){
no_of_products = [Select count() from Product2 where LocationId :=P.LocationId];
Loc = [select Id from Location__c where Id:=LocationId];
Loc.Current_Lot_Inventory=no_of_products;
}
update Loc;
}
Hope this helps! Good Luck!
Cheers,
Aparna Hegde
Assuming that there is lookup relationship between Location__c and Product2 and on Product2 there is Lookup Field with API Name Location_c.
Please use below code to achieve this :
Hope this will work. Please let me know if helped by marking best answer.
Regards,
Ramakant
I tried to add this as a Trigger on the Location object but I got the following:
Error: Compile Error: A non foreign key field cannot be referenced in a path expression: Location__c at line 8 column 35
Please use below updated code:
This code is working for me.
Regards,
Ramakant
Your Trigger should be fired on DML operation on Products because you need a count of products so we need to write a trigger on your Product.
Regards,
Ramakant
It will not update the count on parent