How to check if a Contact record exists by email address

Created on 27 July 2017, over 7 years ago
Updated 21 August 2023, over 1 year ago

While tooling around on a site's integration I needed to quickly check if a specific contact existed in the system based upon their email address. After some testing I came up with the following and thought I'd share it:


/**
 * Check to see if a contact already exists based upon an email address.
 *
 * @param string $email
 *   The email address to check.
 *
 * @return bool
 *   Whether or not the contact exists.
 */
function mymodule_sf_contact_exists($email) {
  $sfapi = salesforce_get_api();
  $soql = new SalesforceSelectQuery('Contact');
  $soql->fields = array(
    'Id' => 'Id',
  );
  $soql->addCondition('Email', "'{$email}'");
  $result = $sfapi->query($soql);
  return !empty($result['totalSize']);
}
πŸ“Œ Task
Status

Active

Version

3.0

Component

Documentation

Created by

πŸ‡ΊπŸ‡ΈUnited States DamienMcKenna NH, USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • I found this helpful. However, for Salesforce 5 (Drupal 10), the syntax is now a bit different - there's no longer a salesforce_get_api() function. The snippet now needs to be:

    use \Drupal\salesforce\SelectQuery;
    
    function mymodule_sf_contact_exists($email) {
      $soql = new SelectQuery('Contact');
      $soql->fields = [ 'Id' => 'Id' ];
      $soql->addCondition('Email', "'{$email}'");
      $result = \Drupal::service('salesforce.client')->query($soql);
      return ($result->size() > 0);
    }

    In my case I wanted to get the SFID of the contact if it existed. In this case, the last line becomes:

      return ($result->size()) ? current($result->records())->id() : NULL;
    
Production build 0.71.5 2024