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
HARI KRISHNAHARI KRISHNA 

Help me for Bulkifying this Trigger

------------------Help me for Bulkifying this Trigger-----------------------------Invoice have look up relationship with Account...
trigger InvAmountUpdate on Invoice__c (After Update)
{
    for(Invoice__c inv:Trigger.New)
    {
        Account acc=new Account();
        acc=[Select id,Account_Balance__c From Account Where id =:inv.Account__c];
        
        if(acc.Account_Balance__c==null)
            acc.Account_Balance__c=0;  
   
        Invoice__c  invOld=Trigger.oldMap.get(inv.id);
        if(inv.Invoice_Amount__c!=invOld.Invoice_Amount__c)
            acc.Account_Balance__c=acc.Account_Balance__c-invOld.Invoice_Amount__c+inv.Invoice_Amount__c;
   
    update acc;
    }
}
James LoghryJames Loghry
trigger InvAmountUpdate on Invoice__c (after Update){

    List<Account> accountsToUpdate = new List<Account>();
    for(Invoice__c inv: [Select Account__r.Account_Balance__c,Invoice_Amount__c From Invoice__c Where Id in :Trigger.newMap.keySet()]){
        
        Decimal oldAmount = Trigger.oldMap.get(inv.Id).Invoice_Amount__c;
        if(oldAmount != inv.Invoice_Amount__c){
            Account acct = inv.Account__r;
            acct.Account_Balance__c = acct.Account_Balance__c - oldAmount + inv.Invoice_Amount__c;
            accountsToUpdate.add(acct);
        }
    }
    update accountsToUpdate;
}

In general, here's how you would handle bulk invoices.  But please note the following: You'll need to handle null values with Account_Balance and Invoice_Amount__c values.  Also, what if the Invoices pertain to the same account?  The account balance might be wrong in that case.