Skip to content

Instantly share code, notes, and snippets.

@adam17amo
Created May 7, 2018 05:58
Show Gist options
  • Select an option

  • Save adam17amo/c339f4ecbd55ce74dd78d0c3ff661696 to your computer and use it in GitHub Desktop.

Select an option

Save adam17amo/c339f4ecbd55ce74dd78d0c3ff661696 to your computer and use it in GitHub Desktop.
public class LeadTriggerHandler extends TriggerHandler {
List<Lead> newLeads;
public LeadTriggerHandler(){
newLeads = (List<Lead>) Trigger.new;
}
public override void beforeInsert() {
Set<String> companyNames = new Set<String>(); // Will hold the set of Lead Company Names
Map<String, ID> accountNamesToId = new Map<String, ID>(); // Will hold the set of Account Names mapped to the Account ID
List<Case> newCases = new List<Case>(); // Will hold the new cases to create
for(Lead l : newLeads){ // Look at each Lead individually
companyNames.add(l.Company); // Add the Lead Company to our set
}
// Get all existing Accounts with the same names as the Leads being inserted
List<Account> existingAccounts = [SELECT Name FROM Account WHERE Name IN :companyNames];
for(Account a : existingAccounts) { // Look at each Account individually
accountNamesToId.put(a.Name, a.Id); // Add all Account names to a set and map it to the Account ID
}
for(Lead l : newLeads) { // Go through list of Leads again
if(accountNamesToId.keySet().contains(l.Company)) { // If the Lead Company name is in the list of existing Account names
Case c = new Case(); // Create a new case
c.AccountId = accountNamesToId.get(l.Company); // Get the Account ID that corresponds to this Account Name
c.Subject = 'Account already exists for ' + l.Company; // Set the subject
c.Status = 'New'; // Set the status
newCases.add(c); // Add our Case to the list of Cases to create
}
}
insert newCases; // Insert our Cases into Salesforce
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment