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); }
Comments
hi!
that's a fine step by step;
i was looking exactly for something like this;
is it possible to create a function maped directly to "/##path_to_autocomplete##"/autocomplete" instead of creating a file for it?
thx
ok, i found hook_menu, that makes what i need;
thx
Hi Ropiafoldetnezi,
Sorry for the late reply. I hope you could fix it with hook_menu()?
Regards,
Jochen
yes,
i am playing with 'theme callback' now ;)
thx
"id you ever created a custom form? A place where you couldn't use the Form API of Drupal?"
Very, very bad practice. ALWAYS use Form API adn i can't think of any case that form API does not support.
I have tried this tutorial, it works in drupal 6, but in drupal 7 I got this error:
TypeError: '[object Object]' is not a function (evaluating 'Drupal.behaviors($('##CONTEXT##'))')
I use the input div id for the context.
This blogpost should be removed :-$ ... I'm getting really good in Drupal now, and I must agree with Reda: you CAN do everything with the Forms API! Don't try to do it manually :-( ... This is a very bad post!
Thank you so much! This was really helpful... I just had to replace ahah.js with ajax.js (for Drupal 7) and it all worked like a charm.
Add new comment