You are here

function entityreference_autocreate_get_entity_by_title in Entityreference Autocreate 7

Fetch the named entity for the field, create it if not found.

Parameters

array $field_info: As loaded from field_info_field()

string $title: Title to search for.

Return value

object|NULL Pre-existing or new entity. is_new should be set on it if it is fresh. Returns NULL on unexpected failure. A failure should probably be caught.

3 calls to entityreference_autocreate_get_entity_by_title()
entityreference_autocreate_feeds_set_target in ./entityreference_autocreate.feeds.inc
Entity reference callback for mapping.
entityreference_autocreate_validate in ./entityreference_autocreate.module
Make a missing target if asked for by name.
entityreference_autocreate_validate_tags in ./entityreference_autocreate.module
Validate handler that makes things up on the fly if needed.

File

./entityreference_autocreate.module, line 242
Intercepts entityreference autocomplete submission validation and creates a target node on the fly if it doesn't yet exist.

Code

function entityreference_autocreate_get_entity_by_title($field_info, $title) {
  $title = trim($title);
  if (empty($title)) {
    return NULL;
  }

  // Take "label (entity id)', match the id from parenthesis.
  if (preg_match("/.+\\((\\d+)\\)/", $title, $matches)) {
    return $matches[1];
  }

  // Try to get a match from the input string when the user didn't use the
  // autocomplete but filled in a value manually.
  $handler = entityreference_get_selection_handler($field_info);

  // Search for matches (exact), limit to 2 so we can detect if there is a
  // potential conflict.
  $entities = $handler
    ->getReferencableEntities($title, '=', 2);

  // Case where $entities looks like $entities[BUNDLE][ETID] = HTML.
  if (is_array(reset($entities))) {

    // Extract items from results. The return is keyed by bundle.
    $target_bundle = entityreference_autocreate_get_target_bundle($field_info);
    if (!empty($target_bundle)) {
      $entities = $entities[$target_bundle];
    }
  }
  if (count($entities) == 1) {

    // Exact match, no confusion, use that.
    return key($entities);
  }
  if (count($entities) > 1) {

    // More than one match.
    // This is a genuine form validation error I can't automate.
    return NULL;
  }

  // By now we've eliminated the options. There is no match.
  if (count($entities) == 0) {

    // Now make one of the named things.
    return entityreference_autocreate_new_entity($field_info, $title);
  }
  return NULL;
}