Skip to content

Instantly share code, notes, and snippets.

@adam17amo
Last active October 5, 2025 22:54
Show Gist options
  • Select an option

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

Select an option

Save adam17amo/acc727d8f8ab6bbb334b0c5b66f94fcc to your computer and use it in GitHub Desktop.
// Trigger to search Accounts and create a new Case if a Lead Company Name is being created that matches an existing Account name
trigger LeadTrigger on Lead (before insert) {
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 : Trigger.new){ // 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 : Trigger.new) { // 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