When you’re working with Salesforce, one of the most common tasks is creating new Contact records. Apex, Salesforce’s programming language, makes this easy to do with just a few lines of code. In this blog post, we’ll walk through a simple method written in Apex that accepts a person’s first name, last name, and email address, and then creates a Contact record using that information. If you’re new to Apex or just starting out in Salesforce development, don’t worry we’ll break it down in a way that’s easy to understand!
What Are We Trying to Do?
Let’s say we have a form on a website or an internal Salesforce page where users input their first name, last name, and email. We want to take that data and create a Contact record in Salesforce. But we also want to make sure we don’t create a record if the last name is missing (since Salesforce requires a last name for Contact records).
That’s exactly what the below method does.
Code Explanation
public class ApexUseCaseOne {
public static void createNewContact(String firstName, String lastName, String emailAddress){
We define a class called
ApexUseCaseOne
.Inside that class, we create a
static
method calledcreateNewContact
, which takes three inputs: first name, last name, and email address.
List<Contact> conListToInsert = new List<Contact>();
- We create a list to store our contact(s). Right now, we’ll only add one contact, but this pattern is useful when you need to insert many at once (called bulk processing).
Contact conToInsert = new Contact();
- We check if the
lastName
is not blank. This is crucial because the Last Name field is required in Salesforce to save a Contact.conToInsert.FirstName = firstName;
conToInsert.LastName = lastName;
conToInsert.Email = emailAddress;
conListToInsert.add(conToInsert);
}
If the last name is present:
We assign the input values to the corresponding Contact fields.
Then, we add the contact to our list.
if(conListToInsert.size() > 0){
insert conListToInsert;
}
}
}
Finally, we check if the list has at least one contact.
If yes, we insert the list into the database using the
insert
DML operation.
Why This Is Useful
This method ensures we only try to insert valid Contact records and prepares us for batch or bulk inserts in the future. It’s simple, efficient, and reusable — you can call this method whenever you need to add a new Contact.
Final Code Snippet
public class ApexUseCaseOne {
public static void createNewContact(String firstName, String lastName, String emailAddress){
List<Contact> conListToInsert = new List<Contact>();
Contact conToInsert = new Contact();
if(!String.isBlank(lastName)){
conToInsert.FirstName = firstName;
conToInsert.LastName = lastName;
conToInsert.Email = emailAddress;
conListToInsert.add(conToInsert);
}
if(conListToInsert.size() > 0){
insert conListToInsert;
}
}
}
🎥 Watch It in Action!
If you’re more of a visual learner, I’ve got you covered. Watch this short video where I show the Apex code in action!