YUI Autocomplete the easy way

[tags]yui, autocomplete, javascript, jquery, symfony[/tags]

I’m redoing the UI for reviewsby.us and for the Javascript library I am standardizing on is YUI. The trick with YUI is that it’s very verbose and very configurable.

Unfortunately to do simple things you have to write quite a lot. Which, coming from a jQuery background, is not what I’m used to. Yahoo provides a lot of useful examples for Auto Complete, I’ll provide you with another (built in symfony, but anything in any server-side language will work). You’ll need:

  1. A data source
  2. Some YUI
  3. Some javascript of your own
  4. And some HTML

We’re building a tool to grab random items from our database and put them into our Autocomplete field. We also want to capture and id of these items and set them in our form.

Here we go…

Data Source

YUI gives you a lot of options with data sources. In many cases a remote script that returns JSON will be best. JSON is nice, compact, human debuggable and machine-readable.

We can make a searchJSON method that simply takes your database results and wraps them in to a formatted array and then using PHP’s json_encode we can return a nice JSON object.

The ResultSet and Result keys are important as we’ll see later.

We can serve this JSON method very easily in symfony like so:

Note that we use renderText rather than a separate ajaxListSuccess.php file.

YUI

There’s some YUI code that you need. It’s described well in the Autocomplete documentation.

Add the following to your page:

http://yui.yahooapis.com/2.4.1/build/yahoo-dom-event/yahoo-dom-event.js" type="text/javascript
http://yui.yahooapis.com/2.4.1/build/connection/connection-min.js type="text/javascript
http://yui.yahooapis.com/2.4.1/build/autocomplete/autocomplete-min.js
http://yui.yahooapis.com/2.4.1/build/autocomplete/assets/skins/sam/autocomplete.css

These are the bare YUI requirements to get Autocomplete working.

Javascript

There’s a good deal of Javascript that you’ll need to provide on your own. Here’s what I wrote:

MA is my own private namespace. /ajax/object/list is the url of our data source we defined earlier. myInput, myACContainer and object_id are all IDs of elements in our DOM which we’ll look at next.

HTML

Okay I went through this backwards, now we have the HTML.

This is all you need:

The End

That’s it. It might seem like a lot, but YUI offers a tested working solution that works and is very customizable.