How to create autocomplete form field in drupal
1. Create a form
print drupal_get_form('admin_add_users');
function admin_add_users(&$form_state, $pid) {
$form['admins_names'] = array(
'#type' => 'textfield',
'#title' => t('Conversation Admins'),
'#autocomplete_path' => 'itechmentors/autocomplete/multiple',
'#description' => t('Enter multiple names as comma separated values Like name1, name2, name3'),
'#default_value' => isset($def['admins_names']) ? implode(",", unserialize($def['admins_names'])) : NULL,
'#required' => FALSE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save')
);
return $form;
}
2. Implementation of hook_menu().
function HOOK_menu() {
$items = array();
$items['itechmentors/autocomplete'] = array(
'title' => '',
'page callback' => 'itechmentors_autocomplete',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['itechmentors/autocomplete/multiple'] = array(
'title' => '',
'page callback' => 'itechmentors_autocomplete_multiple',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
3. Add the page callback function for 'itechmentors/autocomplete' to return the result
/**
* Returns JS array for users autocomplete fields.
*/
function itechmentors_autocomplete($string) {
$matches = array();
$result = db_query_range("SELECT u.name FROM {users} u WHERE LOWER(u.name) LIKE LOWER('%s%%')", $string, 0, 10);
while ($user = db_fetch_object($result)) {
$matches[$user->name] = check_plain($user->name);
}
if (stripos(variable_get('anonymous', t('Anonymous')), $string) === 0) {
$matches[variable_get('anonymous', t('Anonymous'))] = variable_get('anonymous', t('Anonymous'));
}
exit(drupal_json($matches));
}
4. Add the page callback function for 'itechmentors/autocomplete/multiple' to return multiple result
/**
* Returns JS array for users autocomplete fields. Supports multiple entries separated by a comma.
*/
function itechmentors_autocomplete_multiple($string) {
// The user enters a comma-separated list of users. We only autocomplete the last user.
$array = drupal_explode_tags($string);
// Fetch last tag
$last_string = trim(array_pop($array));
$matches = array();
$result = db_query_range("SELECT u.name FROM {users} u WHERE LOWER(u.name) LIKE LOWER('%s%%')", $last_string, 0, 10);
$prefix = count($array) ? implode(', ', $array) .', ' : '';
while ($user = db_fetch_object($result)) {
$matches[$prefix . $user->name] = check_plain($user->name);
}
// This will add anonymous to the list, but not sorted.
if (stripos(variable_get('anonymous', t('Anonymous')), $last_string) === 0) {
$matches[$prefix . variable_get('anonymous', t('Anonymous'))] = variable_get('anonymous', t('Anonymous'));
}
exit(drupal_json($matches));
}