Kaynağa Gözat

update for 2.x version

Bachir Soussi Chiadmi 10 yıl önce
ebeveyn
işleme
7e3ef32d18

+ 58 - 1
README.txt

@@ -1 +1,58 @@
-Next Evolution of Corresponding Node References.
+ACKNOWLEDGEMENTS
+
+As this is the next evolution of Corresponding Node References,
+I would like to say thanks for all the work done over on Corresponding Node
+References.
+
+DESCRIPTION
+
+It syncs the entity reference between two entity types which have an entity
+reference to each other, so double editing entities is no longer needed. If one
+entity has a reference, the other entity also receives a reference to the saved
+entity if it is referenced in that entity.
+
+DEPENDENCIES
+
+7.x: Entity Reference
+
+EXAMPLE
+
+Entity type A has an entity reference to entity type B and entity type B has an
+entity reference to entity type A. When you create entity X of type A and
+reference it to entity Y of type B entity Y will also receive an update in its
+entity reference field pointing to entity X.
+
+KNOWN ISSUES
+
+- Support for entity reference fields in field collections is still a work in progress.
+  CER has no native support for entities that are wrapped by other entities (i.e.,
+  field collections), and implementing this properly will require extensive changes
+  to many parts of CER. For this reason, field collection support is on hold until
+  a few other major issues in the queue are sorted out. The thread for field collection
+  support is http://drupal.org/node/1729666.
+
+- Support for multi-language entities is, at the time of this writing, flaky at best.
+  There is a patch to implement better multi-language support, available at
+  http://drupal.org/node/1961026. If this patch works well for you, PLEASE post
+  in that issue to say that it worked so that the patch can be reviewed by
+  the community before being committed into CER.
+
+- If you're updating CER from 1.x to 2.x, you should rebuild your theme registry.
+  This is because the reference labels on CER's admin page were made themeable
+  in 2.x, so you'll need to make Drupal recognize the new theme hook.
+
+INSTALL
+
+- To install enable the module at admin/build/modules
+- Create entity type A
+- Create entity type B
+- Create a entity reference field on entity type A pointing to entity B
+- Create a entity reference field on entity type B pointing to entity A
+- Go to the settings page at admin/config/system/cer. 
+  Select to enable the corresponding referencing for these node types pointing 
+  to each other.
+- Create some entities and reference them to each other
+
+MAINTAINER
+
+Questions, comments, etc. should be directed to phenaproxima (djphenaproxima@gmail.com).

+ 253 - 0
cer.admin.inc

@@ -0,0 +1,253 @@
+<?php
+
+/**
+ * @file
+ * Administrative functionality, separated for performance purposes.
+ */
+
+/**
+ * The settings form.
+ */
+function cer_settings_form($form = array(), &$form_state) {
+  $channels = array();
+
+  foreach (_cer_get_fields() as $field) {
+    foreach ($field['bundles'] as $entity_type => $bundles) {
+      foreach ($bundles as $bundle) {
+        $instance = field_info_instance($entity_type, $field['field_name'], $bundle);
+        $channels = array_merge($channels, _cer_find_channels($instance));
+       }
+     }
+   }
+
+  if (empty($channels)) {
+    drupal_set_message(t('There are no entity reference fields that can correspond.'), 'warning');
+  }
+  else {
+    $mapping = array();
+    foreach ($channels as $count => $key) {
+      $formatted_key = str_replace(' ', '*', $key);
+
+      $mapping[$count] = $formatted_key;
+
+      $form['values']["enabled_{$count}"] = array(
+        '#type' => 'checkbox',
+        '#default_value' => cer_preset_enabled($formatted_key),
+        '#title' => theme('cer_label', array('key' => $key)),
+      );
+    }
+
+    // We are using a hidden field to submit the configuration because on
+    // some systems the checkbox name length is limited, and using
+    // the key would cause the length to be too long. (Issue #558612)
+    $form['mapping'] = array(
+      '#type' => 'hidden',
+      '#value' => serialize($mapping),
+    );
+
+    $form['submit'] = array(
+      '#type' => 'submit',
+      '#value' => t('Save'),
+    );
+  }
+
+
+  return $form;
+}
+
+/**
+ * Submit function for settings form.
+ */
+function cer_settings_form_submit($form, $form_state) {
+  ctools_include('export');
+  $query_values = array();
+
+  $mapping = unserialize($form_state['values']['mapping']);
+
+  foreach ($form_state['values'] as $key => $value) {
+    $keys = explode('_', $key);
+    if ($keys[0] == 'enabled') {
+      $query_values[$mapping[$keys[1]]] = $value;
+    }
+  }
+
+  // load all existing presets
+  $presets = ctools_export_crud_load_all('cer');
+
+  foreach ($query_values as $key => $value) {
+    // get preset object (create new one if it doesn't exist already).
+    $preset = empty($presets[$key]) ? ctools_export_crud_new('cer') : $presets[$key];
+
+    // set and save value
+    if (empty($preset->entity_types_content_fields)) {
+      $preset->entity_types_content_fields = $key;
+    }
+    $preset->enabled = $value;
+    ctools_export_crud_save('cer', $preset);
+
+    // remove from list of presets, so we know which ones are still used
+    if (isset($presets[$key])) {
+      unset($presets[$key]);
+    }
+  }
+
+  drupal_set_message(t('The configuration has been saved.'));
+}
+
+/**
+ * Allows batch updating of existing entities.
+ */
+function cer_update_form($form = array(), &$form_state) {
+  $form['type'] = array(
+    '#type' => 'select',
+    '#title' => t('Entity type'),
+    '#required' => TRUE,
+    '#options' => array(),
+    '#description' => t('Select the entity type that you want to update.'),
+  );
+  foreach (entity_get_info() as $type => $class) {
+    $form['type']['#options'][$type] = $class['label'];
+  }
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Submit'),
+  );
+
+  return $form;
+}
+
+/**
+ * The update form.
+ * Allows updating of current entitys.
+ */
+function cer_update_form_submit($form, &$form_state) {
+  $batch = array(
+    'finished' => 'cer_batch_update_existing_finished',
+    'title' => t('Processing'),
+    'init_message' => t('Preparing to update corresponding entity references for existing entities...'),
+    'progress_message' => t('Processing entities...'),
+    'error_message' => t('Corresponding entity references - existing entity update has encountered an error.'),
+  );
+
+  $entities = entity_load($form_state['values']['type'], FALSE);
+  foreach ($entities as $entity) {
+    $batch['operations'][] = array('cer_processing_entity', array('update', $entity, $form_state['values']['type']));
+  }
+  batch_set($batch);
+}
+
+/**
+ * The purpose of this function is to answer this question: I am a field instance. Which other
+ * fields reference the entity that owns me? And of those instances, which ones can I reference?
+ * The answer is returned as an array of CER keys: "entity1 bundle1 field1 entity2 bundle2 field2".
+ *
+ * @param array $instance
+ *  Field instance info, as returned by field_info_instance().
+ *
+ * @return array
+ */
+function _cer_find_channels($instance) {
+  $channels = array();
+
+  $my_id = $instance['entity_type'] . ' ' . $instance['bundle'] . ' ' . $instance['field_name'];
+  $my_info = field_info_field($instance['field_name']);
+  $my_targets = _cer_get_target_bundles($my_info);
+  $my_target_type = $my_info['settings']['target_type'];
+
+  $referrers = _cer_find_referrers($instance['entity_type'], $instance['bundle']);
+  foreach ($referrers as $referrer) {
+    if (isset($referrer['bundles'][$my_target_type])) {
+      if (empty($my_targets)) {
+        $bundles = $referrer['bundles'][$my_target_type];
+      }
+      else {
+        $bundles = array_intersect($referrer['bundles'][$my_target_type], $my_targets);
+      }
+      
+      foreach ($bundles as $bundle) {
+        $channels[] = "{$my_id} {$my_target_type} {$bundle} " . $referrer['field_name'];
+      }
+    }
+  }
+
+  return $channels;
+}
+
+/**
+ * Find all fields that can reference the given entity type and bundle.
+ *
+ * @param $entity_type
+ *  The entity type that can be referenced.
+ * @param $bundle
+ *  The bundle that can be referenced.
+ *
+ * @return array
+ */ 
+function _cer_find_referrers($entity_type, $bundle) {
+  $referrers = array();
+  foreach (_cer_get_fields() as $field) {
+    if ($field['settings']['target_type'] == $entity_type) {
+      $target_bundles = _cer_get_target_bundles($field);
+      if (empty($target_bundles) || in_array($bundle, $target_bundles)) {
+        $referrers[] = $field;
+      }
+    }
+  }
+
+  return $referrers;
+}
+
+/**
+ * Find all bundles reference-able by a given field. If all bundles are reference-able,
+ * an empty array is returned.
+ *
+ * @param $field
+ *  Field info array as returned by field_info_field().
+ *
+ * @return array
+ */
+function _cer_get_target_bundles($field) {
+  $target_bundles = array();
+
+  // If the reference field is using a view, load the view and see if it's filtering by the entity
+  // type's bundle filter. If it is, the filter values are the target bundles. Otherwise,
+  // assume that all bundles can be referenced.
+  //
+  // @todo Support contextual filters?
+  //
+  // NOTE: Selection handlers (i.e., $field['settings']['handler']) are plugins owned by
+  // Entity Reference. There is no method defined to get an array of referenceable
+  // bundles, but hopefully, if CER gains enough traction in the community, such a
+  // method can be added to the EntityReference_SelectionHandler interface. This
+  // function could then be deprecated, which would be a more flexible, future-proof
+  // method of finding a field's target bundles.
+  //
+  if ($field['settings']['handler'] == 'views') {
+    $view = views_get_view($field['settings']['handler_settings']['view']['view_name']);
+    $view->set_display($field['settings']['handler_settings']['view']['display_name']);
+
+    $info = entity_get_info($field['settings']['target_type']);
+    if ($info['entity keys']['bundle'] && $handler = $view->display_handler->get_handler('filter', $info['entity keys']['bundle'])) {
+      $target_bundles = $handler->value;
+    }
+  }
+  else {
+    $target_bundles = $field['settings']['handler_settings']['target_bundles'];
+  }
+
+  return $target_bundles;
+}
+
+/**
+ * Get the Field API definitions for all entity reference fields.
+ *
+ * @return array
+ */
+function _cer_get_fields() {
+  static $fields;
+  if (!isset($fields)) {
+    $fields = array_map('field_info_field', db_select('field_config', 'fc')->fields('fc', array('field_name'))->condition('type', 'entityreference')->execute()->fetchCol());
+  }  
+  return $fields;
+}

+ 16 - 0
cer.info

@@ -0,0 +1,16 @@
+name = Corresponding Entity References
+description = Syncs the entity references between entity types which have an entityreference to each other.
+core = 7.x
+package = Fields
+dependencies[] = entityreference
+dependencies[] = ctools
+
+files[] = handler.inc
+
+configure = admin/config/system/cer
+; Information added by drupal.org packaging script on 2013-05-01
+version = "7.x-2.x-dev"
+core = "7.x"
+project = "cer"
+datestamp = "1367412087"
+

+ 12 - 4
corresponding_entity_references.install → cer.install

@@ -8,8 +8,8 @@
 /**
  * Implements hook_schema().
  */
-function corresponding_entity_references_schema() {
-  $schema['corresponding_entity_references'] = array(
+function cer_schema() {
+  $schema['cer'] = array(
     'description' => t('Saves the content types and entity reference fields for which the corresponding entity reference is enabled'),
     'fields' => array(
       'entity_types_content_fields' => array('type' => 'varchar', 'length' => 200, 'not null' => TRUE, 'default' => ''),
@@ -18,12 +18,13 @@ function corresponding_entity_references_schema() {
     'primary key' => array('entity_types_content_fields'),
     'export' => array(
       'key' => 'entity_types_content_fields',
+      'status' => 'enabled',
       'primary key' => 'entity_types_content_fields',
       'key name' => 'Corresponding entity reference',
       'identifier' => 'cnr_obj',
       'api' => array(
-        'api' => 'default_corresponding_entity_references_presets',
-        'owner' => 'corresponding_entity_references',
+        'api' => 'default_cer_presets',
+        'owner' => 'cer',
         'minimum_version' => 1,
         'current_version' => 1,
       ),
@@ -31,3 +32,10 @@ function corresponding_entity_references_schema() {
   );
   return $schema;
 }
+
+/**
+ * Rename table to shorten module name.
+ */
+function cer_update_7001() {
+  db_rename_table('corresponding_entity_references', 'cer');
+}

+ 300 - 0
cer.module

@@ -0,0 +1,300 @@
+<?php
+
+/**
+ * @file
+ * Main module file.
+ */
+
+/**
+ * Implements hook_menu().
+ */
+function cer_menu() {
+  $items = array();
+
+  $items['admin/config/system/cer'] = array(
+    'title' => 'Corresponding entity references',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('cer_settings_form'),
+    'access arguments' => array('administer cer settings'),
+    'file' => 'cer.admin.inc',
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/config/system/cer/references'] = array(
+    'title' => 'References',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('cer_settings_form'),
+    'access arguments' => array('administer cer settings'),
+    'file' => 'cer.admin.inc',
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+  );
+  $items['admin/config/system/cer/update'] = array(
+    'title' => 'Update existing entities',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('cer_update_form'),
+    'access arguments' => array('administer cer settings'),
+    'file' => 'cer.admin.inc',
+    'type' => MENU_LOCAL_TASK,
+  );
+
+  return $items;
+}
+
+/**
+ * Implements hook_permission().
+ */
+function cer_permission() {
+  return array(
+    'administer cer settings' => array(
+      'title' => t('Administer corresponding entity reference settings'),
+    )
+  );
+}
+
+/**
+ * Implements hook_help().
+ */
+function cer_help($path, $arg) {
+  $output = '';
+  if ($path == 'admin/config/system/cer') {
+    $output .= t('Check which entity references should listen to each other. When checking a check box a reference on entity type A to entity B will automatically update the entity reference field on entity B adding an entry which points to entity A.');
+  }
+  elseif ($path == 'admin/config/system/cer/update') {
+    $output .= t('This will update all the existing entities for the selected content types so that their entity reference fields are in sync.');
+    $output .= '<br />';
+    $output .= t('This process may take a long time depending on the number of entities you are updating.');
+    $output .= '<br /><br />';
+    $output .= t('When the process is finished you will see a count of the number of entities that were updated.');
+  }
+  return $output;
+}
+
+/**
+ * Implements hook_field_delete_instance().
+ */
+function cer_field_delete_instance($instance) {
+  foreach (cer_preset_load_enabled() as $row) {
+    $keys = explode('*', $row->entity_types_content_fields);
+
+    if (($keys[0] == $instance['entity_type'] && $keys[1] == $instance['bundle'] && $keys[2] == $instance['field_name']) || ($keys[3] == $instance['entity_type'] && $keys[4] == $instance['bundle'] && $keys[5] == $instance['field_name'])) {
+      cer_preset_delete($row->entity_types_content_fields);
+    }
+  }
+}
+
+/**
+ * Implements hook_field_delete_field().
+ */
+function cer_field_delete_field($field) {
+  foreach (cer_preset_load_enabled() as $row) {
+    $keys = explode('*', $row->entity_types_content_fields);
+
+    if ($keys[2] == $field['field_name'] || $keys[5] == $field['field_name']) {
+      cer_preset_delete($row->entity_types_content_fields);
+    }
+  }
+}
+
+/**
+ * Implements hook_theme().
+ */
+function cer_theme() {
+  return array(
+    'cer_label' => array(
+      'variables' => array('key' => ''),
+    ),
+  );
+}
+
+function theme_cer_label($variables) {
+  $key = explode(' ', $variables['key']);
+  
+  $local = field_info_instance($key[0], $key[2], $key[1]);
+  $remote = field_info_instance($key[3], $key[5], $key[4]);
+
+  $message = 'Correspond <span title="!local_field">%local_label</span> on !local_entity(s) of type %local_bundle with <span title="!remote_field">%remote_label</span> on !remote_entity(s) of type %remote_bundle.';
+
+  $variables = array(
+    '%local_label' => $local['label'],
+    '!local_field' => $local['field_name'],
+    '!local_entity' => $local['entity_type'],
+    '%local_bundle' => $local['bundle'],
+    '%remote_label' => $remote['label'],
+    '!remote_field' => $remote['field_name'],
+    '!remote_entity' => $remote['entity_type'],
+    '%remote_bundle' => $remote['bundle'],
+  );
+
+  return t($message, $variables);
+}
+
+/**
+ * Implements hook_entity_insert().
+ */
+function cer_entity_insert($entity, $type) {
+  cer_processing_entity('insert', $entity, $type);
+}
+
+/**
+ * Implements hook_entity_update().
+ */
+function cer_entity_update($entity, $type) {
+  cer_processing_entity('update', $entity, $type);
+}
+
+/**
+ * Implements hook_entity_delete().
+ */
+function cer_entity_delete($entity, $type) {
+  cer_processing_entity('delete', $entity, $type);
+}
+
+/**
+ * Load enabled CER presets.
+ */
+function cer_preset_load_enabled() {
+  ctools_include('export');
+  return ctools_export_load_object('cer', 'conditions', array('enabled' => 1));
+}
+
+/**
+ * Return CER preset by key.
+ */
+function cer_preset_load($key) {
+  ctools_include('export');
+  return ctools_export_crud_load('cer', $key);
+}
+
+/**
+ * Return 1 if CER preset specified by given key is enabled.
+ */
+function cer_preset_enabled($key) {
+  $preset = cer_preset_load($key);
+  return empty($preset) ? 0 : $preset->enabled;
+}
+
+/**
+ * Deletes or disables a given CER preset.
+ */
+function cer_preset_delete($key) {
+  ctools_include('export');
+
+  ctools_export_crud_delete('cer', $key);
+  ctools_export_crud_disable('cer', $key);
+
+  ctools_export_load_object_reset('cer');
+}
+
+/**
+ * Process a entity's corresponding entity references.
+ *
+ * @param string $op 
+ *  The operation being performed on the entity (insert, update, or delete).
+ *
+ * @param object $entity
+ *  The entity.
+ *
+ * @param string $entity_type
+ *  The entity type.
+ *
+ * @param array $context
+ *  Either the Batch API context (since this is the callback function used
+ *  during bulk update) or NULL if we're not in a batch job.
+ */
+function cer_processing_entity($op, $entity, $entity_type, &$context = NULL) {
+  // If the entity is of the wrong type, entity_extract_IDs() will throw
+  // EntityMalformedException and rightfully bail out here.
+  list (, , $bundle) = entity_extract_IDs($entity_type, $entity);
+
+  $result = cer_preset_load_enabled();
+
+  foreach ($result as $row) {
+    $keys = explode('*', $row->entity_types_content_fields);
+
+    if ($keys[0] == $entity_type && $keys[1] == $bundle) {
+      try {
+        $handler = new CerHandler($row->entity_types_content_fields, $entity);
+        call_user_func(array($handler, $op));
+      }
+      catch (CerException $e) {
+        if (isset($context)) {
+          $context['results']['errors'][] = $e;
+        }
+        else {
+          throw $e;
+        }
+      }
+    }
+
+    if ($keys[3] == $entity_type && $keys[4] == $bundle) {
+      $preset = implode('*', array($keys[3], $keys[4], $keys[5], $keys[0], $keys[1], $keys[2]));
+
+      try {
+        $handler = new CerHandler($preset, $entity);
+        call_user_func(array($handler, $op));
+      }
+      catch (CerException $e) {
+        if (isset($context)) {
+          $context['results']['errors'][] = $e;
+        }
+        else {
+          throw $e;
+        }
+      }
+    }
+  }
+
+  if (isset($context)) {
+    $context['results']['count']++;
+  }
+}
+
+/**
+ * Batch 'finished' callback.
+ */
+function cer_batch_update_existing_finished($success, $results, $operations) {
+  if ($success) {
+    $message = format_plural($results['count'], '1 entity processed.', '@count entities processed.');
+
+    if (isset($results['errors'])) {
+      $type = 'warning';
+      foreach ($results['errors'] as $e) {
+        drupal_set_message($e->getMessage(), 'error');
+      }
+    }
+    else {
+      $type = 'status';
+    }
+    drupal_set_message($message, $type);
+  }
+  else {
+    // An error occurred. $operations contains the operations that remained unprocessed.
+    $error_operation = reset($operations);
+    $message = 'An error occurred while processing ' . $error_operation[0] . ' with arguments:' . print_r($error_operation[0], TRUE);
+    drupal_set_message($message, 'error');
+  }
+}
+
+/**
+ * Implements hook_ctools_plugin_api().
+ */
+function cer_ctools_plugin_api($owner, $api) {
+  if ($owner == 'cer' && $api == 'default_cer_presets') {
+    return array('version' => 1);
+  }
+}
+
+/**
+ * Update field data.
+ *
+ * @param $node the referenced node to be updated.
+ */
+function _cer_update($entity_type, $entity) {
+  $entity->original = isset($entity->original) ? $entity->original : NULL;
+
+  field_attach_presave($entity_type, $entity);
+  field_attach_update($entity_type, $entity);
+
+  $extract_ids = entity_extract_IDs($entity_type, $entity);
+  $id = array_shift($extract_ids);
+  entity_get_controller($entity_type)->resetCache(array($id));
+}

+ 0 - 204
corresponding_entity_references.admin.inc

@@ -1,204 +0,0 @@
-<?php
-/**
- * @file
- * Admin functionality, separated for performance purposes.
- */
-
-/**
- * The settings form.
- */
-function corresponding_entity_references_settings_form() {
-  $form['intro'] = array('#markup' => t('Check which entity references should listen to each other. When checking a check box a reference on entity type A to entity B will automatically update the entity reference field on entity B adding an entry which points to entity A.'));
-
-  $result = db_query("SELECT field_name, data FROM {field_config} WHERE type = :type AND deleted = 0", array(':type' => 'entityreference'));
-  foreach ($result as $row) {
-    $data = unserialize($row->data);
-    if(empty($data['settings']['handler_settings']['target_bundles'])){
-      	$references[$row->field_name][] = $data['settings']['target_type'];
-    }
-    foreach ($data['settings']['handler_settings']['target_bundles'] as $reference) {
-      if ($reference != '0') {
-        $references[$row->field_name][] = $reference;
-      }
-    }
-  }
-
-  $result = db_query("SELECT fci.field_name, fci.entity_type, fci.bundle FROM {field_config_instance} fci INNER JOIN {field_config} fc ON fc.field_name = fci.field_name WHERE fc.type = :type", array(':type' => 'entityreference'));
-
-  foreach ($result as $row) {
-
-    if (!empty($references[$row->field_name])) {
-      foreach ($references[$row->field_name] as $reference) {
-          $fields_to_compare[] = array('field_type' => $row->field_name, 'bundle' => $row->bundle, 'reference' => $reference, 'entity' => $row->entity_type);
-      }
-    }
-  }
-
-  if (!empty($fields_to_compare)) {
-    $corr_entityrefs = array();
-    foreach ($fields_to_compare as $field) {
-      foreach ($fields_to_compare as $second_field) {
-        if ($field['bundle'] == $second_field['reference'] && $second_field['bundle'] == $field['reference']) {
-          if (!array_key_exists($field['entity'] . ' ' . $field['bundle'] . ' ' . $field['field_type'] . ' ' . 
-                         $second_field['entity'] . ' ' . $second_field['bundle'] . ' ' . $second_field['field_type'], $corr_entityrefs) 
-           && !array_key_exists($second_field['entity'] . ' ' . $second_field['bundle'] . ' ' . $second_field['field_type'] . ' ' . $field['entity'] . ' ' . $field['bundle'] . ' ' . $field['field_type'], $corr_entityrefs)) {
-            $corr_entityrefs[$field['entity'] . ' ' . $field['bundle'] . ' ' . $field['field_type'] . ' ' .
-                      $second_field['entity'] . ' ' . $second_field['bundle'] . ' ' . $second_field['field_type']] = array('entity_1' => $field['entity'], 'bundle_1' => $field['bundle'], 'field_1' => $field['field_type'], 'entity_2' => $second_field['entity'], 'bundle_2' => $second_field['bundle'], 'field_2' => $second_field['field_type']);
-          }
-        }
-      }
-    }
-
-    if (!empty($corr_entityrefs)) {
-      $count = 0;
-
-      foreach ($corr_entityrefs as $key => $corr_entityref) {
-        $formatted_label = corresponding_entity_references_format_label($key);
-        $formatted_key = str_replace(' ', '*', $key);
-
-        $mapping[] = $formatted_key;
-        $form['values'][$count] = array(
-          '#type' => 'fieldset',
-        );
-        $form['values'][$count]['enabled_' . $count] = array(
-          '#type' => 'checkbox',
-          '#default_value' => corresponding_entity_references_preset_enabled($formatted_key),
-          '#title' => $formatted_label,
-        );
-        $count++;
-      }
-
-      //We are using a hidden field to submit the configuration because on some systems the checkbox name length is limited
-      //, using the key would cause the length to be too long see issue #558612
-      $form['mapping'] = array(
-        '#type' => 'hidden',
-        '#value' => serialize($mapping),
-      );
-      $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
-    }
-  }
-  else {
-    $form['text'] = array('#markup' => '<div>' . t('There are no entity types which have a corresponding entity reference') . '</div>');
-  }
-
-
-  return $form;
-}
-
-/**
- * Submit function for settings form.
- */
-function corresponding_entity_references_settings_form_submit($form, $form_values) {
-  ctools_include('export');
-  $query_values = array();
-
-  $mapping = unserialize($form_values['values']['mapping']);
-
-  foreach ($form_values['values'] as $key => $value) {
-    $keys = explode('_', $key);
-    if ($keys[0] == 'enabled') {
-      $query_values[$mapping[$keys[1]]] = $value;
-    }
-  }
-
-  // load all existing presets
-  $presets = ctools_export_crud_load_all('corresponding_entity_references');
-
-  foreach ($query_values as $key => $value) {
-    // get preset object (create new one if it doesn't exist already).
-    $preset = empty($presets[$key]) ? ctools_export_crud_new('corresponding_entity_references') : $presets[$key];
-    // set and save value
-
-    if (empty($preset->entity_types_content_fields)) {
-      $preset->entity_types_content_fields = $key;
-    }
-    $preset->enabled = $value;
-    ctools_export_crud_save('corresponding_entity_references', $preset);
-    // remove from list of presets, so we know which ones are still used
-    if (isset($presets[$key])) unset($presets[$key]);
-  }
-
-  // delete old presets
-  foreach ($presets as $preset) {
-    //ctools_export_crud_delete($preset);
-  }
-
-  drupal_set_message(t('The configuration has been saved'));
-}
-
-/**
- * The update form.
- * Allows updating of current entitys.
- */
-function corresponding_entity_references_update_form() {
-  $form = array();
-
-  $form['intro'] = array(
-    '#value' => t('This will update all the existing entitys for the selected content types so that their entity reference fields are in sync.') . '<br />' . t('This process may take a long time depending on the number of entitys you are updating.') . '<br />' . t('When the process is finished you will see a count of the number of entitys that were updated.')
-  );
-
-  $options = entity_get_info();
-  foreach ($options as $type => $class) {
-    $options[$type] = $class['label'];
-  }
-
-  $form['types'] = array(
-    '#type' => 'checkboxes',
-    '#title' => t('Entity types'),
-    '#options' => $options,
-    '#description' => t('Select the entity types that you want to update.'),
-  );
-
-
-  $form['limit'] = array(
-    '#type' => 'select',
-    '#title' => t('Number of entities to process at once'),
-    '#options' => array(
-      10 => t('10'),
-      20 => t('20'),
-      30 => t('30'),
-      50 => t('50'),
-      75 => t('75'),
-      100 => t('100'),
-      125 => t('125'),
-      150 => t('150'),
-      200 => t('200'),
-      250 => t('250'),
-      300 => t('300'),
-      350 => t('350'),
-      400 => t('400'),
-      450 => t('450'),
-      500 => t('500'),
-    ),
-    '#default_value' => 50,
-    '#description' => t('This process is done in batches. This is the number of entitys processed in each batch. If necessary, reduce the number of entitys to prevent timeouts and memory errors while processing.'),
-  );
-
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => 'submit',
-  );
-
-  return $form;
-}
-
-/**
- * The update form.
- * Allows updating of current entitys.
- */
-function corresponding_entity_references_update_form_validate($form, &$form_state) {
-  $types = array_filter($form_state['values']['types']);
-  if (empty($types)) {
-    form_set_error('types', t('You must select at least one entity type.'));
-  }
-}
-
-/**
- * The update form.
- * Allows updating of current entitys.
- */
-function corresponding_entity_references_update_form_submit($form, &$form_state) {
-  $types = array_filter($form_state['values']['types']);
-  $types = array_keys($types);
-  corresponding_entity_references_batch_index_remaining($types, $form_state['values']['limit']);
-}

+ 0 - 339
corresponding_entity_references.crud.inc

@@ -1,339 +0,0 @@
-<?php
-/**
- * @file
- * Include file providing corresponding node reference insert, update, and
- * delete handling.
- */
-
-/**
- * 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],
- * );
- */
-function corresponding_entity_references_insert($home_entity, $keys) {
-  $types = array(
-    'home' => $keys['home_entity_type'],
-    'away' => $keys['away_entity_type'],
-  );
-
-  $ids = _corresponding_entity_references_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 = _corresponding_entity_references_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']);
-                }
-              }
-              _corresponding_entity_references_update($keys['away_entity_type'], $referenced_entity);
-            }
-          }
-        }
-      }
-    }
-  }
-}
-
-/**
- * Change corresponding references on node updating.
- *
- * Corresponding changes are made for any references removed or added.
- */
-/**
- *
- * $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],
- * );
- */
-function corresponding_entity_references_update($home_entity, $keys, $process_unchanged = FALSE) {
-  $types = array(
-    'home' => $keys['home_entity_type'],
-    'away' => $keys['away_entity_type'],
-  );
-
-  $ids = _corresponding_entity_references_entity_ids($types);
-
-  // Since home_entity is just being saved, $old_entity and $home_entity are different!
-  $old_entity = $home_entity->original;
-
-  //$old_entity = $old_entity[$home_entity->$ids['home']];
-  $old = $new = array();
-
-  // Determine the nodereference values before the update.
-  if (isset($old_entity->$keys['home_field']) && is_array($old_entity->$keys['home_field'])) {
-    foreach ($old_entity->$keys['home_field'] as $lang => $fields) {
-      foreach ($fields as $reference) {
-        if (!empty($reference['target_id'])) {
-          $old[] = $reference['target_id'];
-        }
-      }
-    }
-  }
-
-  // Determine the entityreference values after the update.
-  if (isset($home_entity->$keys['home_field']) && is_array($home_entity->$keys['home_field'])) {
-    foreach ($home_entity->$keys['home_field'] as $lang => $fields) {
-      foreach ($fields as $reference) {
-        if (!empty($reference['target_id'])) {
-          $new[] = $reference['target_id'];
-        }
-      }
-    }
-  }
-
-  if ($old == $new){
-    return;
-  }
-
-  // Handle removed references.
-  if (!empty($old) ) {
-    foreach ($old as $data) {
-      if ($removed = array_diff($old, $new)) {
-        foreach ($removed as $id) {
-
-          // Load the referenced node if it is of the specified away type.
-          if ($referenced_entity = entity_load($keys['away_entity_type'], array($id), NULL, FALSE)) {
-	    $referenced_entity = $referenced_entity[$id];
-            // Self-references are handled by the node_reference module anyway.
-            $referenced_entity->bundle_type = _corresponding_entity_references_entity_get_bundle($referenced_entity, $keys['away_entity_type']);
-            if ($referenced_entity->bundle_type == $keys['away_bundle'] && $id != $home_entity->$ids['home']) {
-              if (isset($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE]) && is_array($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE])) {
-                // Iterate through the away node's references.
-                foreach ($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE] as $key => $value){
-                  // Remove references to the deleted node.
-                  if ($value['target_id'] && $value['target_id'] == $home_entity->$ids['home']) {
-                    unset($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE][$key]);
-                    _corresponding_entity_references_update($keys['away_entity_type'], $referenced_entity);
-                    break;
-                  }
-                }
-              }
-            }
-          }
-        }
-      }
-    }
-  }
-  // Handle added references.
-  // No array diff a reference overload could of happend or a mass update.
-  if ($added = $new) {
-    foreach ($added as $id) {
-      // Load the referenced entity if it is of the specified away type.
-      if ($referenced_entity = entity_load($keys['away_entity_type'], array($id), NULL, FALSE)) {
-	$referenced_entity = $referenced_entity[$id];
-        // Self-references are handled by the node_reference module anyway.
-
-        $referenced_entity->bundle_type = _corresponding_entity_references_entity_get_bundle($referenced_entity, $keys['away_entity_type']);
-        if ($referenced_entity->bundle_type == $keys['away_bundle'] && $id != $home_entity->$ids['home']) {
-          // Detect whether the reference already exists.
-          $exists = FALSE;
-                  
-          if (isset($referenced_entity->{$keys['away_field']}[$referenced_entity->language]) || !empty($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE])) {
-            foreach ($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE] as $data) {
-              if ($data['target_id'] == $home_entity->$ids['home']) {
-                $exists = TRUE;
-                break;
-              }
-            }
-          }
-
-          // Empty places are removed.
-          // Yes this means the deltas change on the away node when a
-          // reference is made on the home node.
-          $values = array();
-          if (isset($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE])) {
-            foreach ($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE] as $value) {
-              if (!empty($value['target_id'])) {
-                $values[] = $value;
-              }
-            }
-          }
-          $referenced_entity->{$keys['away_field']}[LANGUAGE_NONE] = $values;
-          // Add the new reference. Don't create a duplicate.
-          if (!$exists) {
-            // Get the allowed values.
-            $unlimited = FALSE;
-            $field = field_info_field($keys['away_field']);
-            if ($field) {
-              if ($field['cardinality'] == -1) {
-                $unlimited = TRUE;
-                $allowed_references = 0;
-              }
-              else {
-                $allowed_references = $field['cardinality'];
-              }
-              // Check for reference overloading.
-              $references = count($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE]) + 1;
-              if (($allowed_references >= $references) || $unlimited) {
-                $referenced_entity->{$keys['away_field']}[LANGUAGE_NONE][] = array('target_id' => $home_entity->$ids['home']);
-                _corresponding_entity_references_update($keys['away_entity_type'], $referenced_entity);
-              }
-              else {
-                $t_reference = format_plural($references, '1 reference', '@count references');
-                $t_allowed = format_plural($allowed_references, '1 reference is', '@count references are');
-                drupal_set_message(
-                  t('Reference overloading: @title would of had @t_reference and only @t_allowed permitted. Before adding a reference, you would need to <a href="@url">edit</a> @title to remove an existing reference and resave this node to have make it correspond. Or you could allow this reference instance to have more references, go to the field settings for this instance.',
-                    array(
-                      '@title' => $referenced_entity->title,
-                      '@url' => url('node/' . $referenced_entity->$ids['away'] . '/edit'),
-                      '@t_reference' => $t_reference,
-                      '@t_allowed' => $t_allowed,
-                    )
-                  ),
-                  'error'
-                );
-              }
-            }
-          }
-        }
-      }
-    }
-  }
-}
-
-/**
- * Remove corresponding references on node deletion.
- **/
-/**
- *
- * $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],
- * );
- */
-function corresponding_entity_references_delete($home_entity, $keys, $process_unchanged = FALSE) {
-  $types = array(
-    'home' => $keys['home_entity_type'],
-    'away' => $keys['away_entity_type'],
-  );
-
-  $ids = _corresponding_entity_references_entity_ids($types);
-
-  // Iterate through the field's references.
-  foreach ($home_entity->$keys['home_field'] as $lang => $langdata) {
-    foreach ($langdata as $reference) {
-      if (!empty($reference['target_id'])) {
-        // Load the referenced node if it is of the specified away type.
-        if ($referenced_entity = entity_load($keys['away_entity_type'], array($reference['target_id']), NULL, FALSE)) {
-          $referenced_entity = $referenced_entity[$reference['target_id']];
-          $referenced_entity->bundle_type = _corresponding_entity_references_entity_get_bundle($referenced_entity, $keys['away_entity_type']);
-          if ($referenced_entity->bundle_type == $keys['away_bundle']) {
-            // Iterate through the away entity's references.
-            foreach ($referenced_entity->{$keys['away_field']}[$lang] as $key => $value) {
-              // Remove references to the deleted node.
-              if ($value['target_id'] && $value['target_id'] == $home_entity->$ids['home']) {
-                unset($referenced_entity->{$keys['away_field']}[$lang][$key]);
-                _corresponding_entity_references_update($keys['away_entity_type'], $referenced_entity);
-                break;
-              }
-            }
-          }
-        }
-      }
-    }
-  }
-}
-
-/**
- * Update field data.
- *
- * @param $node the referenced node to be updated.
- */
-function _corresponding_entity_references_update($entity_type, $entity) {
-  field_attach_presave($entity_type, $entity);
-  field_attach_update($entity_type, $entity);
-}
-
-/**
- * Helper function. Returns entity "ID" keys.
- *
- * @param $entity_types Array containing "home" and "away" keys.
- */
-function _corresponding_entity_references_entity_ids($entity_types) {
-  $types = entity_get_info();
-  foreach($types as $key => $type){
-    $entity_type_id[$key] = $type['entity keys']['id'];
-  }
-
-  $ids = array(
-    'home' => $entity_type_id[$entity_types['home']],
-    'away' => $entity_type_id[$entity_types['away']],
-  );
-  return $ids;
-}
-
-
-
-/**
- * Helper function. Returns entity "bundle" keys.
- *
- * @param $entity_types Array containing "home" and "away" keys.
- */
-function _corresponding_entity_references_entity_bundles($entity_types) {
-  $types = entity_get_info();
-
-  foreach($types as $key => $type){
-    $entity_type_id[$key] = $type['entity keys']['bundle'];
-  }
-
-  $bundles = array(
-    'home' => $entity_type_id[$entity_types['home']],
-    'away' => $entity_type_id[$entity_types['away']],
-  );
-  return $bundles;
-}
-
-function _corresponding_entity_references_entity_get_bundle($entity, $entity_type) {
-  $info = entity_get_info($entity_type);
-  if (empty($info['entity keys']['bundle'])) {
-    return $entity_type;
-  } else {
-    return $entity->{$info['entity keys']['bundle']};
-  }
-}

