I have a custom module that will create a Drupal user programmatically using user_save as follows:

  //set up the user fields
  $fields = array(
    'mail' => $email,
    'pass' => $password,
    'name' => $username,
    'status' => 1,
    'init' => $email,
    'access' => REQUEST_TIME,
    'roles' => array(2 => 'authenticated user'),

  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);

I have first done a check using the CiviCRM API to make sure that if an existing contact is already in the database and has a Drupal account associated with it, we don't create a new one. Also I check to make sure the email address isn't registered from the Drupal side.

The problem is, when I create a new user, it is not linking up to an existing CiviCRM contact record that uses the same email address and I'm ending up with a duplicate contact record.

How can I force the site to link to an existing record if the email address is a match?

1 Answer 1


The function to synchronize Drupal users and CiviCRM contacts is CRM_Core_BAO_UFMatch::synchronize().

Since you're calling user_save(), CiviCRM's hook_user_insert implementation should get triggered (from user_module_invoke('insert', $edit, $account, $category); in user_save().

CiviCRM's civicrm_user_insert() checks whether it thinks you are on a CiviCRM callback already*, then calls either civicrm_register_data() which will in turn call CRM_Core_BAO_UFMatch::synchronize(), or CRM_Core_BAO_UFMatch::synchronize() directly.

To deal with this you could trace your way through CiviCRM's code (drupal/civicrm.module, drupal/civicrm_user.inc, CRM/Core/BAO/UFMatch.php) and work out which path your code is triggering; ultimately you want to end up with a call to CRM_Core_BAO_UFMatch::synchronize() which passes in the parameters for CiviCRM to correctly match the existing and new data.

You could also just call that function directly from your custom code; that might be less robust as in future you might end up triggering the synchronize call twice ...

  • If after investigating you believe CiviCRM isn't behaving correctly here, please consider taking the time to create an account and document your issue on the CiviCRM issue tracker. Feb 10, 2015 at 22:08
  • Consider committing to the CiviCRM Stackexchange proposal to help grow a better forum for such questions in future! Feb 10, 2015 at 22:09
  • Thanks for such an in depth answer, I will work from this. Sorry for the delay in response. And yes, we are getting close on the CiviCRM Stackexchange site!
    – Laryn
    Mar 6, 2015 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.