You are here

function field_property_field_attach_update in Field property 7

Implements hook_field_attach_update().

File

./field_property.module, line 31
Allows fields to be properties and have the same value across all revisions.

Code

function field_property_field_attach_update($entity_type, $entity) {
  if (!field_property_entity_type_has_revisions($entity_type)) {
    return;
  }
  $revision_ids = field_property_get_all_entity_revision_ids($entity_type, $entity, TRUE);
  if (empty($revision_ids)) {
    return;
  }
  $info = entity_get_info($entity_type);
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);

  // Collect the storage backends used by the remaining fields in the entities.
  $storages = array();
  foreach (field_info_instances($entity_type, $bundle) as $instance) {
    if (empty($instance['is_property'])) {

      // Only care about fields that are properties.
      continue;
    }
    $field = field_info_field_by_id($instance['field_id']);
    $field_id = $field['id'];
    $field_name = $field['field_name'];

    // Leave the field untouched if $entity comes with no $field_name property,
    // but empty the field if it comes as a NULL value or an empty array.
    // Function property_exists() is slower, so we catch the more frequent
    // cases where it's an empty array with the faster isset().
    if (isset($entity->{$field_name}) || property_exists($entity, $field_name)) {

      // Collect the storage backend if the field has not been written yet.
      if (!isset($skip_fields[$field_id])) {
        $storages[$field['storage']['type']][$field_id] = $field_id;
      }
    }
  }

  // Field storage backends save any remaining unsaved fields.
  foreach ($storages as $storage => $fields) {

    // Save for each revision.
    foreach ($revision_ids as $revision_id) {

      // Create a cloned revision object based on the entity.
      $revision = clone $entity;
      $revision->{$info['entity keys']['revision']} = $revision_id;
      $storage_info = field_info_storage_types($storage);
      module_invoke($storage_info['module'], 'field_storage_write', $entity_type, $revision, FIELD_STORAGE_UPDATE, $fields);
    }
  }
}