Skip to Content

Drupal 6: Add Autocomplete to Unlimited Textfield

In Drupal 6 you can using the Form API and hook_form_alter to easily add an autocomplete path to an existing field. Here is a blog post with an example: http://qandeelaslam.com/node/27. The blog example works great for single fields but there is a problem when you have a field that has unlimited values with the “Add another item” button. You can use the hook_form_alter to add an autocomplete path to all the fields in the unlimited value field using this code:

function example_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'example_node_form') {
   if (isset($form['field_example'])) {
     foreach($form['field_example'] as $delta => $field) {
       if(is_array($field) && is_numeric($delta)) {
         $form['field_example'][$delta]['#autocomplete_path'] = 'userreference/autocomplete';
       }
     }
   }
 }
}

The problem is when the user clicks the ‘Add another item’ button it runs a function called ‘content_add_more_js’ located in cck/includes/content.node_form.inc which reloads that field causing the changes to be reset. When that function runs it does call form_alter again but with the form_id ‘content_add_more_js’. Adding that form_id to your hook_form_alter will re-add the autocompletes path to the field solving the problem. As simple as that. Here is the updated example:

function example_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'example_node_form' or $form_id == 'content_add_more_js') {
   if (isset($form['field_example'])) {
     foreach($form['field_example'] as $delta => $field) {
       if(is_array($field) && is_numeric($delta)) {
         $form['field_example'][$delta]['#autocomplete_path'] = 'userreference/autocomplete';
       }
     }
   }
 }
}

I recommend reading the comments in that function, a lot of work when into making the unlimited field work the way it does.

– Daniel Mundra