0

I want to make a text field auto complete in a views exposed form. I tried using the following code but nothing happens(I don't see that blue icon in the text field):

<?php
function nk_menu() {
    $items['nk/autocomplete'] = array(
        'page callback' => '_nk_autocomplete',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}
function nk_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-my-page')) {
        $form['title']['#autocomplete_path'] = 'nk/autocomplete';
        $form['title']['#default_value'] = 'abcd'; // this one also doesn't work
        print_r($form); // to be sure that properties has been added to the form (they are added)
    }
}

function _nk_autocomplete($string) {
  // ...
}

Why doesn't it work? I know that there is a module for that, but I want to know why mine doesn't work?

0

Views change elements after form generation, so you should add own after build function:

function nk_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-my-page')) {
      $form['#after_build'][] = 'nk_views_mypage_exposed_after_build';
    }
}

function nk_views_mypage_exposed_after_build($form, &$form_state) {
  $form['title']['#autocomplete_path'] = 'nk/autocomplete';
  $form['title']['#default_value'] = 'abcd'; // this one also doesn't work
//  print_r($form); // I recommend to use dsm function of devel module, instead of print_r.
  return $form;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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