Contributions API

nodereference_autocomplete_validate

Definition

nodereference_autocomplete_validate($element, &$form_state)
contributions/cck/modules/nodereference/nodereference.module, line 609

Description

Validate an autocomplete element.

Remove the wrapper layer and set the right element's value. This will move the nested value at 'field-name-0-nid-nid' back to its original location, 'field-name-0-nid'.

Code

<?php
function nodereference_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 (!empty($value)) {
    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.
      $nids = _nodereference_potential_references($field, $value, TRUE);
      if (empty($nids)) {
        form_error($element[$field_key], t('%name: found no valid post with that title.', array('%name' => t($field['widget']['label']))));
      }
      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 = array_shift(array_keys($nids));
      }
    }
  }
  form_set_value($element, $nid, $form_state);
  return $element;
}
?>