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
Sony PSPSony PSP 

automatically recalculate a field

How to update a field automatically(OPA_Lifetime_Product_Forecast__c) recalculate when a primary is changed. meaning if values from product_is_primary__c  is changed value, it will recalculate the OPA_Lifetime_Product_Forecast__c
public with sharing class AgreementTriggerHandler{
    
    public static void onAfterInsert(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }
    
    public static void onAfterUpdate(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }
    
    public static void onAfterDelete(List<AP_Agreement__c> agrList) {
        isUpdatePanel(agrList);
    }

     public static void onBeforeInsert(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }



    public static void isUpdatePanel (List<AP_Agreement__c> agrList){
        Set<Id> ProjIDs = new Set<Id>();
        List<Project__c> PaneltoUpdate = new List<Project__c>();
        Double pfSum = 0;

         //Get the Project ID
        for(AP_Agreement__c pfs : agrList){
            ProjIDs.add(pfs.Panel__c);
        }
        
        //Checks if there are Projects on the Agreement
        if(!ProjIDs.isEmpty()){
        
            //Loop through Agreement and use the Product Forecast Condition(OPA_Lifetime_Product_Forecast__c) to filter the Primary and Seconadry Series and Panel/Project ID
            for(AP_Agreement__c  pf: [SELECT OPA_Lifetime_Product_Forecast__c, Panel__c  FROM AP_Agreement__c WHERE Panel__c =: ProjIDs]){
                
                //Check if OPA_Lifetime_Product_Forecast__c has a value as MPA records will not have any value here
                if(pf.OPA_Lifetime_Product_Forecast__c!=null){
                pfSum += pf.OPA_Lifetime_Product_Forecast__c;
                }
            }
        
        }


        
         //Update the Project with the summed up quantity from Agreements using the Product Forecast Condtion
        for(Project__c prj: [Select Id from Project__c where Id =: ProjIDs]){
            prj.Allocated_OEM_Project_Forecast__c = pfSum;
            PaneltoUpdate.add(prj);
        }

        //Update the Project
         if(!PaneltoUpdate.isEmpty()){
            update PaneltoUpdate;
        }
    }
}

 
Sudipta DebSudipta Deb
Hi,

There are multiple options available for this scenario - Please accept my solution as Best Answer if my reply is helpful.