You are here

public static function EntityHelper::updateFieldValuesStorage in Helper 7

An lightest-weight version of entity save that invokes field storage.

Parameters

string $entity_type: The entity type of $entity.

object $entity: The entity object to update.

array $fields: (optional) An optional array of field names that if provided will only cause those specific fields to be saved, if values are provided.

Throws

\InvalidArgumentException

File

lib/EntityHelper.php, line 208

Class

EntityHelper

Code

public static function updateFieldValuesStorage($entity_type, $entity, array $fields = array()) {
  list($id, , $bundle) = entity_extract_ids($entity_type, $entity);
  if (empty($id)) {
    throw new InvalidArgumentException(t('Cannot call EntityHelper::updateFieldValues() on an unsaved entity.'));
  }

  // Let any module update field data before the storage engine, accumulating
  // saved fields along the way.
  $skip_fields = array();
  foreach (module_implements('field_storage_pre_update') as $module) {
    $function = $module . '_field_storage_pre_update';
    $function($entity_type, $entity, $skip_fields);
  }

  // Collect the storage backends used by the remaining fields in the entities.
  $storages = array();
  foreach (field_info_instances($entity_type, $bundle) as $instance) {
    $field = field_info_field_by_id($instance['field_id']);
    $field_id = $field['id'];
    $field_name = $field['field_name'];

    // Check if we care about saving this field or not.
    if (!empty($fields) && !in_array($field_name, $fields)) {
      continue;
    }

    // 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 => $storage_fields) {
    $storage_info = field_info_storage_types($storage);
    module_invoke($storage_info['module'], 'field_storage_write', $entity_type, $entity, FIELD_STORAGE_UPDATE, $storage_fields);
  }

  // Clear the cache for this entity now.
  entity_get_controller($entity_type)
    ->resetCache(array(
    $id,
  ));
}