+ Start a Discussion
TJMeadowsTJMeadows 

Trigger on Opportunity Pricebook change not working when line items are present.

I've got a requirement to automatically add a line item under certain circumstances, one being when new pricebook has been selected. Here's a very basic code snippet to reproduce what I'm seeing:
for(Opportunity oppt : Trigger.new){
    Opportunity oldOppt = Trigger.oldMap.get(oppt.Id);
    system.debug(oppt.Pricebook2Id);
    system.debug(oldOppt.Pricebook2Id);
.
.
.
}

Scenario 1: 
A pricebook is selected but there are 0 OpportuntityLineItem records. Click to change the selected Pricebook and save with the new selection.
The result is that the trigger recognizes the change in the Opportunity's Pricebook2Id.
11:22:48.106 (1136814371)|STATEMENT_EXECUTE|[11]
11:22:48.106 (1136937523)|USER_DEBUG|[11]|DEBUG|01s14000000O8KHAA0
11:22:48.106 (1136951905)|STATEMENT_EXECUTE|[12]
11:22:48.106 (1136994368)|USER_DEBUG|[12]|DEBUG|01sa0000000VjKKAA0

Scenario 2: 
A pricebook is selected but there is at least 1 OpportuntityLineItem record. Click to change the selected Pricebook and save with the new selection.
The result is that the trigger does not recognize the change in the Opportunity's Pricebook2Id.
11:19:54.624 (1650559414)|STATEMENT_EXECUTE|[11]
11:19:54.624 (1650693331)|USER_DEBUG|[11]|DEBUG|01sa0000000VjKKAA0
11:19:54.624 (1650703192)|STATEMENT_EXECUTE|[12]
11:19:54.624 (1650731617)|USER_DEBUG|[12]|DEBUG|01sa0000000VjKKAA0

Scenario 3: 
A pricebook is selected but there is at least 1 OpportuntityLineItem record. Manually delete the line item(s). Click to change the selected Pricebook and save with the new selection.
The result is that the trigger recognizes the change in the Opportunity's Pricebook2Id.​
12:50:21.992 (1017463572)|STATEMENT_EXECUTE|[11]
12:50:21.992 (1017568036)|USER_DEBUG|[11]|DEBUG|01sa0000000VjKKAA0
12:50:21.992 (1017578515)|STATEMENT_EXECUTE|[12]
12:50:21.992 (1017603260)|USER_DEBUG|[12]|DEBUG|01s14000000O8KHAA0

Has anyone ran acrossed this before? Does the automated deletion of line items interfere with the normal trigger flow?