Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackrabbithanna/919e2839c7d6a436bc2945e0bc5e750f to your computer and use it in GitHub Desktop.
Save jackrabbithanna/919e2839c7d6a436bc2945e0bc5e750f to your computer and use it in GitHub Desktop.
CE custom code snippet, copy address lat/long to Geolocation field on contact
/**
* Implements hook_ENTITY_TYPE_update().
*
* On contact update, update primary Address, giving Drupal Geolocation its value
*/
function map_customs_civicrm_contact_update(CivicrmEntity $civicrm_contact) {
if ($civicrm_contact->get('contact_type')->value !== 'Organization') {
return;
}
$result = \Drupal::service('civicrm_entity.api')->getSingle('Contact', [
'id' => $civicrm_contact->id(),
'return' => ['address_id'],
]);
if (!empty($result) && isset($result['address_id'])) {
/** @var \Drupal\civicrm_entity\Entity\CivicrmEntity $address */
$address = \Drupal::entityTypeManager()
->getStorage('civicrm_address')
->load($result['address_id']);
if (!$address) {
return;
}
if ($address->get('geo_code_1')->isEmpty() || $address->get('geo_code_2')->isEmpty()) {
return;
}
$address->set('field_geolocation', [
'lat' => $address->get('geo_code_1')->value,
'lng' => $address->get('geo_code_2')->value,
]);
$address->save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment