Drupal AutoCompletion sans Form API
I rely heavily on Zend Framework when prototyping Drupal modules. It provides me with an easier way to create and manage my view scripts, database calls, and logic. Recently, I needed to create a form with a text field for username entry. I wanted to provide the user with username AutoCompletion instead of assuming that they will fully type or copy & paste their entry. So lets use Zend_View to enable AutoCompletion for our test field as opposed to making use of Drupal’s Form API.
To begin, I took a look at the source behind the “Edit Comment” form – a common Drupal form that I know uses username AutoCompletion. Two sections are of particular interest to us:
jQuery scripts in the head section ... <script type="text/javascript" src="/misc/jquery.js?x"></script> <script type="text/javascript" src="/misc/drupal.js?x"></script> <script type="text/javascript" src="/misc/autocomplete.js?x"></script> ...
The author text field ... <div class="form-item" id="edit-author-wrapper"> <label for="edit-author">Authored by: </label> <input type="text" maxlength="60" name="author" id="edit-author" size="30" value="admin" class="form-text form-autocomplete" /> </div> <input class="autocomplete" type="hidden" id="edit-author-autocomplete" value="/user/autocomplete" disabled="disabled" /> ...
If you have ever poked around the core node.module you know that this html will only appear if your Drupal installation contains more than 200 users.
Opening up autocomplete.js, we can infer how everything works. When included, Drupal’s AutoCompletion processes every input field with a class of ‘autocomplete’ and an id of ‘{target}-autocomplete’ and a value of ‘{url}’. It will instantiate an AutoCompletion callback on ‘{url}’ if another field of id ‘{target}’ exists on the page.
So, we can write the following code to create the same effect using Zend_View in a module’s page callback function:
function page_callback() { $view = Zend_Registry::get('view'); // Force Drupal to include JS scripts @drupal_add_js('misc/autocomplete.js'); // Return a simple example of what we discussed return $view->formText('username', null, array('size' => '30', 'maxlength' => '60', 'class' => 'form-autocomplete')) . $view->formHidden('username-autocomplete', '/user/autocomplete', array('disabled' => 'disabled', 'class' => 'autocomplete')); }
A class of ‘form-autocomplete’ on the text field adds the standard Drupal AutoCompletion indicators provided by our theme’s css. ‘/user/autocomplete’ is the url to the user.module callback that provides us with a list of usernames for AutoCompletion. Its that simple!











