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
DipthiDipthi 

Plz help me to bulkify my code - add error to all records in the list

trigger AccountIndustryAnnualRevenue on Account (before insert , before update) {
    List<Account> AccList = new List<Account>();
    for(Account Acc : Trigger.new) {
        If((Acc.Industry == 'Chemicals') && (Acc.AnnualRevenue <= 1200)){
           AccList.add(Acc);
        }    
        If(AccList.size() > 0) {
          Acc.addError ('When Industry is ‘Chemical’, annual revenue cannot be less than 1200'); // logic is incorrect. 
          
        }   
    }
}
Best Answer chosen by Dipthi
Ajay MohananAjay Mohanan
You would want to add the error in side your loop. One way to rewrite it would be:

for(Account Acc : Trigger.new) {
    if(Acc.Industry == 'Chemicals' && Acc.AnnualRevenue <= 1200){
        Acc.addError('When Industry is ‘Chemical’, annual revenue cannot be less than 1200');
        //AccList.add(Acc); You do not need to use a list to add the errors.
    }      
}

This page has details on the behavior of addError while doing bulk updates.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_exceptions.htm
 

All Answers

Ajay MohananAjay Mohanan
You would want to add the error in side your loop. One way to rewrite it would be:

for(Account Acc : Trigger.new) {
    if(Acc.Industry == 'Chemicals' && Acc.AnnualRevenue <= 1200){
        Acc.addError('When Industry is ‘Chemical’, annual revenue cannot be less than 1200');
        //AccList.add(Acc); You do not need to use a list to add the errors.
    }      
}

This page has details on the behavior of addError while doing bulk updates.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_exceptions.htm
 
This was selected as the best answer
DipthiDipthi

 

Thank you very much Ajay Mohanan :)

Mark StvenMark Stven
THanks Ajay i applied this to my chemical website (https://researchemicalsforsale.com) and it works.