0

I have a class method that is assigning a Team to a contact record based on the value from another field. I want to expand this logic so that I don't have to write out multiple methods for each team and use only one method. This logic I have works, but as stated, would need to write multiple methods for each team. Can anyone help?

trigger FUSContactTrigger on Contact (after insert, after update) {

    if(checkRecursive.runOnce())
    {

    //Freshman Team Assignment    
    List<Contact> FreshmanTeam = New List<Contact>();
    List<String> FreshmanTypes = new List<String> { 'U - Senior' , 'U - Senior Transfer', 'U - Transfer', 'U - UG Readmit', 'U - UG Readmit Transfer', 'U - Post-Secondary' };

    for(Contact c: Trigger.New) {
        if(FreshmanTypes.contains(c.TargetX_SRMb__Student_Type__c) && c.Team_Assignment__c != 'Freshman Team') {
            FreshmanTeam.add(c);
        } 
    }

    if(FreshmanTeam.size() > 0) {
    FUSContactController ctrl = New FUSContactController();
    ctrl.FreshmanTeamAssignment(FreshmanTeam);
    }

    }//End Check Recursion

}
public class FUSContactController {

    public void FreshmanTeamAssignment(List<Contact> Contacts) {
        List<Contact> FreshmanTeamAssignment = new List<Contact>();

        for(Contact c : Contacts) {
            FreshmanTeamAssignment.add(new Contact(id=c.id, Team_Assignment__c = 'Freshman Team'));
        }

        if(FreshmanTeamAssignment.size() > 0) {
            update FreshmanTeamAssignment;
        }
    }   

}
  • runOnce() is perhaps the worst possible way to cope with trigger recursion and actively breaks your code in a variety of real-world situations. – David Reed Apr 7 at 16:08
  • Thanks @DavidReed. I am in the process of trying to clean up my org and it was only meant to be temporary. – Alan Apr 7 at 16:13
0

You can use a parameter:

public class FUSContactController {
    public static void FreshmanTeamAssignment(List<Contact> Contacts, String teamName) {
        for(Contact c : Contacts) {
            c.Team_Assignment__c = teamName;
        }
        update FreshmanTeamAssignment;
    }   
}

Note all the optimizations; you don't need to create new records in memory, you don't need a no-op DML guard, and you can use static methods to avoid constructing objects, reducing code use. That's obsolete programming design, as DML operations automatically ignore empty lists.

| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.