0

Here's what I have.

Basically, if an opportunitylineitem is deleted, before it gets delete I need the probability field on opportunity to be set to 99. I can't seem to get it to work. What am I missing?

trigger BeforeDeleteProbability on OpportunityLineItem (before delete) {
    Set<Id> oppIds = new Set<Id>();
    for (OpportunityLineItem oli:trigger.old){
        oppIds.add(oli.opportunityId);
    }

    Map<Id, Opportunity> oppstoUpdate = new Map<Id, Opportunity>([Select Id, probability From Opportunity where id in: oppids]);
    for(OpportunityLineItem oli: Trigger.old){
        oppstoUpdate.get(oli.OpportunityId).probability = 99;
    }

    try {
        update oppsToUpdate.values();        
    }
    catch(Exception Ex){
        system.debug(Ex);
    }
}
1
  • 1
    I've taken the liberty of tidying up your code here to be consistent in style and indentation (and that did involve removing some completely blank lines). Well-formatted code helps other people read your code, which makes it easier for people to answer.
    – Derek F
    Commented Jul 24, 2019 at 0:35

1 Answer 1

5

If I had to take a guess at what your issue is, I'd say that you're probably getting a Duplicate object in list error.

You're not seeing that error because you are smothering any exceptions you encounter with that try/catch block.

I'd recommend removing the try/catch, or at the very least adding some additional debugging so that you can see that an exception was encountered in your debug logs.

You also don't need to query for the Opportunity records to update them. You can take advantage of the SObject constructor allowing you to specify the Id.

Getting back to my suspected error, you can solve that by using a Map<Id, Opportunity> to store the Opportunity records that you're trying to update.

All in all, your trigger might end up looking like this

Map<Id, Opportunity> oppstoUpdate = new Map<Id, Opportunity>();
for(OpportunityLineItem oli: Trigger.old){
    oppstoUpdate.put(oli.OpportunityId, new Opportunity(Id = oli.OpportunityId, Probability = 99));
}

// DML won't work on a Map directly, so we need to get a list of the values
//   contained in the map, and give that to the DML operation instead.
// Since we're using a Map here, we should be guaranteed to not run into a
//  "duplicate value in list" error
update oppsToUpdate.values();

You must log in to answer this question.

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