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
Edgar MacachorEdgar Macachor 

sum of a field using apex trigger

Hi help guys! I am really new in salesforce and also in Apex. I have to create an Apex Trigger to get the sum of a field. my components are:
Hi help guys! I am really new in salesforce and also in Apex. I have to create an Apex Trigger to get the sum of a field. my components are:
1.  Price - custom object
The fields of Price are:
  • Discount Line (currency field type)
  • Discount Price (currency field type)
2. Products - custom object
3. Sale - custom object
The fields of Sale are:
  • Status (Picklist: Draft, For Approval, Active)
  • Min Sale Amount (currency)
  • Min Sale Quantity (number)
  • Discount Sale (currency)
Record type for Sale:
  • Row Stage
  • Column Stage
Both Products and Sale has data imported to each object it contains the Product 
So the instruction is to get the sum for Discount Line and Discount Price. The formula is:
Discount Line = ​​​​​​Sum of ACTIVE applied discounts for Column Stage Sale
Discount Price= 
Sum of ACTIVE applied discounts for Row Stage Sale
Both custom object has no relationship to each other. The event is before insert, before update. Please help me guys. Ask me for clarifications. Thank you.

​​​​​​​
Edgar MacachorEdgar Macachor
Hi Suraj Tripathi 47, thanks for the reply, but I am getting the problem: Invalid loop variable type expected Price__c was Sale__c on line 5.
 
Suraj Tripathi 47Suraj Tripathi 47

Hi Edgar Macachor,

Please try this code for Insert Only because for an update there needs to be a relationship between Sale and Price.

trigger SumDiscount on Sale__c (After insert,After Update) {
   if(trigger.isAfter && trigger.isInsert){
     List<Sale__c> saleList=new List<Sale__c>([select id,RecordType.Name,Status__c,Discount_Sale__c  from Sale__c where id in: trigger.new]);

        Double sumDL=0;
        Double sumDP=0;
        for(Sale__c obj:saleList){
            if(obj.Status__c=='Active'){
                 if(obj.RecordType.Name=='Row Stage'){
                     sumDP=sumDP+obj.Discount_Sale__c; 
                }else if(obj.RecordType.Name=='Column Stage'){
                    sumDL=sumDL+obj.Discount_Sale__c;
                    
                }
             }
        }
         Price__c priceObj=new Price__c();
        priceObj.Name='Test Price';
        priceObj.Discount_Line__c=sumDL;
        priceObj.Discount_Price__c=sumDP;
        insert priceObj;
        
   }
}

Please let me know it is working or not??

If it works don't forget to mark Best Answer.

Thank You