• Mark S
  • NEWBIE
  • 0 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
Hello,
Can anybody help me on this Case Trigger I'm working on?

Basically when a new case comes in via W2C, I have a trigger to link the Account (or create one if needed). It works in sandbox but something is going wrong with the amount of data returned in my query on line 14. The custom E_mail__c field is indexed, and I'm not sure what else I could check.

Is there something I'm missing in my WHERE clause (in particular to line 14 of the code snippet)?
trigger CaseAutocreateAccount on Case (before insert) {
    List<String> emailAddresses = new List<String>();
    
    //First exclude any cases where the account is set
    for (Case caseObj:Trigger.new) {
        if (caseObj.AccountId==null &&
            caseObj.SuppliedEmail!='')
        {
            emailAddresses.add(caseObj.SuppliedEmail);
        }
    }

    //Now we have a nice list of all the email addresses.  Let's query on it and see how many Accounts already exist.
    List<Account> listAccounts = [Select Id,E_mail__c From Account Where E_mail__c in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Account a:listAccounts) {
        takenEmails.add(a.E_mail__c);
    }
    
    Map<String,Account> emailToAccountMap = new Map<String,Account>();
    List<Case> casesToUpdate = new List<Case>();

    for (Case caseObj:Trigger.new) {
        if (caseObj.AccountId==null &&
            //caseObj.Origin=='Web' &&
            caseObj.SuppliedEmail!=null &&
            //caseObj.SuppliedName!='' &&
            //!caseObj.SuppliedName.contains('@') &&
            caseObj.SuppliedEmail!='' &&
            !takenEmails.contains(caseObj.SuppliedEmail))
        {
            //The case was created with a null Account
            //Let's make a account for it
            String[] nameParts = caseObj.SuppliedName.split(' ',2);
            if (nameParts.size() == 2)
            {
                Account acct = new Account(FirstName=nameParts[0],
                                            LastName=nameParts[1],
                                            E_mail__c=caseObj.SuppliedEmail);
                emailToAccountMap.put(caseObj.SuppliedEmail,acct);
                casesToUpdate.add(caseObj);
            }
        }
    }
    
    List<Account> newAccounts = emailToAccountMap.values();
    insert newAccounts;
    
    for (Case caseObj:casesToUpdate) {
        Account newAccount = emailToAccountMap.get(caseObj.SuppliedEmail);
        
        caseObj.AccountId = newAccount.Id;
    }
}

Thanks for any help provided!

-Mark
  • November 08, 2017
  • Like
  • 0