You are here

function multifield_field_presave in Multifield 7

Same name and namespace in other branches
  1. 7.2 multifield.field.inc \multifield_field_presave()

Implements hook_field_presave().

1 call to multifield_field_presave()
multifield_field_insert in ./multifield.field.inc
Implements hook_field_insert().

File

./multifield.field.inc, line 214
Field integration for the Multifield module.

Code

function multifield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  $machine_name = multifield_extract_multifield_machine_name($field);

  // Gather the original field values from the parent entity if it has them.
  $original_items = !empty($entity->original->{$field['field_name']}[$langcode]) ? $entity->original->{$field['field_name']}[$langcode] : array();
  foreach ($items as $delta => $item) {

    // If an ID is not yes assigned, add one, unless this hook is invoked
    // from the default value widget on the field instance (empty $entity).
    // If this is a new or cloned entity, ensure that the internal ID values
    // are reset.
    if (empty($item['id']) && !empty($entity)) {
      $item['id'] = multifield_get_next_id();
    }
    elseif (!empty($item['id']) && empty($entity->original)) {
      $item['id'] = multifield_get_next_id();
    }
    $pseudo_entity = _multifield_field_item_to_entity($machine_name, $item);

    // Add the original item value to the pseudo-entity.
    if (!empty($original_items[$delta])) {
      $pseudo_entity->original = _multifield_field_item_to_entity($machine_name, $original_items[$delta]);
    }

    // Ensure the revision flag is set.
    if (!empty($entity->revision)) {
      $pseudo_entity->revision = TRUE;
    }

    // Run each sub-field through hook_field_presave().
    _multifield_field_invoke('presave', $machine_name, 'multifield', $pseudo_entity, $langcode);
    unset($pseudo_entity->original);
    $items[$delta] = _multifield_field_entity_to_item($pseudo_entity);
  }

  // Invoke hook_field_presave() with the sub-field data attached to a stub of
  // the parent entity.
  $stub_entity = _multifield_create_stub_entity_with_subfield_data($machine_name, $items, $original_items, $entity_type, $entity, $langcode);
  _multifield_field_invoke('presave', $machine_name, $entity_type, $stub_entity, $langcode);

  // Serialize the multifield values into separate columns for saving into the
  // field table.
  array_walk($items, 'multifield_item_serialize', $machine_name);
}