1 ajax_example_autocomplete.inc ajax_example_node_by_author_autocomplete_validate($form, &$form_state)

Validate handler to convert our title string into a nid.

In case the user did not actually use the autocomplete or have a valid string there, we'll try to look up a result anyway giving it our best guess.

Since the user chose a unique node, we must now use the same one in our submit handler, which means we need to look in the string for the nid.

This handler looks complex because it's ambitious (and tries to punt and find a node if they've entered a valid username and part of a title), but you *could* just do a form_error() if nothing were found, forcing people to use the autocomplete to look up the relevant items.

Parameters

array $form: Form API form.

array $form_state: Form API form state.

File

modules/examples/ajax_example/ajax_example_autocomplete.inc, line 346
ajax_example_autocomplete.inc

Code

function ajax_example_node_by_author_autocomplete_validate($form, &$form_state) {
  $title = $form_state['values']['node'];
  $author = $form_state['values']['author'];
  $matches = array();
  $nid = 0;

  // We must have a valid user.
  $account = user_load_by_name($author);
  if (empty($account)) {
    form_error($form['author'], t('You must choose a valid author username'));
    return;
  }
  // This preg_match() looks for the last pattern like [33334] and if found
  // extracts the numeric portion.
  $result = preg_match('/\[([0-9]+)\]$/', $title, $matches);
  if ($result > 0) {
    // If $result is nonzero, we found a match and can use it as the index into
    // $matches.
    $nid = $matches[$result];
    // Verify that it's a valid nid.
    $node = node_load($nid);
    if (empty($node)) {
      form_error($form['node'], t('Sorry, no node with nid %nid can be found', array('%nid' => $nid)));
      return;
    }
  }
  // Not everybody will have JavaScript turned on, or they might hit ESC and not
  // use the autocomplete values offered. In that case, we can attempt to come
  // up with a useful value. This is not absolutely necessary, and we can just
  // show a form error. We find the first matching title and assume that is
  // adequate.
  else {
    $nid = db_select('node')
      ->fields('node', array('nid'))
      ->condition('uid', $account->uid)
      ->condition('title', db_like($title) . '%', 'LIKE')
      ->range(0, 1)
      ->execute()
      ->fetchField();
  }

  // Now, if we somehow found a nid, assign it to the node. If we failed, emit
  // an error.
  if (!empty($nid)) {
    $form_state['values']['node'] = $nid;
  }
  else {
    form_error($form['node'], t('Sorry, no node starting with %title can be found', array('%title' => $title)));
  }
}