I am having an issue with a trigger which i have put together using a couple of similar posts.
It fires on an Order, to update a field called Outstanding_Balance__c on the Order's Account, which should collect all outstanding balances from all associated Orders.
The field on the order is a Roll Up Summary, called Outstanding_Balance__c.
There is no validation, and both the Order and the Account can be updated manually (any mandatory fields are fulfilled.
The trigger successfully updates the Account field if I simply replace the line -
acc.Outstanding_Balance__c = 0.00;
with
acc.Outstanding_Balance__c = 2.00;
So it is firing correctly, otherwise, the Outstanding_Balance__c field on Account isn't being calculated. It seems the following line is not working as intended.
acc.Outstanding_Balance__c += ord.Outstanding_Balance__c;
Full code:
trigger OrderTrigger on Order (After insert, After update, After delete, After undelete){
Set<id> AccountIds = new Set<id>();
If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
for (Order ord : Trigger.new){
AccountIds.add(ord.AccountId);
}
}
If(Trigger.IsDelete){
For(Order ord: Trigger.Old){
AccountIds.add(ord.AccountId);
}
}
List<Account> accsToUpdate = New List<Account>();
For(Account acc : [SELECT Id,Name,Outstanding_Balance__c,Sales_Order_Count__c,(
SELECT id,name,Outstanding_Balance__c FROM Orders__r) FROM Account WHERE Id IN :AccountIds]) {
{
acc.Outstanding_Balance__c = 0.00;
for(Order ord: acc.Orders__r) {
acc.Outstanding_Balance__c += ord.Outstanding_Balance__c;
acc.Sales_Order_Count__c = acc.Orders__r.size();
}
accsToUpdate.add(acc);
}
try{
update accsToUpdate;
}
catch(Exception E){
system.debug('Error thrown is: ' + E.getMessage());
}
}
}