function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Hermann Ouré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 :
User-added imageOrder added to Account

User-added image

Chiffre_d_affaire__c  overwritten with Order TotalAmount

User-added image

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;
}

 
Kritika RajKritika Raj
SUM(TotalAmount) amt will return you 85000 , and then you are just assigning this value in Chiffre_d_affaire__c , hence instead of Adding/Subtracting its replacing . First you need to have the value of Chiffre_d_affaire__c and then add/subtract . Like if i = 10 and you want to add 15 to i , then you write : i = i + 15 which will increment i to 25 but if you write i = 15 then the value of i will be replaced from 10 to 15.  
vishal-negandhivishal-negandhi

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