1

I got the below trigger written in a trigger and I need to separate it out to a helper class/trigger dispatcher as a method and call that method in the trigger.

trigger updateOppStage on Proposal__c(after update){
    Set<Id> proposalIds = new Set<Id>();

    for(Proposal__c prp : Trigger.new)
    {
         if(prp.Proposal_Status__c=='Completed')
              proposalIds.add(ac.Id);
    }

     List<Opportunity> oppsToUpdate = new List<Opportunity>();

     for(Opportunity opp : [select id, StageName from Opportunity where ProposalId in: proposalIds])
     {
          opp.StageName='Closed - Won';
          oppsToUpdate.add(opp);
     }

     update oppsToUpdate;
}

How can I put the trigger to a helper class/trigger dispatcher as a method? Thanks in advance.

1 Answer 1

9

You want to extract all logic from your trigger and put it in a helper class. This way, you can create one trigger per object and have a good overview of which object triggers what logic.

First, you create your helper class with the logic from your trigger:

public with sharing class ProposalTriggerHelper {

    public static void updateOpportunityStage(List<Proposal__c> proposals) {
        Set<Id> proposalIds = new Set<Id>();

        for(Proposal__c prp : proposals)
        {
            if(prp.Proposal_Status__c=='Completed')
                proposalIds.add(ac.Id);
        }

        List<Opportunity> oppsToUpdate = new List<Opportunity>();

        for(Opportunity opp : [select id, StageName from Opportunity where ProposalId in: proposalIds])
        {
             opp.StageName='Closed - Won';
             oppsToUpdate.add(opp);
        }

        update oppsToUpdate;
   }
}

Then, you create one single Trigger for your Proposal object, using the trigger variables to define which methods runs for which context:

trigger ProposalTrigger on Proposal__c(before insert, after insert, before update, after update, before delete, after delete, after undelete){
    if(Trigger.isUpdate && Trigger.isAfter){
        ProposalTriggerHelper.updateOpportunityStage(Trigger.new);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .