Skip to main content
Question about Assigning column values in a list to new Records in a custom Objectactual code:

trigger OpportunityTrigger on Opportunity (after update) {

    for(Opportunity opp : Trigger.new){

        if(opp.StageName == 'Closed/Won' && Trigger.oldMap.get(opp.Id).StageName != 'Closed/Won') {

        Invoice__c firstInvoice = new Invoice__c();

        firstInvoice.Amount__c =opp.Amount * 0.5;

        firstInvoice.Opportunity__c = opp.Id;

       

        Invoice__c secondInvoice = new Invoice__c();

        secondInvoice.Amount__c = opp.Amount * 0.5;

        secondInvoice.Opportunity__c = opp.Id;

           

        Invoice__c thirdInvoice = new Invoice__c();

        thirdInvoice.Amount__c = opp.Amount * 0.2;

        thirdInvoice.Opportunity__c = opp.Id;

           

            insert new List<Invoice__c>{firstInvoice, secondInvoice, thirdInvoice};

        }

    }

}

How do I now loop through the created List and create the new records in my custom Invoice Object with the values based on the Opportunity stage name changing to Closed/Won?
2 个回答
  1. 2020年12月25日 20:56
    Nevermind, i found it out. I had to replace the text to be the below:

    trigger OpportunityTrigger on Opportunity (after update) {

        List<Invoice__c> newInvoices = new

        List<Invoice__c>();    

        for(Opportunity opp : Trigger.new){

            if(opp.StageName == 'Closed Won' && Trigger.oldMap.get(opp.Id).StageName != 'Closed/Won') {

            Invoice__c firstInvoice = new Invoice__c();

            firstInvoice.Amount__c = opp.Amount * 0.5;

            firstInvoice.Opportunity__c = opp.Id;

            newInvoices.add(FirstInvoice);

                

            Invoice__c secondInvoice = new Invoice__c();

            secondInvoice.Amount__c = opp.Amount * 0.5;

            secondInvoice.Opportunity__c = opp.Id;

            newInvoices.add(SecondInvoice);

                

            Invoice__c thirdInvoice = new Invoice__c();

            thirdInvoice.Amount__c = opp.Amount * 0.2;

            thirdInvoice.Opportunity__c = opp.Id;

            newInvoices.add(ThirdInvoice); 

                

            }

            }

        insert newInvoices;

    }

    Obviously, if it equals Closed Won and the prior value did not equal 'whatever', then i want it to create the three invoice records