Thursday, August 18, 2016

Using Drupal's autocomplete on a custom form element

http://www.jochenhebbrecht.be/site/2011-01-10/drupal/using-drupals-autocomplete-a-custom-form-element

Did you ever created a custom form? A place where you couldn't use the Form API of Drupal?
Imagine this form, and you want to create an autocomplete feature on the nickname. The moment you start typing a nickname, a list of usernames get in the textfield.
<form action="/foo">
   ...
   <input type="text" value="Nickname"></input>
   <input type="submit" value="Submit"></input>
</form>



Step 1: adjust the HTML code

  • Start from a normal text field
<input id="txt-existing-bidder" type="text"></input>
  • Add attributes to normal text field
<input id="txt-nickname" type="text" class="form-text form-autocomplete text"
       autocomplete="OFF"></input>
  • Add a hidden value to capture the autocomplete values. Put this field immediately after the textfield
<input class="autocomplete" type="hidden" id="txt-nickname-autocomplete"
       value="/##path_to_autocomplete##"/autocomplete" disabled="disabled" />



Step 2: adjust the Javascript code

  • You need the following JS files to have a fully working version:
    drupal_add_js("misc/autocomplete.js");
    drupal_add_js("misc/ahah.js");
  • If the HTML (see above) is added by AJAX, Drupal's autocomplete will not discover the autocomplete fields. Therefore, execute following code after loading the AJAX call
    Drupal.attachBehaviors($("##CONTEXT##"));

    ##CONTEXT##: reference to a div which hold the input


Step 3: create a autocomplete PHP function which returns a JSON object

/**
 * Searches all auction users and returns a JSON object of all users
 * @param $search the value to be searched
 * @return JSON object with all users
 */
function autocomplete_users($search = '') {
        // TODO: implement search function here
 
        // DEBUG
 $users['admin {uid:1}'] = 'admin';
 $users['jochen {uid:2}'] = 'jochen';
 
 return drupal_json($users);
}



Step 4: the result

No comments:

Post a Comment