function civicrm_entity_reference_field_entity_presave in CiviCRM Entity 7.2
Implements hook_entity_presave().
We needed this because sometimes you need to back fill a value before save
For example, if you put a civicrm entity reference field which targets the location block, on a event entity, you have to make sure the event gets a value for the location_block_id Another example is that the location block address_id property needs to be set after the address is saved (considering if you have an civicrm_entity_reference field on the location block form, targeting address
More cases of this type may crop up and we'll better understand how to automate as time passes and experience hits us over the head
Parameters
$entity:
$type:
File
- modules/
civicrm_entity_reference_field/ civicrm_entity_reference_field.module, line 761 - Provide CiviCRM entity reference field type
Code
function civicrm_entity_reference_field_entity_presave($entity, $type) {
if ($type == 'civicrm_loc_block' || $type == 'civicrm_event') {
foreach ($entity as $key => $value) {
if (strpos($key, 'field_') === 0) {
$field = field_info_field($key);
if ($field['type'] == 'civicrm_entity_reference') {
if ($type == 'civicrm_loc_block') {
switch ($field['settings']['target_entity_type']) {
case 'address':
$entity->{$field['settings']['host_source_id']} = $entity->{$key}[LANGUAGE_NONE][0]['target_id'];
// VIA the API you cannot save/create an address without a contact id, we fool it in this special case by in the form setting the id to 1, then undoing it with sql directly
// it ain't pretty but it works
db_update('civicrm_address')
->fields(array(
'contact_id' => NULL,
))
->condition('id', $entity->{$key}[LANGUAGE_NONE][0]['target_id'])
->execute();
break;
case 'email':
$entity->{$field['settings']['host_source_id']} = $entity->{$key}[LANGUAGE_NONE][0]['target_id'];
db_update('civicrm_email')
->fields(array(
'contact_id' => NULL,
))
->condition('id', $entity->{$key}[LANGUAGE_NONE][0]['target_id'])
->execute();
break;
case 'phone':
$entity->{$field['settings']['host_source_id']} = $entity->{$key}[LANGUAGE_NONE][0]['target_id'];
db_update('civicrm_phone')
->fields(array(
'contact_id' => NULL,
))
->condition('id', $entity->{$key}[LANGUAGE_NONE][0]['target_id'])
->execute();
break;
case 'im':
$entity->{$field['settings']['host_source_id']} = $entity->{$key}[LANGUAGE_NONE][0]['target_id'];
db_update('civicrm_im')
->fields(array(
'contact_id' => NULL,
))
->condition('id', $entity->{$key}[LANGUAGE_NONE][0]['target_id'])
->execute();
break;
}
}
elseif ($type == 'civicrm_event' && $field['settings']['target_entity_type'] == 'loc_block') {
$entity->{$field['settings']['host_source_id']} = $entity->{$key}[LANGUAGE_NONE][0]['target_id'];
}
}
}
}
}
}