You need to sign in to do that
Don't have an account?
Hermann Ouré
stop Apex Trigger overwriting a custom field
Hello,
I have created a trigger to update a custom field called "Chiffre_d_affaire__c". Anytime an Order with the status 'Activated' is added to an account. The amount of the order should be added to the field "Chiffre_d_affaire__c".
So let's say my : Chiffre_d_affaire__c = 100 000.00 ;
Order (TotalAmount) = 85 000.00 ;
the Chiffre_d_affaire__c should be updated to 185 000.00
But instead of adding to amount of the order to Chiffre_d_affaire__c;
The Trigger overwrite the 100 000.00 in Chiffre_d_affaire__c with the Order.
So Chiffre_d_affaire__c is updated with 85 000.00
How can I fix it?
Thanks
Initial Chiffre_d_affaire__c :
Order added to Account
Chiffre_d_affaire__c overwritten with Order TotalAmount
my trigger:
I have created a trigger to update a custom field called "Chiffre_d_affaire__c". Anytime an Order with the status 'Activated' is added to an account. The amount of the order should be added to the field "Chiffre_d_affaire__c".
So let's say my : Chiffre_d_affaire__c = 100 000.00 ;
Order (TotalAmount) = 85 000.00 ;
the Chiffre_d_affaire__c should be updated to 185 000.00
But instead of adding to amount of the order to Chiffre_d_affaire__c;
The Trigger overwrite the 100 000.00 in Chiffre_d_affaire__c with the Order.
So Chiffre_d_affaire__c is updated with 85 000.00
How can I fix it?
Thanks
Initial Chiffre_d_affaire__c :
Order added to Account
Chiffre_d_affaire__c overwritten with Order TotalAmount
my trigger:
trigger UpdateAccountCA on Order (after update, before delete) { Set<Id> accountIds = new Set<Id>(); if(Trigger.isUpdate) { //Iterate through each Order for(Order o : Trigger.new) { accountIds.add(o.AccountId); } } else if(Trigger.isDelete) { for(Order o : Trigger.old) { accountIds.add(o.AccountId); } } AggregateResult[] groupedResults = [SELECT AccountId, SUM(TotalAmount)amt FROM Order WHERE AccountId In : accountIds AND Status = 'Activated' GROUP BY AccountId]; List<Account> toBeUpdateAccount = new List<Account>(); for(AggregateResult Results: groupedResults) { Account acc = new Account(); acc.Id = (id) Results.get('AccountId'); acc.Chiffre_d_affaire__c = (Decimal)Results.get('amt'); toBeUpdateAccount.add(acc); } update toBeUpdateAccount; }
Hello Hermann,
Your code looks alright to me.
Can you add a debug statement just before you assign "(Decimal)Results.get('amt');" to see what value are you getting here?
I had a look and also ran a similar snippet in my org and it worked fine for me.
Please share what you find as it could be helpful for others.
Best,
Vishal