You are here

function ref_field_sync_add_reference in (Entity)Reference Field Synchronization 7.2

Same name and namespace in other branches
  1. 7 ref_field_sync/ref_field_sync.module \ref_field_sync_add_reference()

Add a ref_field value form an entity

Parameters

string $type: The type of entity being modified

object $entity: The entity being modified

int $target_id: The ID of the entity to reference to

string $field_name: Name of the field to add the reference to

2 calls to ref_field_sync_add_reference()
ref_field_sync_entity_insert in ./ref_field_sync.module
Implements hook_entity_insert().
ref_field_sync_entity_update in ./ref_field_sync.module
Implements hook_entity_update().

File

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

Code

function ref_field_sync_add_reference($type, $entity, $target_id, $field_name) {
  $lng = field_language($type, $entity, $field_name);
  $field = field_info_field($field_name);

  // Remove previous references if limited to 1 value.
  if ($field['cardinality'] == 1) {
    $entity->{$field_name}[$lng] = array();
  }

  // Do not reference if already referenced.
  if ($items = field_get_items($type, $entity, $field_name)) {
    foreach ($items as $key => $value) {
      if ($value['target_id'] == $target_id) {
        return;
      }
    }
  }
  $entity->{$field_name}[$lng][] = array(
    'target_id' => $target_id,
  );

  // Set flag to not process the calling entity again.
  $entity->ref_field_caller = $target_id;
  entity_save($type, $entity);
}