Fork me on GitHub

Autocomplete with static vocabulary

Autocomplete can make use of a static vocabulary source. Here words of blind text Lorem Ipsum are used. First the static list of words is generated

lipsum = '''Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.'''
lipsum = sorted(set(lipsum.lower().replace('.', '').replace(',', '').split()))

Next, the field is defined as

field = factory('#field:autocomplete', props={
    'label': 'Enter some text (local, lorem ipsum)',
    'value': '',
    'source': lipsum,

Autocomplete with dynamic json vocabulary

Instead of static lists autocomplete may ask the server for a list of words matching a given term. The source is a string and as such interpreted as a absolute or relative url

field = factory('#field:autocomplete', props={
    'label': 'Enter some text (remote listdir)',
    'value': '',
    'source': 'yafowil.widget.autocomplete.json',
    'minLength': 1,

The server answers with a JSON response, here the example does it using WSGI and webob way. This code needs modification depending on the framework used

def json_response(environ, start_response):
    data = lipsum
    if environ['QUERY_STRING'].startswith('term='):
        qsts = environ['QUERY_STRING'][5:]
        data = [_ for _ in data if _.startswith(qsts)]
    response = Response(content_type='application/json',
    return response(environ, start_response)