0

I have a triggerHandler on the Opportunity object which inserts other objects on afterInsert if it meets the criteria (Opportunity Line Item and Payment). The objects are added to a list before inserting but when the first list is inserted the next list is emptied/nulled so nothing is being inserted on the next list.

The instantiation of the lists looks like this:

static List<Membership__c> membershipsToUpdate;
static List<Case> casesToUpdate;
static List<OpportunityLineItem> oppItemsToInsert;
static List<npe01__OppPayment__c> paymentsToInsert;

public TRG_OpportunityHandler(){
    membershipsToUpdate = new List<Membership__c>();
    casesToUpdate = new List<Case>();
    oppItemsToInsert = new List<OpportunityLineItem>();
    paymentsToInsert = new List<npe01__OppPayment__c>();
}

And the inserts look like this:

  if(paymentsToInsert.size() > 0) {
        insert paymentsToInsert;
    }
    if(oppItemsToInsert.size() > 0) {
        insert oppItemsToInsert;
    }
    if(membershipsToUpdate.size() > 0) {
        update membershipsToUpdate;
    }
    if(casesToUpdate.size() > 0 ){
        update casesToUpdate;
    }

If I switch place and insert oppItemsToInsert before paymentsToInsert then oppItems are inserted but not payments. Is it really not possible to do 2 DML transactions in one trigger? How else can I do this?

  • There is nothing stopping you from doing as many DML statements as the Governor allows, multiple inserts are absolutely common. If the snippets you gave are all that is happening to the lists, then it should work. Any error messages? – Florian Heer Aug 26 '19 at 12:37
  • There are no errors. The lists just goes blank. I just noticed that both the lists go blank after the first DML statement. Here is a screenshot of the logs when debuggging both lists before and after each insert transaction: prntscr.com/oxnuhp – Andegosu Aug 26 '19 at 13:00
  • Ok I just noticed the problem looking at my own debug logs from the screenshot. Opportunity update is run which causes the list to be reistantiated in the constructor which resets the list. – Andegosu Aug 26 '19 at 13:02
  • Without more context it's hard to say what is happening. How do the oppItemsToInsert and paymentsToInsert get filled? We've seen part of your trigger handler, but what does the trigger itself look like? – nbrown Aug 26 '19 at 13:05
0

Moving the instantiation from the constructor of the handler to inside the afterInsert trigger method solved it. Since the trigger was firing again with an update it reinstatiated the lists and nulled them: http://prntscr.com/oxnuhp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.