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
Kon DeleKon Dele 

How can I move the following trigger logic into an apex class?

How can I remove logic from the following trigger into an apex class?
trigger AssignAccNumber on Opportunity(before insert,before update){
    
    List<Id> accIds = new List<Id>();
    
    for(Opportunity opp:trigger.new){
        
        if(opp.AccountId!=null){
            
            accIds.add(opp.AccountId);
        }
    }
    
    Map<Id,Account> accMap = new Map<Id,Account>([SELECT id,Area__c,AccountNumber,Type FROM Account WHERE id in:accIds]);
    Account a = [SELECT AccountNumber FROM Account WHERE AccountNumber != null AND Type='Prospect' AND Area__c='East' ORDER BY AccountNumber DESC LIMIT 1];
    
    for(Opportunity opp :Trigger.new){
     Account accs = accMap.get(opp.AccountId);       
        
	if(!accMap.IsEmpty()){
            
            if(opp.Probability == 95 && accs.AccountNumber == null){
                
                if(accs.LC_Market__c == 'Americas' && accs.Type == 'Prospect'){
                    
                    accs.AccountNumber = String.valueOf(Integer.valueOf(a.AccountNumber)+1);
                }            
            }
            update accMap.values();
        }
    }            
}

 
Best Answer chosen by Kon Dele
Steven MellerSteven Meller
Kon,
declare the public class and public static method, then invoke the method by passing in the opp object handle.

public class TriggerTest {
    public static void addAcctId (Opportunity opp) {    
    List<Id> accIds = new List<Id>();
            
        if(opp.AccountId!=null){
            
            accIds.add(opp.AccountId);
        }
....

and in the trigger, where opp comes from  :trigger.new
for (Opportunity opp : trigger.new ) {
TriggerTest.addAcctId( opp );
}
 

All Answers

Steven MellerSteven Meller
Kon,
declare the public class and public static method, then invoke the method by passing in the opp object handle.

public class TriggerTest {
    public static void addAcctId (Opportunity opp) {    
    List<Id> accIds = new List<Id>();
            
        if(opp.AccountId!=null){
            
            accIds.add(opp.AccountId);
        }
....

and in the trigger, where opp comes from  :trigger.new
for (Opportunity opp : trigger.new ) {
TriggerTest.addAcctId( opp );
}
 
This was selected as the best answer
James LoghryJames Loghry
Kon,

Force.com MVP Kevin O'Hara has created a framework to handle exactly this.  Visit his github project here: https://github.com/kevinohara80/sfdc-trigger-framework.  Follow the instructions in the README and you'll find moving your logic outside of your trigger isn't as complicated as you may think.