You are here

public function FlexiformFormEntityFieldCollection::getEntity in Flexiform 7

Get the entity for the form.

Return value

A loaded or created entity object ready for use in the form.

Overrides FlexiformFormEntityBase::getEntity

File

includes/form_entity/field_collection.form_entity.inc, line 15
Contains class for a basic entity getter.

Class

FlexiformFormEntityFieldCollection
Form entity to get a field collection item.

Code

public function getEntity() {
  parent::getEntity();
  $settings = $this->settings;
  $base_type = $this
    ->getParamType('base');

  // Get the base entity.
  $base_entity = $this
    ->getParam('base');

  // Check we have enough information to load the entity.
  if (!$base_entity) {
    return FALSE;
  }
  if ($settings['delta'] == 'new') {
    $field = field_info_field($settings['bundle']);
    $item_count = count($base_entity->{$settings['bundle']}[LANGUAGE_NONE]);
    if ($field['cardinality'] < 0 || $item_count < $field['cardinality']) {
      $target_entity = entity_create('field_collection_item', array(
        'field_name' => $settings['bundle'],
      ));
      $target_entity
        ->setHostEntity($base_type, $base_entity);
    }
  }
  else {
    if (empty($base_entity->{$this->getter['field_name']}[LANGUAGE_NONE][$settings['delta']]['value'])) {
      if ($settings['create']) {
        $target_entity = entity_create('field_collection_item', array(
          'field_name' => $settings['bundle'],
        ));
        $target_entity
          ->setHostEntity($base_type, $base_entity);
      }
    }
    else {

      // Load the entity;
      $target_id = $base_entity->{$this->getter['field_name']}[LANGUAGE_NONE][$settings['delta']]['value'];
      $target_entity = entity_load_single('field_collection_item', $target_id);
    }
  }
  if (!$target_entity) {
    return FALSE;
  }

  // Check the entity is the right bundle.
  list(, , $bundle) = entity_extract_ids('field_collection_item', $target_entity);
  if ($bundle != $settings['bundle']) {
    return FALSE;
  }
  return $target_entity;
}