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

Node title validation handler.

Validate handler to convert our string like "Some node title [3325]" 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.


array $form: Form API form.

array $form_state: Form API form state.


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


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

  // 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)));
  // BUT: 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
  // *could* just emit a form_error() as below.
  else {
    $nid = db_select('node')
      ->fields('node', array('nid'))
      ->condition('title', db_like($title) . '%', 'LIKE')
      ->range(0, 1)

  // 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)));