Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should execute a query on lead and contact using the email address as the criteria for you query. If it returns 0 records for the Lead and 0 records for the Contact, then you would create a new Lead.</p> <p>Your query could return more than 1 record for either Lead or Contact, so you will have to develop a strategy to handle that case. Email address is not required to be unique.</p> <pre><code>public class StackOverflowExample { public static void test(String email) { handleNewEmail(email); } private static void handleNewEmail(String email) { List&lt;Lead&gt; leads = [select id, email from Lead where email = :email]; List&lt;Contact&gt; contacts = [select id, email from Contact where email = :email]; if (leads.size() == 0 &amp;&amp; contacts.size() == 0) { //Create new lead insert new Lead(Company = 'Lead Company', FirstName = 'firstname', LastName = 'lastname', Email = email); } else if (leads.size() == 1) { // Update this lead leads[0].FirstName = 'newfirstname'; update leads; } else if (contacts.size() == 1) { // Update this contact contacts[0].FirstName = 'newfirstname'; update contacts; } else { // Must be more than 1 contact or lead System.debug('\nMore than 1 contact or lead.'); } } </code></pre> <p>}</p> <p>The other option is to execute a search limiting the scope to email fields. </p> <pre><code>public class StackOverflowExample { public static void test(String email) { handleNewEmail(email); } private static void handleNewEmail(String email) { List&lt;List&lt;SObject&gt;&gt; searchResults = [FIND :email IN Email Fields RETURNING Lead(Id, FirstName, LastName), Contact(Id, FirstName, LastName)]; List&lt;Lead&gt; leads = ((List&lt;Lead&gt;)searchResults[0]); List&lt;Contact&gt; contacts = ((List&lt;Contact&gt;)searchResults[1]); if (leads.size() == 0 &amp;&amp; contacts.size() == 0) { //Create new lead insert new Lead(Company = 'Lead Company', FirstName = 'firstname', LastName = 'lastname', Email = email); } else if (leads.size() == 1) { // Update this lead leads[0].FirstName = 'newfirstname'; update leads; } else if (contacts.size() == 1) { // Update this contact contacts[0].FirstName = 'newfirstname'; update contacts; } else { // Must be more than 1 contact or lead System.debug('\nMore than 1 contact or lead.'); } } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload