function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AtiqahAtiqah 

Create multiple record using trigger

Hi, my scenario I have 3 objects here. payment term credit limit, sales order and vehicle. let's say when users create new payment term records, the vehicle records will auto-populate based on the sales order. This code is working well for after insert only. but is I put After insert and after update, the vehicle records become double (duplicate value)
 
trigger CreateSOonPtcl on Payment_Term_Credit_Limit__c (after insert, after update) {
    set<Id> lstId = new set<Id>();
    set<date> startDate = New set<date>();
    set<date> endDate = New set<date>();
    List <Vehicle__c> vehToInsert = new List <Vehicle__c>(); 
    
    for (Payment_Term_Credit_Limit__c o : Trigger.new) {
        
        //meets the criteria
        if (o.Category__c == 'Increase / Decrease Credit Limit') {
            lstId.add(o.Name_of_Customer__c);
            startDate.add(o.Start_Order_Date__c);
            endDate.add(o.End_Order_Date__c);
        }
    }
    
    list<Sales_Order__c> lstOb1 =[select Id,Requested_Delivery_Date__c, account__c, Name,Po_No__c,Total_Qty_Pcs__c,Total_Amount_USD__c,Currency__c from Sales_Order__c where Account__c IN :lstId AND Status__c = 'E0005 ZSHP' and Order_Date__c >= :startDate and Order_Date__c <= :endDate order by CreatedDate ];
    for (Payment_Term_Credit_Limit__c oo : Trigger.new) {
        for(integer i=0; i<lstOb1.size(); i++){
            Vehicle__c v = new Vehicle__c ();
            v.Payment_Term_Credit_Limit__c = oo.id;
            V.Sales_Order__c = lstOb1[i].Id; 
            
            vehToInsert.add(v);
        }
    }
    
    try {
        insert vehToInsert;	
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}
User-added imageplease help me with this. I think It is because this code in loop
Vehicle__c v = new Vehicle__c ();


 
Best Answer chosen by Atiqah
PriyaPriya (Salesforce Developers) 
Hey Atiqah,

If your requirement is to create vechicle record only when the payment record is created then you can remove the "After update " event. 

Or else you have to specify the condition like below:- 
trigger ContextExampleTrigger on Account (before insert, after insert, after delete) {
    if (Trigger.isInsert) {
        if (Trigger.isBefore) {
            // Process before insert
        } else if (Trigger.isAfter) {
            // Process after insert
        }        
    }
    else if (Trigger.isUpdate) {
        // Process after delete
    }
}

Kindly mark it as best answer if it solve your requirement.

Thanks!