You need to sign in to do that
Don't have an account?
Dritter
Apex Trigger that can't handle null values
I have an object called terms and conditions AND only one record can be active at a time by SBU. Therefore, create a trigger and services class.
trigger
Class methods
My trigger throws an error if my first method getActiveTermsAndConditionsBySBU returns null. I could put a try catch around it to handle the error, but before I try that I have two questions: (1) should I be using List in the methods if the query is only going to return 1 record and (2) does anyone have any recommendations on how to make the code more efficient?
trigger
trigger TermsAndConditionTrigger on Terms_and_Conditions__c (before insert, after update) { if (trigger.isInsert) { for (Terms_and_Conditions__c newtermsAndCondRec : Trigger.new) { List <Terms_and_Conditions__c> ExistingTermsAndCond = EnrollmentAgreementServices.getActiveTermsAndConditionsBySBU(newtermsAndCondRec.SBU__c); EnrollmentAgreementServices.unCheckExistingActiveTermsAndCondBeforeInsert(ExistingTermsAndCond); } } }
Class methods
public static List<Terms_and_Conditions__c> getActiveTermsAndConditionsBySBU (String SBU) { List <Terms_and_Conditions__c> findIfActiveTermsAndCondExistList = [SELECT id, Active__c, SBU__c FROM Terms_and_Conditions__c WHERE SBU__c =: SBU AND Active__c = TRUE]; if(findIfActiveTermsAndCondExistList.isEmpty()) { return null; } else { return findIfActiveTermsAndCondExistList; } } public static void unCheckExistingActiveTermsAndCondBeforeInsert (List <Terms_and_Conditions__c> existTermsAndCond) { List<Terms_and_Conditions__c> oldActiveTermsAndCondToDeactivateList = new List<Terms_and_Conditions__c> (); for (Terms_and_Conditions__c tc :existTermsAndCond) { if (tc.Active__c == TRUE) { tc.Active__c = FALSE; oldActiveTermsAndCondToDeactivateList.add(tc); } } update oldActiveTermsAndCondToDeactivateList; }
My trigger throws an error if my first method getActiveTermsAndConditionsBySBU returns null. I could put a try catch around it to handle the error, but before I try that I have two questions: (1) should I be using List in the methods if the query is only going to return 1 record and (2) does anyone have any recommendations on how to make the code more efficient?
need to remember the gobernor limits. Give it a try and let me know if it works for you.
You can check for existing and deactivate them in the same method.
Wil,