How to create a autocomplete field

You know how to create a module and that it's easier to add a autocomplete field like node reference or user reference to an existing content type with CCK.

When you have your on module you can create an autocomplete field to any field of the database

<?php
/**
 * Implementation of hook_menu().
 *
 */
function siteanalyzer_menu() {
   
$items = array(); 

   
$items['siteanalyzer/autocomplete'] = array(
     
'page callback' => 'siteanalyzer_autocomplete',
     
'access arguments' => array('administer siteanalyzer'),
     
'type' => MENU_CALLBACK,
    );

    return
$items;
}

/**
 * Creates a form
 *
 */
function siteanalyzer_start_form() {

 
$form['siteanalyzer']['autopath'] = array(
   
'#title' => t('Path'),
   
'#type' => 'textfield',
   
'#description' => t('Specify a path to analyze.'),
   
'#autocomplete_path' => 'siteanalyzer/autocomplete',
  );
}

/**
 * Selects titles to autocomplete field
 *
 */
function siteanalyzer_autocomplete($string) {
 
$matches = array();
 
 
// searching in database, only title column
 
$result = db_query('SELECT title FROM {node} WHERE LOWER(title) LIKE LOWER("%%%s%%") LIMIT 10', $string);
 
 
// found wrote into $matches
 
while ($data = db_fetch_object($result)) {
   
$matches[$data->title] = check_plain($data->title);
   
$matches[$data->title] = '<div class="reference-autocomplete">'. $data->title . '</div>';
  }
 
 
drupal_json($matches);

  exit();
}


?>

Might not be needed depending on where you show the autocomplete fields and what theme and other modules you are using, but if you don't get the autocomplete features like the gray/blue spinning circle then you might have to add some scripts in your page template, block, call or in hook_init

<?php
//the module way
function siteanalyzer_init(){
 
drupal_add_js("misc/drupal.js?");
 
drupal_add_js("misc/autocomplete.js?");
}
?>


//one other template way
<script type="text/javascript" src="/misc/drupal.js?G"></script>
<script type="text/javascript" src="/misc/autocomplete.js?G"></script>
Knowledge keywords: