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
Lakshmi SLakshmi S 

Can we use more if conditions in before insert or update trigger handler class?

Hi Team,

Can we use more if conditions in before insert or update trigger handler class?
Example
-----------------
public with sharing class A {
     public static void beforeInsert(List<ObjectA> objA){
    
      for(ObjectA ob : objA){

       if(condition){
        
        }
         else
         {
         }
         if(condition){
             if(codition)
                    {
                    }
          }
        }

    }

}


Please Advise..

Thanks in Advance
Lakshmi S.
Andrew GAndrew G
Short answer is YES

The only thing to consider is to be consistent/deliberate with your formating so that the code is easier to read:
Example 1:
public with sharing class A {
		public static void beforeInsert(List<ObjectA> objA){
	
		for(ObjectA ob : objA){

			if(condition){
				//some action
			} else {
				//some else action
			}
			if(condition){
				if(condition) {
					//my nested IF action
				}
			}
		}

	}
Example 2:
    public with sharing class A 
	{
		public static void beforeInsert(List<ObjectA> objA){
	
		for(ObjectA ob : objA)
		{
			if(condition)
			{
				//some action
			} 
			else 
			{
				//some else action
			}
			if(condition)
			{
				if(condition) 
				{
					//my nested IF action
				}
			}
		}

	}
I prefer Example 1, but at time have used the second where the code has become quite convoluted.

HTH

Andrew

 
Deepali KulshresthaDeepali Kulshrestha
Hi Lakshmi,

Yes, you can use multiple if conditions in the trigger handler class as I have done it in my  Org here is my code which i have done and it worked fine.
Please saw the given code and use it according to you.

public class OpportunityTriggerHandler {
    public static void opportunity_AfterinsertHandler(List<Opportunity> OpportunityList){
        OpportunityTriggerHandler.createContact(OpportunityList,null);
    }

    public static void opportunity_BeforeUpdateHandler(List<opportunity> OpportunityList, Map<id, opportunity>oldmap){
        OpportunityTriggerHandler.createContact(OpportunityList,oldmap);
    }
    /*Below method is for creating contact*/
    public Static void createContact(List<opportunity> OpportunityList,Map<id,opportunity>oldmap){
        try{
            List<Contract>ContractList= new List<Contract>();
            List<Contract> ContractsCancelled=new List<Contract>();
            Set<Id>OpportunityIdSet=new Set<Id>();
            Set<Id>AccountIdSet= new Set<Id>();
            List<Account>AccountList= new List<Account>();
            Set<String>EmailSet= new Set<String>();
            String EmailBody = '';
            String EmailSubject = '';
                if(oldmap != null){
                    For(Opportunity OppObj: OpportunityList){
                    EmailBody = 'Opportunity is Stage is setted to closed won';
                    EmailSubject = 'Opportunity Stage is Changed';
                        if(OppObj.StageName!=oldmap.get(OppObj.Id).StageName) {
                            if (OppObj.StageName == 'closed won') {
                                Contract ContractObj = new Contract();
                                ContractObj.StartDate = OppObj.CloseDate ;
                                ContractObj.ContractTerm = 12;
                                ContractObj.OwnerExpirationNotice = '60';
                                ContractObj.Status = 'Draft';
                                ContractObj.Opportunity__c = OppObj.Id;
                                ContractObj.AccountId = OppObj.AccountId ;
                                ContractList.add(ContractObj);
                                AccountIdSet.add(oppObj.AccountId);
                            } else if (OppObj.StageName == 'Closed Lost') {
                                OpportunityIdSet.add(OppObj.Id);
                            }
                        }
                    }
                }else{
                    For(Opportunity OppObj: OpportunityList) {
                        EmailBody = 'new Opportunity is Created with Stage closed won';
                        EmailSubject = 'Opportunity Created';
                        if (OppObj.StageName == 'closed won') {
                            Contract ContractObj = new Contract();
                            ContractObj.StartDate = OppObj.CloseDate ;
                            ContractObj.AccountId = OppObj.AccountId ;
                            ContractObj.ContractTerm = 12;
                            ContractObj.OwnerExpirationNotice = '60';
                            ContractObj.Status = 'Draft';
                            ContractObj.Opportunity__c = OppObj.Id;
                            ContractList.add(ContractObj);
                            AccountIdSet.add(oppObj.AccountId);
                        }
                    }
                }
                if(!OpportunityIdSet.isEmpty()){
                    ContractsCancelled=[SELECT Id,Status FROM Contract WHERE Opportunity__c IN :OpportunityIdSet ];
                    for(Contract ContractObj : ContractsCancelled){
                        ContractObj.Status = 'cancelled';
                    }
                }
                AccountList = [SELECT Id, Owner.Email FROM Account WHERE Id IN : AccountIdSet];
                for(Account AccObj : AccountList){
                    EmailSet.add(AccObj.Owner.Email);
                }
                if(!EmailSet.isEmpty()){
                    List<String>EmailList = new List<String>();
                    EmailList.addAll(EmailSet);
                    sendEmail_Apex(EmailList, EmailBody, EmailSubject);
                }
                System.debug('>>>>>>>>>>>>>ContractList'+ContractList);
                if(ContractList.size() > 0){
                    upsert ContractList;
                }
                if(ContractsCancelled.size() > 0){
                    upsert ContractsCancelled;
                }
        }catch (Exception ex){
            system.debug('ERROR :'+ex.getMessage()+'at Line : '+ex.getLineNumber());
        }
    }

    /*method to send Email*/
    public static void sendEmail_Apex(List<string> sendToList,String emailBody,String emailsubject){
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        if(!sendToList.isEmpty() && emailBody != null && emailsubject != null){
            mail.setToAddresses(sendToList);
            mail.setReplyTo(UserInfo.getUserEmail()); // change it with your mail address.
            mail.setSenderDisplayName(UserInfo.getName());
            //mail.setTargetObjectId(contact.Id);
            mail.setSaveAsActivity(true);
            mail.setSubject(emailsubject);
            mail.setHtmlBody(emailBody);
            //mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
            mails.add(mail);
        }
        if(!mails.isEmpty()){
            Messaging.sendEmail(mails);
            System.debug('Mail sent.');
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha