You are here

function noderefcreate_autocomplete_validate in Node Reference Create 6

Same name and namespace in other branches
  1. 7 noderefcreate.module \noderefcreate_autocomplete_validate()
1 string reference to 'noderefcreate_autocomplete_validate'
noderefcreate_autocomplete_process in ./noderefcreate.module

File

./noderefcreate.module, line 97

Code

function noderefcreate_autocomplete_validate($element, &$form_state) {
  $field_name = $element['#field_name'];
  $type_name = $element['#type_name'];
  $field = content_fields($field_name, $type_name);
  $field_key = $element['#columns'][0];
  $delta = $element['#delta'];
  $value = $element['#value'][$field_key];
  $nid = NULL;
  if (strlen(trim($value)) > 0) {
    preg_match('/^(?:\\s*|(.*) )?\\[\\s*nid\\s*:\\s*(\\d+)\\s*\\]$/', $value, $matches);
    if (!empty($matches)) {

      // Explicit [nid:n].
      list(, $title, $nid) = $matches;
      if (!empty($title) && ($n = node_load($nid)) && $title != $n->title) {
        form_error($element[$field_key], t('%name: title mismatch. Please check your selection.', array(
          '%name' => t($field['widget']['label']),
        )));
      }
    }
    else {

      // No explicit nid.
      $reference = _nodereference_potential_references($field, $value, 'equals', NULL, 1);
      if (empty($reference)) {
        $newnode = NULL;
        if (is_array($field['referenceable_types'])) {
          foreach (array_filter($field['referenceable_types']) as $related_type) {
            $newnode->type = $related_type;
          }
        }
        global $user;
        $newnode->uid = $user->uid;
        $newnode->title = $value;
        if (module_exists('i18n')) {
          $newnode->language = i18n_get_lang();
        }
        else {
          $newnode->language = language_default();
        }
        if (module_exists('comment')) {
          $newnode->comment = variable_get("comment_{$newnode->type}", COMMENT_NODE_READ_WRITE);
        }
        node_save($newnode);
        $nid = $newnode->nid;
      }
      else {

        // 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($reference);
      }
    }
  }
  else {
    if (strlen($value) > 0) {

      // if we got here then the user filled the name with spaces
      form_error($element, t('%name: title is empty. Please check your input.', array(
        '%name' => $instance['label'],
      )));
    }
  }
  form_set_value($element, $nid, $form_state);
}