You are here

function restws_field_collection_item_create in RESTful Web Services Field Collection 7

Create a field collection item and attach it to an entity.

Parameters

$field_name: The field collection field name.

$entity_type: The host entity type.

$entity: The host entity.

$values: The field values.

1 call to restws_field_collection_item_create()
restws_field_collection_property_set in ./restws_field_collection.module
Sets a field collection property.

File

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

Code

function restws_field_collection_item_create($field_name, $entity_type, $entity, $values) {

  // Create a new field_collection attached to the entity.
  $field_collection = entity_create('field_collection_item', array(
    'field_name' => $field_name,
  ));
  $field_collection
    ->setHostEntity($entity_type, $entity);

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

  // If there are no fields in this field collection, bail.
  if (empty($field_collections[$field_name]['fields'])) {
    return;
  }

  // Iterate through the field collection fields.
  foreach ($field_collections[$field_name]['fields'] as $field_alias => $field_info) {

    // If no value is available for this field, skip it.
    if (empty($values[$field_alias])) {
      continue;
    }

    // If the value is an array, it might be an entity reference, so look for
    // an ID.
    if (is_array($values[$field_alias]) && !empty($values[$field_alias]['id'])) {
      $values[$field_alias] = $values[$field_alias]['id'];
    }

    // If the field name is empty, skip it.
    if (empty($field_info['field_name'])) {
      continue;
    }

    // Get the values for this field.
    $field_values = $values[$field_alias];

    // If the field values are not an array, wrap it.
    if (!is_array($field_values)) {
      $field_values = array(
        $field_values,
      );
    }

    // Iterate through the field values and save them to the field collection.
    foreach ($field_values as $key => $field_value) {
      $field_collection->{$field_info['field_name']}[LANGUAGE_NONE][$key] = array(
        $field_info['field_value'] => $field_value,
      );
    }
  }

  // Save the field collection.
  entity_save('field_collection_item', $field_collection);
}