You are here

function restws_field_collection_property_set in RESTful Web Services Field Collection 7

Sets a field collection property.

1 string reference to 'restws_field_collection_property_set'
restws_field_collection_entity_property_info_alter in ./restws_field_collection.module
Implements hook_entity_property_info_alter().

File

./restws_field_collection.module, line 173
RESTful Web Services Field collection module.

Code

function restws_field_collection_property_set(&$data, $name, $values, $langcode, $type, $info) {

  // Get information about field collections.
  $field_collections = restws_field_collection_info();

  // Figure out what field collection this name maps to.
  $field_name = '';
  foreach ($field_collections as $fc_name => $fc_info) {
    if ($name == $fc_info['alias']) {
      $field_name = $fc_name;
      break;
    }
  }

  // If a field collection field name wasn't found, bail.
  if (empty($field_name)) {
    return;
  }

  // If this is an existing entity, delete existing field collection item(s).
  //
  // This works because $data (the entity) does not get reloaded between
  // subsequent calls to this function. So if a field collection supports
  // multiple values, and we are replacing old field collection items on the
  // entity, we can see what the old ones were in $data and delete those.
  // Creating new field collection items will not update $data, so we don't run
  // the risk of deleting the new ones right after we create them.
  if (empty($data->is_new)) {
    if (!empty($data->{$field_name}[LANGUAGE_NONE])) {
      foreach ($data->{$field_name}[LANGUAGE_NONE] as $old_fc) {
        if (!empty($old_fc['value'])) {
          field_collection_item_delete($old_fc['value']);
        }
      }
    }
  }

  // If the field collection does not support multiple values, wrap the values
  // in an array.
  if (empty($field_collections[$field_name]['multiple'])) {
    $values = array(
      $values,
    );
  }

  // Iterate through the values.
  foreach ($values as $key => $value) {

    // If all of the field values are empty, skip it.
    $empty = TRUE;
    foreach ($field_collections[$field_name]['fields'] as $field_alias => $field_info) {
      if (!empty($value[$field_alias])) {
        $empty = FALSE;
        break;
      }
    }
    if ($empty) {
      continue;
    }

    // Create a new field collection item.
    restws_field_collection_item_create($field_name, $type, $data, $value);
  }
}