+ Start a Discussion
Lavanya Ponniah 3Lavanya Ponniah 3 

How to bulkify the below trigger?

This trigger works perfect for the single record insert and update.But how to do for the bulk records.Its Urgent

trigger InstalledHardware on Vehicle_Details__c (before insert, before update)
{
    list<Order> listup=new list<Order>();
    list<i
    for(Vehicle_Details__c V:trigger.new)
    {
        
        Order o=[select Order_Number__c,Finished_HardWare__c,Left_Hardware__c,Total_Hardware_Type_Ordered_Products__c from Order where id=:v.Order__c];
        if(o.id!=null)
        {
            o.Finished_HardWare__c=o.Finished_HardWare__c+V.Total_Hardware_Installed__c;
            listup.add(o);
        }
        v.Pending_Hardware_Installations_Order__c=o.Left_Hardware__c;
        v.Total_Hardware_Quantity_for_Order__c=o.Total_Hardware_Type_Ordered_Products__c;
    }
    if(listup.size()>0)
    {
        update listup;
    }
}
PratikPratik (Salesforce Developers) 
Hi Lavanya,

Will you please let us know the requirement/ what you want to achieve through this trigger?  What are the issues with this trigger when bulk updates/insert happens?

Thanks,
Pratik
Lavanya Ponniah 3Lavanya Ponniah 3
When we insert the data using dataloader.io its shows too many dml operations.
Bhanu MaheshBhanu Mahesh
Hi Lavanya,

Try the below code
If it does not meet your requirement please share the complete requirement

trigger InstalledHardware on Vehicle_Details__c (before insert, before update)
{
    list<Order> listup=new list<Order>();
    Set<Id> setOrderIds = new Set<Id>();
    Map<Id,Order> mapIdWithOrder = new Map<Id,Order>();
    for(Vehicle_Details__c V:trigger.new){
        if(v.Order__c != null){
           setOrderIds.add(v.Order__c); 
        }
    }
    if(!setOrderIds.isEmpty()){
        for(Order ordr :[select Order_Number__c,Finished_HardWare__c,Left_Hardware__c,Total_Hardware_Type_Ordered_Products__c from Order where id IN :setOrderIds]){
            mapIdWithOrder.put(ordr.Id,ordr);    
        }
    }
    for(Vehicle_Details__c V:trigger.new){
        if(v.Order__c != null && mapIdWithOrder != null && mapIdWithOrder.get(v.Order__c) != null){
           Order ordr = mapIdWithOrder.get(v.Order__c);
           v.Pending_Hardware_Installations_Order__c = ordr.Left_Hardware__c;
           v.Total_Hardware_Quantity_for_Order__c = ordr.Total_Hardware_Type_Ordered_Products__c; 
           ordr.Finished_HardWare__c = ordr.Finished_HardWare__c + V.Total_Hardware_Installed__c;
           listup.add(ordr);
        }
    }
    
    if(listup.size() > 0)
    {
        update listup;
    }
}

Regards,
Bhanu Mahesh
Lavanya Ponniah 3Lavanya Ponniah 3
I am getting error ERROR: InstalledHardware: execution of BeforeInsertcaused by: System.ListException: Duplicate id in list: 801O00000003HOIIA2Trigger.InstalledHardware: line 32, column 1