How to create an autocomplete form element in Drupal 7
<?php
function demo_menu() {
$items['demo-autocomplete-test'] = array(
'title' => 'Test autocomplete',
'page callback' => 'drupal_get_form',
'page arguments' => array('demo_form'),
'access arguments' => array('view published content'),
'type' => MENU_NORMAL_ITEM,
);
$items['demo-autocomplete-engine'] = array(
'page callback' => 'demo_autocomplete',
'access arguments' => array('view published content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function demo_form($form, &$form_state) {
$form = array();
$form['colors'] = array(
'#title' => t('Colors'),
'#type' => 'textfield',
'#maxlength' => 60,
'#autocomplete_path' => 'demo-autocomplete-engine',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
function demo_autocomplete($text) {
$results = array();
$query = db_select('colors', 'c');
$query
->condition('c.color', '%' . db_like($text) . '%', 'LIKE')
->fields('c', array('color'))
->orderBy('color', 'ASC');
$colors = $query->execute();
foreach ($colors as $row) {
$results[$row->color] = check_plain($row->color);
}
drupal_json_output($results);
}
Tags: