You are here

function node_reference_autocomplete_validate in References 7.2

Validation callback for a node_reference autocomplete element.

1 string reference to 'node_reference_autocomplete_validate'
node_reference_field_widget_form in node_reference/node_reference.module
Implements hook_field_widget_form().

File

node_reference/node_reference.module, line 708
Defines a field type for referencing one node from another.

Code

function node_reference_autocomplete_validate($element, &$form_state, $form) {
  $field = field_widget_field($element, $form_state);
  $instance = field_widget_instance($element, $form_state);
  $value = $element['#value'];
  $nid = NULL;
  if (!empty($value)) {

    // Check whether we have an explicit "[nid:n]" input.
    preg_match('/^(?:\\s*|(.*) )?\\[\\s*nid\\s*:\\s*(\\d+)\\s*\\]$/', $value, $matches);
    if (!empty($matches)) {

      // Explicit nid. Check that the 'title' part matches the actual title for
      // the nid.
      list(, , $nid) = $matches;
      if (!empty($nid)) {
        $real_title = db_select('node', 'n')
          ->fields('n', array(
          'title',
        ))
          ->condition('n.nid', $nid)
          ->execute()
          ->fetchField();
        if (empty($real_title)) {
          form_error($element, t('%name: No node found. Please check your selection.', array(
            '%name' => $instance['label'],
          )));
        }
      }
    }
    else {

      // No explicit nid (the submitted value was not populated by autocomplete
      // selection). Get the nid of a referencable node from the entered title.
      $options = array(
        'string' => $value,
        'match' => 'equals',
        'limit' => 1,
      );
      $references = node_reference_potential_references($field, $options);
      if ($references) {

        // @todo The best thing would be to present the user with an
        // additional form, allowing the user to choose between valid
        // candidates with the same title. ATM, we pick the first
        // matching candidate...
        $nid = key($references);
      }
      else {
        form_error($element, t('%name: found no valid post with that title.', array(
          '%name' => $instance['label'],
        )));
      }
    }
  }

  // Set the element's value as the node id that was extracted from the entered
  // input.
  form_set_value($element, $nid, $form_state);
}