You need to sign in to do that
Don't have an account?
Sony 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; } } }
There are multiple options available for this scenario -
- [Preferred Approach]: If you don't have any trigger written for Project__c, go for Salesforce's Declarative Tool - Process Builder. Define the object, filter criteria and then the action to recalculate the OPA_Lifetime_Product_Forecast__c. You can learn about Process Builder -
- https://trailhead.salesforce.com/en/business_process_automation/process_builder
- https://help.salesforce.com/articleView?id=process_overview.htm&type=0
- If you have any existing trigger for Project__c, then write your logic in before update context. Make your trigger bulkified and test the same.
Please accept my solution as Best Answer if my reply is helpful.