You are here

function field_collection_item_add in Field collection 7

Add a new field collection item.

@todo: Support optionally passing in the revision_id and langcode parameters.

1 string reference to 'field_collection_item_add'
field_collection_menu in ./field_collection.module
Implements hook_menu().

File

./field_collection.pages.inc, line 100
Provides the field collection item view / edit / delete pages.

Code

function field_collection_item_add($field_name, $entity_type, $entity_id, $revision_id = NULL, $langcode = NULL) {
  $info = entity_get_info();
  if (!isset($info[$entity_type])) {
    return MENU_NOT_FOUND;
  }
  $result = entity_load($entity_type, array(
    $entity_id,
  ));
  $entity = reset($result);
  if (!$entity) {
    return MENU_NOT_FOUND;
  }

  // Ensure the given entity is of a bundle that has an instance of the field.
  list($id, $rev_id, $bundle) = entity_extract_ids($entity_type, $entity);
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  if (!$instance) {
    return MENU_NOT_FOUND;
  }

  // Check field cardinality.
  $field = field_info_field($field_name);
  $langcode = !empty($field['translatable']) ? entity_language($entity_type, $entity) : LANGUAGE_NONE;
  if (!($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || !isset($entity->{$field_name}[$langcode]) || count($entity->{$field_name}[$langcode]) < $field['cardinality'])) {
    return MENU_ACCESS_DENIED;
  }
  $field_collection_item = entity_create('field_collection_item', array(
    'field_name' => $field_name,
  ));

  // Do not link the field collection item with the host entity at this point,
  // as during the form-workflow we have multiple field collection item entity
  // instances, which we don't want link all with the host.
  // That way the link is going to be created when the item is saved.
  $field_collection_item
    ->setHostEntity($entity_type, $entity, $langcode, FALSE);
  $label = $field_collection_item
    ->translatedInstanceLabel();
  $title = $field['cardinality'] == 1 ? $label : t('Add new !instance_label', array(
    '!instance_label' => $label,
  ));
  drupal_set_title($title);

  // Make sure the current user has access to create a field collection item.
  if (!entity_access('create', 'field_collection_item', $field_collection_item)) {
    return MENU_ACCESS_DENIED;
  }
  return drupal_get_form('field_collection_item_form', $field_collection_item);
}