You are here

function user_reference_autocomplete_validate in References 7.2

Validation callback for a user_reference autocomplete element.

1 string reference to 'user_reference_autocomplete_validate'
user_reference_field_widget_form in user_reference/user_reference.module
Implements hook_field_widget_form().

File

user_reference/user_reference.module, line 711
Defines a field type for referencing a user from a node.

Code

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

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

      // Explicit uid. Check that the 'name' part matches the actual name for
      // the uid.
      list(, $name, $uid) = $matches;
      if (!empty($name)) {
        $names = _user_reference_get_user_names(array(
          $uid,
        ));
        if ($name != $names[$uid]) {
          form_error($element, t('%name: name mismatch. Please check your selection.', array(
            '%name' => $instance['label'],
          )));
        }
      }
    }
    else {

      // No explicit uid (the submitted value was not populated by autocomplete
      // selection). Get the uid of a referencable user from the entered name.
      $options = array(
        'string' => $value,
        'match' => 'equals',
        'limit' => 1,
      );
      $references = user_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 name. ATM, we pick the first
        // matching candidate...
        $uid = key($references);
      }
      else {
        form_error($element, t('%name: found no valid user with that name.', array(
          '%name' => $instance['label'],
        )));
      }
    }
  }

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