0

I have to implement same logic x=y+z for after insert and after update trigger on an object. Unfortunately I cannot make use of context variables as our prototype for trigger handler is defined long ago and they have not taken these into considerations. So I am planning to implement the logic in a method in the below way. Please let me know if this is the correct way or suggest if there is any better way of doing this.

public void Samelogic(Map<..> oldMap, Map<..> newMap){
  //Local variable flag
  boolean flag = 0;
  //After Insert
  if(oldMap.isEmpty()){
    if(condition1){ flag =1;}
  }
  //After update
  else{
    if(conditon2){ flag =1;}
  }

  if(flag ==1){
    //Perform common logic
    x=y+z;
  }
}

1 Answer 1

1

Your code won't work as you expect: oldMap is null in an insert trigger, and will crash with a NullPointerException. You might want to just go with a switch statement:

Boolean doAction = false;
switch on Trigger.operationType {
  when AFTER_INSERT {
    doAction = condition1;
  }
  when AFTER_UPDATE {
    doAction = condition2;
  }
}
if(doAction) {
  x = y + z;
}

Trigger context variables are available in classes, so long as you're actually in a trigger context (between a DML_BEGIN and a DML_END). And the if statements are not always necessary; you can always assign the result of using Boolean operators to a Boolean variable.

2
  • Thanks for the solution. Just checking with you again, it means that i need not to explicitly pass this Trigger.operationType from trigger handler?
    – Kanikala
    Commented Sep 14, 2018 at 3:22
  • @Kanikala correct. If you're using a framework of any sort, and you don't know why you're doing it this way, you need to do some research and/or ask more questions.
    – sfdcfox
    Commented Sep 14, 2018 at 3:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .