I am looking to replace the rollups in my Salesforce rollup helper with apex versions, and run those instead. I am trying to transform the following into Apex code. Please let me know if you have any ideas.
Asked
Active
Viewed 245 times
1 Answers
0
This is a very straight forward use case for Apex. You need to create a Trigger on the child object that will do the math and update the parent object. Best Practices dictate that the Trigger should actually call a method in a class, but here is an abbreviated version of the solution:
trigger myTrigger on Collateral__c (after insert, after update){
Map<Id, Deal__c> dealMap = new Map<Id, Deal__c>();
for ( Collateral__c c : Trigger.new ){
dealMap.put( c.Deal__c, new Deal__c( Id=c.Deal__c, Total_Lendable_Collateral__c=0) );
}
for ( AggregateResult ar : [
SELECT Deal__c parentId, SUM(Lendable_Value__c) s
FROM Collateral__c
WHERE Deal__c IN :dealMap.keySet()
]){
Id i = (Id)ar.get('parentId');
dealMap.put( i, new Deal__c(Id=i,Total_Lendable_Collateral__c=(Decimal)ar.get('s')));
}
update dealMap.values();
}

Matt Kaufman
- 748
- 4
- 12