You are here

function cer_insert in Corresponding Entity References 7

Add any corresponding references on node insertion.

$keys = array( 'home_entity_type' => $key[0], 'home_bundle' => $key[1], 'home_field' => $key[2], 'away_entity_type' => $key[3], 'away_bundle' => $key[4], 'away_field' => $key[5], );

File

./cer.crud.inc, line 20
Include file providing corresponding node reference insert, update, and delete handling.

Code

function cer_insert($home_entity, $keys) {
  $types = array(
    'home' => $keys['home_entity_type'],
    'away' => $keys['away_entity_type'],
  );
  $ids = _cer_entity_ids($types);

  // Determine the nodereference values after the insert.
  if (isset($home_entity->{$keys}['home_field']) && is_array($home_entity->{$keys}['home_field'])) {
    foreach ($home_entity->{$keys}['home_field'] as $fields) {
      foreach ($fields as $reference) {
        if (!empty($reference['target_id'])) {

          // Load the referenced entity if it is of the specified away type.
          // TODO: Do this with EntityFieldQuery
          // See http://api.drupal.org/api/drupal/modules--node--node.module/function/node_load_multiple/7
          if ($referenced_entity = entity_load($keys['away_entity_type'], array(
            $reference['target_id'],
          ), NULL, FALSE)) {

            // Entity Load loads an array of ojects keyed by their ID.
            $referenced_entity = $referenced_entity[$reference['target_id']];
            $referenced_entity->bundle_type = _cer_entity_get_bundle($referenced_entity, $keys['away_entity_type']);
            if ($referenced_entity->bundle_type == $keys['away_bundle']) {

              // Add the new reference.
              // If there are no other references, we need to make sure this
              // is delta 0
              if (array_key_exists(LANGUAGE_NONE, $referenced_entity->{$keys['away_field']}) == FALSE || $referenced_entity->{$keys['away_field']}[LANGUAGE_NONE][0]['target_id'] == NULL) {
                $referenced_entity->{$keys['away_field']}[LANGUAGE_NONE][0]['target_id'] = $home_entity->{$ids}['home'];
              }
              else {

                // Add the new reference.
                // Check for doubles, could happen when nodes of same type are
                // referenced.
                $exists = FALSE;
                foreach ($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE] as $key => $value) {
                  if ($value['target_id'] == $home_entity->{$ids}['home']) {
                    $exists = TRUE;
                    break;
                  }
                }
                if (!$exists) {
                  $referenced_entity->{$keys['away_field']}[LANGUAGE_NONE][] = array(
                    'target_id' => $home_entity->{$ids}['home'],
                  );
                }
              }
              _cer_update($keys['away_entity_type'], $referenced_entity);
            }
          }
        }
      }
    }
  }
}