As a part of a larger project surrounding Apex triggers, I need to move what was functional code from a before update trigger on the lead object to a trigger handler called by a trigger on the Lead object.
While working through this I am struggling with how to best update OwnerID and Reassignment_Status__c (see the two if statements in the code below, I know that the LD variable does not exist).
In addition, I would like to get feedback regarding the overall structure of how this is written because:
I'm concerned that the way that I am using the SELECT statements here may be inefficient
I have another project upcoming in which the plan is to leverage after an after delete trigger handler to grab values from merged lead records and insert them into a custom object. How/whether I am able to address the issues with the handler I am posting about here will inform how I approach that task as well.
Below is my current code.
public void OnBeforeUpdate( List<Lead> newLead, List<Lead> oldLead, Map<ID, Lead> newLeadMap , Map<ID, Lead> oldLeadMap )
{
system.debug('Lead Trigger On Before Update ');
try
{
Set<Id> ldIdSet = new Set<Id>(); //Initialize set of LeadIDs
List<Lead> ldList = new List<Lead>(); //Initialize list of lead records for update
List<ProcessInstance> piList = new List<ProcessInstance>(); //Initialize list of approval process items
ldList = [SELECT Id, OwnerID, Reassignment_Status__c FROM Lead WHERE Id IN :ldIdSet];
piList = [SELECT SubmittedById,SystemModstamp,TargetObjectId, Status, (SELECT ID, ProcessNodeId, StepStatus, Comments,TargetObjectId,ActorId,CreatedById,IsDeleted,IsPending, OriginalActorId,ProcessInstanceId,RemindersSent,CreatedDate
FROM StepsAndWorkitems ) FROM ProcessInstance pi WHERE pi.TargetObjectId IN :ldIdSet order by createddate DESC limit 1];
if(ldList.size() > 0) {
for(Lead l : ldList)
{
ldIdSet.Add(l.Id); //Add Ids from ldList to the LeadID set list
}
If (ldList[0].Reassignment_Status__c == 'Pending' && piList[0].Status == 'Approved') //Update Owner to the approval process requestor
{
LD.OwnerId = piList[0].SubmittedById;
LD.Reassignment_Status__c = '';
system.debug('Reassignment Approved - Owner Changed from '+ldList[0].OwnerId+'to ' +piList[0].SubmittedById);
}
If (ldList[0].Reassignment_Status__c == 'Pending' && piList[0].Status == 'Rejected') //Clear the reassignment status indicator, make no change to Owner
LD.Reassignment_Status__c = '';
system.debug('Reassignment Rejected - Owner not changed');
}
}
catch(Exception e)
{
system.debug('The following exception has occured:' +e.getMessage());
system.debug('The following Line:' + e.getLineNumber());
}
}