Activity Forums Salesforce® Discussions Why is Trigger Not Working For Bulk Insert? Reply To: Why is Trigger Not Working For Bulk Insert?

  • Jayant

    Member
    March 23, 2016 at 12:41 pm

    The first for loop can cause performance issue: Suppose Trigger.New has 1000 or 2000 records then it will run for 1000*1000 = 1,000,000 or 2000*2000 = 2,000,000.

    You can use Set here for improving performance:

    Integer counter = 0;
    Set<String> uniqueEmails = new Set<String>();
    List<Contact> validContacts = new List<Contact>();
    Map<String, Contact> validContacts = new Map<String,Contact>();
    for(Contact conToInsert : Trigger.New) {
    if(conToInsert.Email != null) {
    Contact result = validContacts.get(conToInsert.Email)
    //If result is FALSE, then add Error to record.
    if(result != null) {
    conToInsert.addError("Duplicate Email Address.");
    }
    else if(result != null && conToInsert.Type__c == ‘Type 4’){
    conToInsert.addError("Contact Cannot be Type 4.");
    } else {
    //Everything okay

    validContacts.put(conToInsert.Email, result );
    }
    }
    }

    //Now check Contact with unique email against existing Contacts.
    //If there are more than 50000 Record, then this needs to be rewritten
    List<Contact> existingContacts = [select Email,Type__c from Contact Email in :validContacts.keySet()];

    for(Contact existingContact : existingContacts){
    Contact temp = validContacts.get(existingContact.Email);
    if(temp.id == null || temp.Type__c == ‘Type 4’) {
    //This is bad record, remove
    temp.addError("Duplicate Email or Type 4");
    validContacts.remove(temp);
    }
    }

    //These are valid record. Do whatever you want to do with them.
    List<Contact> updateOrInsertContact = validContacts.values();

    I hope this helps.