You are here

function ref_field_sync_entity_delete in (Entity)Reference Field Synchronization 7.2

Implements hook_entity_delete().

File

./ref_field_sync.module, line 307
Hooks and main functions for ref_field module.

Code

function ref_field_sync_entity_delete($entity, $type) {
  $info = entity_get_info($type);

  // Get fields of type ref_field
  $fields = field_read_fields(array(
    'type' => 'entityreference',
  ));

  // Loop through every field.
  foreach ($fields as $field_name => $field) {

    // Get more info for the field (bundles where exist)
    $field = field_info_field_by_id($field['id']);

    // Update fields array with new info.
    $fields[$field_name] = $field;

    // Go through fields that exist in this entity/bundle
    if (isset($entity->{$field_name}) && !empty($field['settings']['sync'])) {
      $delete = array();

      // Get values from deleted entity.
      $items = field_get_items($type, $entity, $field_name);
      if (isset($items) && gettype($items) === 'array') {
        foreach ($items as $item) {
          $delete[] = $item['target_id'];
        }
      }
      if (!empty($delete)) {
        $entities = entity_load($field['settings']['target_type'], $delete);
        if (!empty($entities)) {
          foreach ($entities as $entity_id => $e) {

            // Remove reference from synced field.
            ref_field_sync_remove_reference($field['settings']['target_type'], $e, $entity->{$info['entity keys']['id']}, $field['settings']['sync']);
          }
        }
      }
    }
  }
}