+ Start a Discussion
Brie BatesBrie Bates 

Basic Opportunity Trigger to Sum 3 Custom Currency field and place is Total Currency Field

I am new to trigger writing and I need help writing a trigger that sums 3 opportunity amount fields (Item1, Item2, Item 3) and places it in a Custom currency field called  "Total" (opportunity field) any time any of the 3 fields are populated. The user should have the ability to overwrite the custom data and I would like to add a checkbox to essentially disable the trigger if set to true. Can you anyone help me with some base code i can use to create this trigger?
RaidanRaidan
Hi Brie,

Try to use the Process Builder first before writing a trigger. A requirement like this can be resolved easily with a Process Builder.
  • Create a new Process Builder
  • Select Opportunity as the main object, and choose to start when the record is created and edited
  • In the criteria, add the conditions: the 3 fields are edited (IsChanged) 
  • For the action, select Update Records and select the Opportunity
  • Add the Total field, and set the type to Formula
  • You can write your formula as the sum of all three amount fields (pay attention to BLANK value)
Yury BondarauYury Bondarau
Hi Brie,

Try the following code (Pleasae replace tem1, Item2, Item3 with real field names).
 
trigger CalculateSum on Opportunity (before insert, before update) {
    for (Opportunity o: Trigger.new) {
        if (Trigger.isUpdate && o.Amount != Trigger.oldMap.get(o.Id).Amount) { 
            //here we check if Amount have been changed manually
            //ignote automatic update and save value entered by user
    		continue;        
        }
	//please replace Item1__c etc with real field names
        o.Amount = o.Item1__c + o.Item2__c + o.Item3__c;
    }

}