Drupal: Autocomplete for any CCK text field or any form field

At present no module is available for CCK autocomplete field but you can achieve this by custom code : Edit 03-March-2012: Check out http://drupal.org/project/autocomplete_widgets

Step 1 : use hook_form_alter((&$form, &$form_state, $form_id)
create case for your form_id
Step 2 : Add '#autocomplete_path' to the field where you want to add autocomplete functionality.
Take reference of code given below :-

<?php
$form
['autocomplete_textfield'] = array(
'#title' => t("Autocomplete Textfield"),
'#type' => 'textfield',
'#autocomplete_path' => 'autocomplete/example/textfield'
);
?>

Step 3 :- and in hook_menu() :-

<?php
$items
['autocomplete/example/textfield'] = array(
'page callback' => 'autocomplete_example_textfield',
'access callback' => TRUE,
'weight' => 1,
);
?>

Step 4 :- now define the callback function.

<?php
function autocomplete_example_textfield ($string) {
$items = array();
$query = db_select('node', 'n');
$value = $query->fields('n', array('nid', 'title'));
$value = $query->condition(db_and()->condition('n.status', 1)->condition('title', '%' . db_like($string) . '%', 'LIKE'))
->
orderRandom()
->
execute();
$data = array();
$i = 0;
foreach (
$value as $val) {
$items[$val->nid] = check_plain($val->title);
}
print
drupal_json_output($items);
exit();
}
?>

Source: http://drupal.org/node/1117562

Comments