+ 0 - 14
corresponding_entity_references.info

@@ -1,14 +0,0 @@
-name = Corresponding Entity References
-description = Syncs the Entity reference between two node types which have an entityreference to each other.  
-core = 7.x
-dependencies[] = entityreference
-dependencies[] = ctools
-
-
-
-; Information added by drupal.org packaging script on 2012-06-15
-version = "7.x-1.x-dev"
-core = "7.x"
-project = "cer"
-datestamp = "1339718736"
-

+ 0 - 252
corresponding_entity_references.module

@@ -1,252 +0,0 @@
-<?php
-/**
- * @file
- * Module file providing the "corresponding entity reference" module main
- * functions.
- */
-
-/**
- * Implements hook_menu().
- */
-function corresponding_entity_references_menu() {
-  $items = array();
-  $items['admin/config/system/corresponding_entity_references'] = array(
-    'title' => 'Corresponding entity references',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('corresponding_entity_references_settings_form'),
-    'access arguments' => array('administer corresponding entity references settings'),
-    'file' => 'corresponding_entity_references.admin.inc',
-    'type' => MENU_NORMAL_ITEM,
-  );
-
-  $items['admin/config/system/corresponding_entity_references/references'] = array(
-    'title' => 'Corresponding entity references',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('corresponding_entity_references_settings_form'),
-    'access arguments' => array('administer corresponding entity references settings'),
-    'file' => 'corresponding_entity_references.admin.inc',
-    'type' => MENU_DEFAULT_LOCAL_TASK,
-  );
-
-  $items['admin/config/system/corresponding_entity_references/update'] = array(
-    'title' => 'Update existing entities',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('corresponding_entity_references_update_form'),
-    'access arguments' => array('administer corresponding entity references settings'),
-    'file' => 'corresponding_entity_references.admin.inc',
-    'type' => MENU_LOCAL_TASK,
-  );
-
-  return $items;
-}
-
-/**
- * Implements hook_permission().
- */
-function corresponding_entity_references_permission() {
-  return array(
-    'administer corresponding entity references settings' => array(
-      'title' => t('Administer corresponding entity reference settings'),
-      'description' => t('Administer corresponding entity reference settings'),
-    )
-  );
-}
-
-/**
- * Formats a label.
- */
-function corresponding_entity_references_format_label($key) {
-  $key = explode(' ', $key);
-  return t('Field instance:"!field1" on Entity type:"!entity1" - Bundle type:"!bundle1" <b>Corresponds with</b> Field instance:"!field2" on Entity type:"!entity2" Bundle type:"!bundle2"',
-    array('!entity1' => $key[0], '!bundle1' => $key[1], '!field1' => $key[2], '!entity2' => $key[3], '!bundle2' => $key[4], '!field2' => $key[5]));
-}
-
-/**
- * Implements hook_entity_insert().
- */
-function corresponding_entity_references_entity_insert($entity, $type) {
-  corresponding_entity_references_processing_entity('insert', $entity, $type);
-}
-
-/**
- * Implements hook_entity_update().
- */
-function corresponding_entity_references_entity_update($entity, $type) {
-  corresponding_entity_references_processing_entity('update', $entity, $type);
-}
-
-/**
- * Implements hook_entity_delete().
- */
-function corresponding_entity_references_entity_delete($entity, $type) {
-  corresponding_entity_references_processing_entity('delete', $entity, $type);
-}
-
-/**
- * Load enabled CNR presets.
- */
-function corresponding_entity_references_preset_load_enabled() {
-  ctools_include('export');
-  return ctools_export_load_object('corresponding_entity_references', 'conditions', array('enabled' => 1));
-}
-
-/**
- * Return CNR preset by key.
- */
-function corresponding_entity_references_preset_load($key) {
-  ctools_include('export');
-  return ctools_export_crud_load('corresponding_entity_references', $key);
-}
-
-/**
- * Return 1 if CNR preset specified by given key is enabled.
- */
-function corresponding_entity_references_preset_enabled($key) {
-  $preset = corresponding_entity_references_preset_load($key);
-  return empty($preset) ? 0 : $preset->enabled;
-}
-
-/**
- * Process a entity's corresponding entity references.
- *
- * @param $op the operation being performed on the entity.
- * @param $entity the entity object
- * @param $process_unchanged whether or not to process entity reference fields
- *        whose values have not changed.
- */
-function corresponding_entity_references_processing_entity($op, $entity, $type, $process_unchanged = FALSE) { 
-  module_load_include('inc', 'corresponding_entity_references', 'corresponding_entity_references.crud');
-
-  $result = corresponding_entity_references_preset_load_enabled();
-
-  while ($row = array_shift($result)) {
-    $key = explode('*', $row->entity_types_content_fields);
-    if(($type == $key[0]) || ($type == $key[3])){
-	
-      $entity->home = _corresponding_entity_references_entity_get_bundle($entity, $type);
-
-      switch ($entity->home) {
-        case $key[1]:
-          // Create an array to pass to op function instead of 6 arguments.
-          $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],
-          );
-          $args = array($entity, $keys, $process_unchanged);
-          $function = 'corresponding_entity_references_' . $op;
-          call_user_func_array($function, $args);
-          if ($key[0] != $key[2]) {
-            break;
-          }
-
-        // Fall through.
-        case $key[4]:
-          $keys = array(
-            'home_entity_type' => $key[3],
-            'home_bundle' => $key[4], 
-            'home_field' => $key[5],
-            'away_entity_type' => $key[0],
-            'away_bundle' => $key[1],
-            'away_field' => $key[2],
-          );
-          $args = array($entity, $keys, $process_unchanged);
-          $function = 'corresponding_entity_references_' . $op;
-          call_user_func_array($function, $args);
-          break;
-      }
-    }
-  }
-}
-
-
-
-/**
- * Submit a batch job to index the remaining, unindexed content.
- */
-function corresponding_entity_references_batch_index_remaining($types, $limit) {
-  $batch = array(
-    'operations' => array(
-      array(
-        'corresponding_entity_references_batch_update_existing_entities',
-        array($types, $limit)
-      ),
-    ),
-    'finished' => 'corresponding_entity_references_batch_update_existing_finished',
-    'title' => t('Processing'),
-    'init_message' => t('Preparing to update corresponding entity references for existing entities...'),
-    'progress_message' => t('Processing entities...'),
-    'error_message' => t('Corresponding entity references - existing entity update has encountered an error.'),
-  );
-  batch_set($batch);
-}
-
-/**
- * Batch Operation Callback
- *
- * @see corresponding_entity_references_batch_index_remaining()
- */
-function corresponding_entity_references_batch_update_existing_entities($types, $limit, &$context) {
-  // If we are on our first time through.
-  if (!isset($context['sandbox']['progress'])) {
-    $context['sandbox']['progress'] = 0;
-    $context['sandbox']['current_entity'] = 0;
-    $context['sandbox']['max'] = db_query("SELECT COUNT(DISTINCT nid) FROM {node} WHERE type IN (:types)", array(':types' => $types))->fetchField();
-  }
-
-  $nids = array();
-  $args = $types;
-  $args['current_entity'] = $context['sandbox']['current_entity'];
-  // Get entity IDs to update.
-  $result = db_query_range("SELECT nid FROM {node} WHERE type IN (:types) AND nid > :args ORDER BY nid", 0, $limit, array(':types' => $types, ':args' => $args['current_entity']));
-
-  while ($row = $result->fetchObject()) {
-    $entity = entity_load($row->nid);
-    corresponding_entity_references_processing_entity('update', $entity, $type, TRUE);
-
-    // Update our progress information.
-    $context['sandbox']['progress']++;
-    $context['sandbox']['current_entity'] = $entity->nid;
-    $context['message'] = t('Processed @current of @total entitys', array('@current' => $context['sandbox']['progress'], '@total' => $context['sandbox']['max']));
-  }
-
-  // Inform the batch engine that we are not finished,
-  // and provide an estimation of the completion level we reached.
-  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
-    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
-  }
-  // Put the total into the results section when we're finished so we can show
-  // it to the admin.
-  if ($context['finished']) {
-    $context['results']['count'] = $context['sandbox']['progress'];
-  }
-}
-
-/**
- * Batch 'finished' callback.
- *
- * @see corresponding_entity_references_batch_index_remaining()
- */
-function corresponding_entity_references_batch_update_existing_finished($success, $results, $operations) {
-  if ($success) {
-    $type = 'status';
-    $message = format_plural($results['count'], '1 entity processed successfully.', '@count entitys processed successfully.');
-  }
-  else {
-    $type = 'error';
-    // An error occurred.
-    // $operations contains the operations that remained unprocessed.
-    $error_operation = reset($operations);
-    $message = 'An error occurred while processing ' . $error_operation[0] . ' with arguments:' . print_r($error_operation[0], TRUE);
-  }
-  drupal_set_message($message, $type);
-}
-
-function corresponding_entity_references_ctools_plugin_api($owner, $api) {
-  if ($owner == 'corresponding_entity_references' && $api == 'default_corresponding_entity_references_presets') {
-    return array('version' => 1);
-  }
-}

+ 0 - 84
duplicates-PDO.patch

@@ -1,84 +0,0 @@
-diff --git a/corresponding_entity_references.crud.inc b/corresponding_entity_references.crud.inc
-index 3736e98..4ad5e83 100644
---- a/corresponding_entity_references.crud.inc
-+++ b/corresponding_entity_references.crud.inc
-@@ -52,19 +52,17 @@ function corresponding_entity_references_insert($home_entity, $keys) {
-                 // referenced.
-                 $exists = FALSE;
-                 foreach ($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE] as $key => $value) {
--                  if ($value[$ids['away']] == $home_entity->$ids['home']) {
-+                  if ($value['target_id'] == $home_entity->$ids['home']) {
-                     $exists = TRUE;
-                     break;
-                   }
-                 }
- 
-                 if (!$exists) {
--                  $referenced_entity->{$keys['away_field']}[LANGUAGE_NONE][] = array($ids['home'] => $home_entity->$ids['home']);
-+                  $referenced_entity->{$keys['away_field']}[LANGUAGE_NONE][] = array('target_id' => $home_entity->$ids['home']);
-                 }
-               }
--
-               _corresponding_entity_references_update($keys['away_entity_type'], $referenced_entity);
--              
-             }
-           }
-         }
-@@ -114,14 +112,7 @@ function corresponding_entity_references_update($home_entity, $keys, $process_un
-     }
-   }
- 
--
--  // If we are processing unchanged references, remove all new references
--  // from the old references.
--  if ($process_unchanged) {
--    $old  = array_diff($old, $new);
--  }
--
--  // Determine the nodereference values after the update.
-+  // Determine the entityreference values after the update.
-   if (isset($home_entity->$keys['home_field']) && is_array($home_entity->$keys['home_field'])) {
-     foreach ($home_entity->$keys['home_field'] as $lang => $fields) {
-       foreach ($fields as $reference) {
-@@ -132,8 +123,12 @@ function corresponding_entity_references_update($home_entity, $keys, $process_un
-     }
-   }
- 
-+  if ($old == $new){
-+    return;
-+  }
-+
-   // Handle removed references.
--  if ( !empty($old) ) {
-+  if (!empty($old) ) {
-     foreach ($old as $data) {
-       if ($removed = array_diff($old, $new)) {
-         foreach ($removed as $id) {
-@@ -174,10 +169,9 @@ function corresponding_entity_references_update($home_entity, $keys, $process_un
-         if ($referenced_entity->bundle_type == $keys['away_bundle'] && $id != $home_entity->$ids['home']) {
-           // Detect whether the reference already exists.
-           $exists = FALSE;
--
-+                  
-           if (isset($referenced_entity->{$keys['away_field']}[$referenced_entity->language]) && !empty($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE])) {
-             foreach ($referenced_entity->{$keys['away_field']}[LANGUAGE_NONE] as $data) {
--
-               if ($data['target_id'] == $home_entity->$ids['home']) {
-                 $exists = TRUE;
-                 break;
-@@ -271,7 +265,6 @@ function corresponding_entity_references_delete($home_entity, $keys, $process_un
-           $referenced_entity->bundle_type = _corresponding_entity_references_entity_get_bundle($referenced_entity, $keys['away_entity_type']);
-           if ($referenced_entity->bundle_type == $keys['away_bundle']) {
-             // Iterate through the away entity's references.
--
-             foreach ($referenced_entity->{$keys['away_field']}[$lang] as $key => $value) {
-               // Remove references to the deleted node.
-               if ($value['target_id'] && $value['target_id'] == $home_entity->$ids['home']) {
-@@ -293,6 +286,7 @@ function corresponding_entity_references_delete($home_entity, $keys, $process_un
-  * @param $node the referenced node to be updated.
-  */
- function _corresponding_entity_references_update($entity_type, $entity) {
-+  field_attach_presave($entity_type, $entity);
-   field_attach_update($entity_type, $entity);
- }
- 

+ 437 - 0
handler.inc

@@ -0,0 +1,437 @@
+<?php
+
+/**
+ * @file
+ * Contains base code for CER handlers, which are objects responsible for
+ * creating, updating and deleting corresponding references between entities.
+ */
+
+/**
+ * Exception related to CER operations.
+ */
+class CerException extends Exception {
+}
+
+interface CerHandlerInterface {
+
+  /**
+   * @constructor
+   *
+   * @param string $preset
+   *  The CER preset string, in the format:
+   *  entity_a*bundle_a*field_a*entity_b*bundle_b*field_b.
+   *
+   * @param $entity.
+   *  The local (home) entity to be wrapped by this instance.
+   */
+  public function __construct($preset, $entity);
+
+  /**
+   * Create reciprocal references on referenced entities after the
+   * local entity has been created.
+   */
+  public function insert();
+
+  /**
+   * Delete reciprocal references on entities the local entity is no
+   * longer referencing, and create new reciprocal references, after
+   * the local entity has been updated.
+   */
+  public function update();
+
+  /**
+   * Delete all reciprocal references after the local entity is deleted.
+   */
+  public function delete();
+  
+  /**
+   * Check if $entity is referenced by the local entity.
+   *
+   * @param object $entity
+   *  The remote entity.
+   *
+   * @return boolean
+   */
+  public function references($entity);
+
+  /**
+   * Check if the local entity is referenced by $entity.
+   *
+   * @param object $entity
+   *  The remote entiy.
+   *
+   * @return boolean
+   */
+  public function referencedBy($entity);
+  
+  /**
+   * Check if the remote entity can reference the local entity, and vice-versa.
+   *
+   * @param object $entity
+   *  The remote entity.
+   *
+   * @return boolean
+   */
+  public function referenceable($entity);
+
+  /**
+   * Create a reference to the local entity on the remote entity, and vice-versa
+   * if needed. Should throw CerException if the reference(s) can't be created
+   * for any reason.
+   *
+   * @param object $entity
+   */
+  public function reference($entity);
+
+  /**
+   * Delete all references to the remote entity from the local entity,
+   * and delete reciprocal references from the remote entity.
+   *
+   * @param object $entity.
+   */
+  public function dereference($entity);
+
+}
+
+/**
+ * @class
+ * Base class for CER handlers. All this does is parse the preset
+ * and store instance info about the local and remote fields.
+ */
+abstract class CerHandlerBase {
+
+  /**
+   * Local field instance definition.
+   */
+  protected $local;
+
+  /**
+   * Remote field instance definition.
+   */
+  protected $remote;
+
+  public function __construct($preset) {
+    $keys = explode('*', $preset);
+
+    if (sizeof($keys) != 6) {
+      throw new CerException(t('Invalid configuration: @preset', array('@preset' => $preset)));
+    }
+
+    $this->local = field_info_instance($keys[0], $keys[2], $keys[1]);
+    if ($this->local) {
+      $this->local['field'] = field_info_field($keys[2]);
+    }
+    else {
+      throw new CerException(t('Local field instance does not exist.'));
+    }
+
+    $this->remote = field_info_instance($keys[3], $keys[5], $keys[4]);
+    if ($this->remote) {
+      $this->remote['field'] = field_info_field($keys[5]);
+    }
+    else {
+      throw new CerException(t('Remote field instance does not exist.'));
+    }
+  }
+
+}
+
+/**
+ * @class
+ * Generic CER handler with rudimentary language handling.
+ */
+class CerHandler extends CerHandlerBase implements CerHandlerInterface {
+
+  /**
+   * The local (home) entity.
+   */
+  protected $entity;
+
+  /**
+   * The local entity's ID.
+   */
+  protected $id;
+
+  /**
+   * Implements CerHandlerInterface::__construct().
+   */
+  public function __construct($preset, $entity) {
+    parent::__construct($preset);
+
+    // If $entity is of the wrong type, entity_extract_IDs()
+    // will throw EntityMalformedException here.
+    $extract_ids = entity_extract_IDs($this->local['entity_type'], $entity);
+    $this->id = array_shift($extract_ids);
+
+    $this->entity = $entity;
+  }
+
+  /**
+   * Implements CerHandlerInterface::insert().
+   */
+  public function insert() {
+    foreach ($this->getReferencedEntities() as $referenced_entity) {
+      $this->reference($referenced_entity);
+      _cer_update($this->remote['entity_type'], $referenced_entity);
+    }
+  }
+
+  /**
+   * Implements CerHandlerInterface::update().
+   */
+  public function update() {
+    $original = isset($this->entity->original) ? $this->entity->original : $this->entity;
+
+    $deleted = array_diff($this->getReferenceIDs($original, $this->local), $this->getLocalReferenceIDs());
+    if ($deleted) {
+      $entities = entity_load($this->remote['entity_type'], $deleted);
+      foreach ($entities as $referenced_entity) {
+        $this->dereference($referenced_entity);
+        _cer_update($this->remote['entity_type'], $referenced_entity);
+      }
+    }
+
+    $this->insert();
+  }
+
+  /**
+   * Implements CerHandlerInterface::delete().
+   */
+  public function delete() {
+    foreach ($this->getReferencedEntities() as $referenced_entity) {
+      $this->dereference($referenced_entity);
+      _cer_update($this->remote['entity_type'], $referenced_entity);
+    }
+  }
+
+  /**
+   * Implements CerHandlerInterface::references().
+   */  
+  public function references($entity) {
+    return in_array($this->getRemoteEntityID($entity), $this->getLocalReferenceIDs());
+  }
+
+  /**
+   * Implements CerHandlerInterface::referencedBy().
+   */
+  public function referencedBy($entity) {
+    return in_array($this->id, $this->getRemoteReferenceIDs($entity));
+  }
+
+  /**
+   * Implements CerHandlerInterface::referenceable().
+   */
+  public function referenceable($entity) {
+    $id = $this->getRemoteEntityID($entity);
+
+    $allowed = array(
+      entityreference_get_selection_handler(
+        $this->local['field'],
+        $this->local,
+        $this->local['entity_type'],
+        $this->entity
+      )
+        ->validateReferencableEntities(array($id)),
+      entityreference_get_selection_handler(
+        $this->remote['field'],
+        $this->remote,
+        $this->remote['entity_type'],
+        $entity
+      )
+        ->validateReferencableEntities(array($this->id)),
+    );
+
+    return in_array($id, $allowed[0]) && in_array($this->id, $allowed[1]);
+  }
+
+  /**
+   * Implements CerHandlerInterface::reference().
+   */
+  public function reference($entity) {
+    if ($this->referenceable($entity)) {
+      try {
+        $this->addReferenceTo($entity);
+      }
+      catch (CerException $e) {
+        // Fail silently
+      }
+    
+      try {
+        $this->addReferenceFrom($entity);
+      }
+      catch (CerException $e) {
+        // Fail silently
+      }
+    }
+    else {
+      throw new CerException(t('Cannot create invalid reference to remote entity.'));
+    }
+  }
+
+  /**
+   * Implements CerHandlerInterface::dereference().
+   */
+  public function dereference($entity) {
+    if ($this->references($entity)) {
+      $id = $this->getRemoteEntityID($entity);
+
+      foreach ($this->entity->{$this->local['field_name']} as $language => $references) {
+        foreach ($references as $delta => $reference) {
+          if ($reference['target_id'] == $id) {
+            unset($this->entity->{$this->local['field_name']}[$language][$delta]);
+          }
+        }
+      }
+    }
+
+    if ($this->referencedBy($entity)) {
+      foreach ($entity->{$this->remote['field_name']} as $language => $references) {
+        foreach ($references as $delta => $reference) {
+          if ($reference['target_id'] == $this->id) {
+            unset($entity->{$this->remote['field_name']}[$language][$delta]);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * Creates a reference to the local entity on the remote entity. Throws CerException
+   * if the local entity is already referenced by the remote entity, or if the remote
+   * field cannot hold any more values.
+   *
+   * @param object $entity
+   *  The remote entity.
+   */ 
+  protected function addReferenceFrom($entity) {
+    if ($this->referencedBy($entity)) {
+      throw new CerException(t('Cannot create duplicate reference from remote entity.'));
+    }
+    elseif ($this->filled($this->getRemoteReferenceIDs($entity), $this->remote['field'])) {
+      throw new CerException(t('Remote field cannot support any more references.'));
+    }
+    else {
+      $languages = field_available_languages($this->remote['entity_type'], $this->remote['field']);
+      foreach ($languages as $language) {
+        $entity->{$this->remote['field_name']}[$language][] = array('target_id' => $this->id);
+      }
+    }
+  }
+
+  /**
+   * Creates a reference to the remote entity on the local entity. Throws CerException
+   * if the local entity already references the remote entity, or if the field cannot
+   * hold any more values.
+   *
+   * @param object $entity
+   *  The remote entity.
+   */
+  protected function addReferenceTo($entity) {
+    $id = $this->getRemoteEntityID($entity);
+
+    if ($this->references($entity)) {
+      throw new CerException(t('Cannot create duplicate reference to remote entity.'));
+    }
+    elseif ($this->filled($this->getLocalReferenceIDs(), $this->local['field'])) {
+      throw new CerException(t('Local field cannot support any more references.'));
+    }
+    else {
+      $languages = field_available_languages($this->local['entity_type'], $this->local['field']);
+      foreach ($languages as $language) {
+        $this->entity->{$this->local['field_name']}[$language][] = array('target_id' => $id);
+      }
+    }
+  }
+
+  /**
+   * Get the ID of the remote entity. If the entity is of the wrong type,
+   * EntityMalformedException will be thrown.
+   *
+   * @param object $entity
+   *  The remote entity.
+   *
+   * @return mixed
+   *  The remote entity ID.
+   */
+  protected function getRemoteEntityID($entity) {
+    $extract_ids = entity_extract_IDs($this->remote['entity_type'], $entity);
+    return array_shift($extract_ids);
+  }
+
+  /**
+   * Gets all the entities referenced by the local entity.
+   *
+   * @return array
+   *  Array of fully loaded referenced entities keyed by ID, or empty
+   *  array if nothing has been referenced.
+   */
+  protected function getReferencedEntities() {
+    $IDs = $this->getLocalReferenceIDs();
+    return $IDs ? entity_load($this->remote['entity_type'], $IDs) : array();
+  }
+
+  /**
+   * Gets the IDs of the entities referenced by the local entity.
+   *
+   * @return array
+   *  Array of entity IDs, empty array if there are no references.
+   */
+  protected function getLocalReferenceIDs() {
+    return $this->getReferenceIDs($this->entity, $this->local);
+  }
+
+  /**
+   * Gets the IDs of the entities referenced by $entity.
+   *
+   * @param object $entity
+   *  The remote entity.
+   *
+   * @return array
+   *  Array of entity IDs, empty array if there are no references.
+   */
+  protected function getRemoteReferenceIDs($entity) {
+    return $this->getReferenceIDs($entity, $this->remote);
+  }
+
+  /**
+   * Check if a field can support any more values. Formerly known as
+   * "reference overloading".
+   *
+   * @param array $references
+   *  The values in the field.
+   *
+   * @param $field
+   *  Field definition (i.e., from field_info_field).
+   *
+   * @return boolean
+   */
+  private function filled($references, $field) {
+    return $field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && sizeof($references) >= $field['cardinality'];
+  }
+
+  /**
+   * Gets all the referenced entity IDs from a specific field on $entity.
+   *
+   * @param object $entity
+   *  The entity to scan for references.
+   *
+   * @param array $field
+   *  Field or instance definition.
+   *
+   * @return array
+   *  Array of unique IDs, empty if there are no references or the field
+   *  does not exist on $entity.
+   */
+  private function getReferenceIDs($entity, $field) {
+    $IDs = array();
+    if (isset($entity->{$field['field_name']})) {
+      foreach ($entity->{$field['field_name']} as $references) {
+        foreach ($references as $reference) {
+          $IDs[] = $reference['target_id'];
+        }
+      }
+    }
+    return array_unique(array_filter($IDs));
+  }
+
+}

+ 16 - 0
tests/cer_tests.info

@@ -0,0 +1,16 @@
+name = "CER Tests"
+core = "7.x"
+description = "Automated tests for CER."
+hidden = TRUE
+
+dependencies[] = simpletest
+dependencies[] = cer
+
+files[] = crud.test
+files[] = fields.test
+; Information added by drupal.org packaging script on 2013-05-01
+version = "7.x-2.x-dev"
+core = "7.x"
+project = "cer"
+datestamp = "1367412087"
+

+ 1 - 0
tests/cer_tests.module

@@ -0,0 +1 @@
+<?php

+ 168 - 0
tests/crud.test

@@ -0,0 +1,168 @@
+<?php
+
+class CerCrudTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'CRUD',
+      'group' => 'Corresponding Entity Reference',
+      'description' => 'Tests basic CER functionality.',
+    );
+  }
+
+  public function setUp() {
+    parent::setUp('field', 'field_sql_storage', 'ctools', 'entityreference', 'cer');
+
+    field_create_field(array(
+      'field_name' => 'field_user',
+      'type' => 'entityreference',
+      'cardinality' => -1,
+      'settings' => array(
+        'target_type' => 'user',
+      ),
+    ));
+    field_create_field(array(
+      'field_name' => 'field_node',
+      'type' => 'entityreference',
+      'cardinality' => -1,
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+    ));
+
+    field_create_instance(array(
+      'field_name' => 'field_user',
+      'entity_type' => 'node',
+      'bundle' => 'page',
+    ));
+    field_create_instance(array(
+      'field_name' => 'field_node',
+      'entity_type' => 'user',
+      'bundle' => 'user',
+    ));
+
+    db_insert('cer')->fields(array(
+      'entity_types_content_fields' => 'node*page*field_user*user*user*field_node',
+      'enabled' => TRUE,
+    ))->execute();
+  }
+
+  public function testImplicitReferenceCreation() {
+    $uid = $this->drupalCreateUser()->uid;
+    
+    $referrers = array();
+    for ($i = 0; $i < 5; $i++) {
+      $referrers[] = $this->drupalCreateNode(array(
+        'type' => 'page',
+        'field_user' => array(
+          'und' => array(
+            array('target_id' => $uid),
+          ),
+        ),
+      ))->nid;
+    }
+
+    $references = array();
+    foreach (user_load($uid, TRUE)->field_node['und'] as $reference) {
+      $references[] = $reference['target_id'];
+    }
+    $this->assertFalse(array_diff($referrers, $references), 'Creating 5 referrers to a single entity creates 5 corresponding references on that entity.', 'CER');
+  }
+
+  public function testDuplicateReferencePrevention() {
+    $uid = $this->drupalCreateUser()->uid;
+
+    $this->drupalCreateNode(array(
+      'type' => 'page',
+      'field_user' => array(
+        'und' => array(
+          array('target_id' => $uid),
+          array('target_id' => $uid),
+        ),
+      ),
+    ));
+
+    $account = user_load($uid, TRUE);
+    $this->assertEqual(sizeof($account->field_node['und']), 1, 'Creating two references to an entity from a single referrer creates one corresponding reference.', 'CER');
+  }
+
+  public function testExplicitReferenceCreation() {
+    $uid = $this->drupalCreateNode()->uid;
+
+    $node = $this->drupalCreateNode(array('type' => 'page'));
+    $node->field_user['und'][0]['target_id'] = $uid;
+    node_save($node);
+
+    $account = user_load($uid, TRUE);
+    $this->assertEqual($account->field_node['und'][0]['target_id'], $node->nid, 'Creating an explicit reference between to unrelated entities creates a corresponding reference.', 'CER');
+  }
+
+  public function testExplicitDereference() {
+    $uid = $this->drupalCreateUser()->uid;
+
+    $nid = $this->drupalCreateNode(array(
+      'type' => 'page',
+      'field_user' => array(
+        'und' => array(
+          array('target_id' => $uid),
+        ),
+      ),
+    ))->nid;
+
+    $account = user_load($uid, TRUE);
+    $account->field_node = array();
+    user_save($account);
+
+    $node = node_load($nid, NULL, TRUE);
+    $this->assertFalse($node->field_user, 'Explicitly clearing a reference from the referenced entity clears the corresponding reference on the referrer.', 'CER');
+  }
+
+  public function testReferrerDeletion() {
+    $uid = $this->drupalCreateUser()->uid;
+    
+    $referrers = array();
+    for ($i = 0; $i < 5; $i++) {
+      $referrers[] = $this->drupalCreateNode(array(
+        'type' => 'page',
+        'field_user' => array(
+          'und' => array(
+            array('target_id' => $uid),
+          ),
+        ),
+      ))->nid;
+    }
+
+    node_delete($referrers[0]);
+
+    $references = array();
+    foreach (user_load($uid, TRUE)->field_node['und'] as $reference) {
+      $references[] = $reference['target_id'];
+    }
+    $this->assertFalse(in_array($referrers[0], $references), 'Deleting a referrer clears corresponding reference on the referenced entity.', 'CER');
+  }
+
+  public function testReferencedEntityDeletion() {
+    $uid = $this->drupalCreateUser()->uid;
+
+    $referrers = array();
+    for ($i = 0; $i < 5; $i++) {
+      $referrers[] = $this->drupalCreateNode(array(
+        'type' => 'page',
+        'field_user' => array(
+          'und' => array(
+            array('target_id' => $uid),
+          ),
+        ),
+      ))->nid;
+    }
+    user_delete($uid);
+
+    $cleared = 0;
+    foreach ($referrers as $nid) {
+      $node = node_load($nid, NULL, TRUE);
+      $cleared += (int) empty($node->field_user);
+    }
+    $this->assertEqual($cleared, sizeof($referrers), 'Deleting a referenced entity clears all references to it.', 'CER');
+  }
+
+}

+ 67 - 0
tests/fields.test

@@ -0,0 +1,67 @@
+<?php
+
+class CerFieldTestCase extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Fields',
+      'group' => 'Corresponding Entity Reference',
+      'description' => 'Tests integration with the Field API.',
+    );
+  }
+
+  public function setUp() {
+    parent::setUp('field', 'field_sql_storage', 'ctools', 'entityreference', 'cer');
+
+    field_create_field(array(
+      'field_name' => 'field_user',
+      'type' => 'entityreference',
+      'cardinality' => -1,
+      'settings' => array(
+        'target_type' => 'user',
+      ),
+    ));
+    field_create_field(array(
+      'field_name' => 'field_node',
+      'type' => 'entityreference',
+      'cardinality' => -1,
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+    ));
+
+    field_create_instance(array(
+      'field_name' => 'field_user',
+      'entity_type' => 'node',
+      'bundle' => 'page',
+    ));
+    field_create_instance(array(
+      'field_name' => 'field_node',
+      'entity_type' => 'user',
+      'bundle' => 'user',
+    ));
+    
+    ctools_include('export');
+
+    $preset = ctools_export_crud_new('cer');
+    $preset->entity_types_content_fields = 'node*page*field_user*user*user*field_node';
+    $preset->enabled = TRUE;
+
+    ctools_export_crud_save('cer', $preset);
+  }
+
+  public function testFieldInstanceDelete() {
+    field_delete_instance(field_info_instance('user', 'field_node', 'user'));
+
+    $preset = cer_preset_load('node*page*field_user*user*user*field_node');
+    $this->assertNull($preset, 'Deleting a field instance clears CER presets for that instance.');
+  }
+
+  public function testFieldDelete() {
+    field_delete_field('field_user');
+
+    $preset = cer_preset_load('node*page*field_user*user*user*field_node');
+    $this->assertNull($preset, 'Deleting a field clears CER presets for that field.');
+  }
+
+}