I had a situation recently where I needed to delete both a Drupal user account and a CiviCRM contact at the same time. This was to rid SPAM from the system that was made years ago before there was a CAPTCHA in place.
I thought about making an action to use with Views Bulk Actions, but decided that there was no reason to have two ways to delete a user. What I ended up doing was using hook_entity_predelete to check if there was a CiviCRM contact attached to a user and to delete it if it exists.
function my_module_user_predelete(UserInterface $user){
\Drupal::service('civicrm')->initialize();
//Iterate over each possible User and delete the user and their CiviCRM Contact
$uid = $user->id();
//Get the CiviCRM ID
$uf_result = civicrm_api3('UFMatch', 'get', [
'sequential' => 1,
'return' => ["contact_id"],
'uf_id' => $uid,
]);
$civiid = $uf_result['values'][0]['contact_id'];
//Delete the CiviCRM contact if one was found
if ($uf_result['is_error'] == 0 && !empty($civiid)) {
$contact_delete = civicrm_api3('Contact', 'delete', [
'id' => $civiid,
]);
}
}
Comments