It seems like something this simple shouldn't require 3 separate maps. I'm querying for the Account and Contact using the Account name pulled from the auto-generated case subject. Any tips are appreciated.
// Called from Case Trigger public static void beforeInsert(Case[] newCases) { Map<String, String> acctNames = new Map<String, String>(); Map<String, String> caseToAccts = new Map<String, String>(); Map<String, String> caseToConts = new Map<String, String>(); for (Case c : newCases) { if (c.Origin == 'Email' && c.Subject.contains('Backup Failed:')) { acctNames.put(c.Subject.substringBetween('Backup Failed: ',' on'), c.Id); } } for (Account acc : [SELECT Id, Name, (SELECT Id FROM Contacts WHERE Server_Failure_Contact__c = true) FROM Account WHERE Name IN :acctNames.values()]) { caseToAccts.put(acctNames.get(acc.Name), acc.Id); caseToConts.put(acctNames.get(acc.Name), acc.Contacts[0].Id); } for (Case c : newCases) { c.AccountId = caseToAccts.get(c.Id); c.ContactId = caseToConts.get(c.Id); } }
WHERE Name IN :acctNames.values()
should beWHERE Name IN :acctNames.keySet()
. Probably better to use the nameacctNameToCases
for that variable. While you could remove a map, that part of the code is probably clearer the way you have done it. I'd use the type Id instead of String in the maps though where appropriate to make the code a bit clearer. And only do the Account query and following code whenacctNames
isn't empty.