You are here

function paragraphs_items_add in Paragraphs table 7

Add a new paragraphs item.

File

./pharagraphs_table.pages.inc, line 82

Code

function paragraphs_items_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'])) {
    drupal_set_message(t('Too many items.'), 'error');
    return '';
  }
  $paragraphs_items = entity_create('paragraphs_items', 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.
  $paragraphs_items
    ->setHostEntity($entity_type, $entity, $langcode, FALSE);
  $label = $paragraphs_items
    ->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.
  global $user;
  $account = user_load($user->uid);
  if (!entity_access('create', 'paragraphs_items', $paragraphs_items, $account)) {
    return MENU_ACCESS_DENIED;
  }
  return drupal_get_form('paragraphs_items_form', $paragraphs_items);
}