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
Joy___Joy___ 

Apex Trigger - Update Field Values from Order object ?

Hi ! 

Can anyone tell me how to write trigger for this scenario, please ?

On Order object, I have 2 custom fields : 
   - Net_amount__c : is total amount without shipment cost
   - Shipment_cost__c

I would like to update Net_amount__c field. 


My trigger is bellow, but there are many problems :

1) When an order is created :
Total amount : 0
Net_amount__c : 
Shipment_cost__c : 100

2) When an order is updated :
Total amount : 100
Net_amount__c : -50
Shipment_cost__c : 50



trigger CalculMontantTrigger on Order (before update) {
   
    for (Order o: Trigger.new) {
        o.Net_amount__c = o.TotalAmount - o.Shipment_cost__c;
    }
}
Best Answer chosen by Joy___
Omar Rajab 94Omar Rajab 94
the calculation is correct!
Order Amount (TotalAmount): 0,00 
Shipment cost (Shipment_cost__c): 100,00
so TotalAmount - Shipment_cost__c => 0,00 - 100,00 = -100,00

Regards,
Omar

All Answers

Omar Rajab 94Omar Rajab 94
Hi JoyTola, 
I recommend you to use Record-Triggered Flow instead of coding.
Record-Triggered Flow
Anyways try the code below: 
trigger CalculMontantTrigger on Order(before update, before insert) {
    switch on Trigger.OperationType {
        when BEFORE_UPDATE, BEFORE_INSERT {
            for (Order o : Trigger.new) {
                o.Net_amount__c = o.TotalAmount - o.Shipment_cost__c;
            }
        }
    }

}

Thanks, 
Omar
Joy___Joy___
I'm trying something else because it doesn't work :( 

Now, Net_Amount__c is a formula field (TotalAmount - Shipment_cost__c)

When an order is created or a record is delated Net_Amount__c  is negative ...

Please check below :

User-added image
Omar Rajab 94Omar Rajab 94
Can you share us the content of the forumla field?

regards,
Omar
Joy___Joy___
The content of the formula is :

TotalAmount - Shipment_cost__c

User-added image

Regards, 
Joy 
 
Omar Rajab 94Omar Rajab 94
the calculation is correct!
Order Amount (TotalAmount): 0,00 
Shipment cost (Shipment_cost__c): 100,00
so TotalAmount - Shipment_cost__c => 0,00 - 100,00 = -100,00

Regards,
Omar
This was selected as the best answer