0

I wrote a trigger to update the field B with a field A value when we create a record, now I want that field B to update everytime I edit the record. would trigger update the existing record fields ? How to achieve this ? Please look at my code.

Trigger Handler

 public void onAfterInsert(){
            List<HealthCloudGA__CarePlanGoal__c> percent=[select Name, HealthCloudGA__Progress__c, ProgressToCompletion__c, HealthCloudGA__CarePlanProblem__c from HealthCloudGA__CarePlanGoal__c  where Id IN: Trigger.New  ];
            for(HealthCloudGA__CarePlanGoal__c cent:percent){
                if(cent.ProgressToCompletion__c == '0'){
                    cent.HealthCloudGA__Progress__c=0;
                }
                else if(cent.ProgressToCompletion__c == '25%'){
                    cent.HealthCloudGA__Progress__c=0.25;
                }
                else if(cent.ProgressToCompletion__c == '50%'){
                    cent.HealthCloudGA__Progress__c=0.50;
                }
                else  if(cent.ProgressToCompletion__c == '75%'){
                    cent.HealthCloudGA__Progress__c=0.75;
                }
                else   if(cent.ProgressToCompletion__c == '100%'){
                    cent.HealthCloudGA__Progress__c=1.0;
                }
            }
            update percent;  
        }

Trigger

 MCM_GoalTriggerHandler handler = new MCM_GoalTriggerHandler(trigger.new, trigger.old, trigger.newMap, trigger.oldMap);
 if (Trigger.IsUpdate || Trigger.IsInsert)
    {
        
        if (Trigger.IsInsert && Trigger.isAfter ){
            handler.onAfterInsert(); 
        }
  • did you try doing the same using a process builder/flow or a formula field? – SF Ninja Jul 14 at 23:45
  • I tried using workflow/formula field but did not worked cause they both are different field types. ProgressToCompletion__c is Picklist DataType and HealthCloudGA__Progress__c is Percent DataType. @SFNinja – Teja Jul 14 at 23:49
  • 1
    If you want your trigger to work on update, you should run the code on update event as well. But the update actually doesn't really need to run on after event. You should be able to run it on before event and no need to run the soql query. – Hengky Ilawan Jul 15 at 0:21
  • Thanks @HengkyIlawan. It worked with before update Trigger.isBefore and took off the query too .. – Teja Jul 15 at 4:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.