function ajax_example_unique_autocomplete_validate

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.

Parameters

array $form: Form API form.

array $form_state: Form API form state.

File

ajax_example/ajax_example_autocomplete.inc, line 143

Code

function ajax_example_unique_autocomplete_validate($form, &$form_state) {
    $title = $form_state['values']['node'];
    $matches = array();
    // 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;
        }
    }
    else {
        $nid = db_select('node')->fields('node', array(
            'nid',
        ))
            ->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,
        )));
    }
}