2

I'm adding Drupal's built in Autocomplete functionality using hook_form_alter to set the #autocomplete_path like so:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  ...
  $form['field_company']['und'][0]['value']['#autocomplete_path'] = 'autocomplete/company';
  ...
}

This works perfectly for a text field where the number of values is 1, but doesn't work when the number of values is unlimited. I'm assuming this has something to do with the field be added via Javascript. Is there another hook I can tap in to in order to add the #autocomplete_path?

EDIT : Drupal 6.

3
  • same issue here. Solved the problem with an alternate method using autocomplete_widgets. But it will be helpful if anyone found solution to above problem!
    – Serjas
    May 2, 2013 at 11:35
  • What do you mean by "Doesn't work" ? May 2, 2013 at 11:42
  • @GregoryKapustin for unlimited value, field will no longer autocomplete ,if we click add more. it will revert back to textfield
    – Serjas
    May 2, 2013 at 11:49

2 Answers 2

4
+25

You have to iterate your field's delta ; here, you only affect $form['field_company']['und']__[0]__, not $form['field_company']['und']__[n]__

Stay in your hook_form_alter but iterate it each time your $form is rebuild :

    foreach($form['field_company']['und'] as $delta => $field) {
        if(is_array($field) && is_numeric($delta)) {
            $form['field_company']['und'][$delta]['value']['#autocomplete_path'] = 'autocomplete/company';
        }
    }
9
  • 1
    It's added with ajax, by field_add_more_js (if you have js enabled) and field_add_more_submit (either way) in field.form.inc . Anyway, use my code, it works, because your hook_form_alter is called on form_rebuild, which happens in that case. May 2, 2013 at 12:38
  • Not working .after clicking add more it reverted back to textfield!
    – Serjas
    May 2, 2013 at 12:55
  • I test again and come back to you. May 2, 2013 at 12:55
  • I'm sorry it works perfectly for me... :( May 2, 2013 at 13:00
  • I am using drupal6 and my field is like this $form['field_test'][0]['#autocomplete_path']
    – Serjas
    May 2, 2013 at 13:17
1

When altering a field with cardinality, I like to use #process. Basically you are defining a function that will get called everytime the field is processed on the form including when added via javascript.

In your case, the code might look like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  ...
  $form['field_company'][$form['field_company']['#language']]['#process'][] = 'field_company_process';  
  ...
}

function field_company_process($element, &$form_state, $complete_form) {
  $element[$element['#max_delta']]['value']['#autocomplete_path'] = 'autocomplete/company';
  return $element;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.