I'm trying to write an apex code to update a custom currency field Order_Grand_Total__c
on my Account Records to display the sum of all orders under that particular Account.
Here's my Account Trigger:
trigger SumOrders on Account (after insert, after update) {
List<Order> orderList = [SELECT id, TotalAmount, AccountId FROM ORDER WHERE AccountId IN: Trigger.newMap.keySet()];
for (Account a : Trigger.new)
{
for (Order o : orderList)
{
if (a.id == o.AccountId && orderList.size() > 0)
{
a.Order_Grand_Total__c += o.TotalAmount;
}
}
}
}
And my Test class, which is only covering 57% of the code (4/7):
@IsTest
public class SumOrders {
static testmethod void insertAccount() {
Account a = new Account();
a.Name = 'AJ Kreuer2';
a.Last_Name__c = 'Kreuer2';
a.Email__c = '[email protected]';
insert a;
}
static testmethod void insertOrder() {
Order o = new Order();
o.AccountId = '0013B000004Llt6';
o.Order_ID__c = '0001';
o.Status = 'Draft';
o.EffectiveDate = Date.Today();
insert o;
}
}
The end result is the custom field remains blank:
I'm a bit new to Salesforce and Apex coding so not really sure where to go from here, any ideas? Or is there a simpler way of achieving this?
EDIT:
I've also tried adding a Rollup Summary with the following settings:
However, the Real Time calculation doesn't seem to work, I have to manually click calculate to get the field to populate / update the current order amount on Account Records