Some of the information here may be outdated, please check the book instead
[edit]

What

Normally, if you are making a custom form and want to include a select field, you'd use something like this in your controller:

form = FORM(TABLE(TR('Search in category',SELECT(['Non-Fiction', 'Fiction', 'Childrens'], name="searchcategory",requires=ISINSET(['Non-Fiction', 'Fiction', 'Childrens'])))), TR("",INPUT(type="submit",value="SEARCH"))))

Which would produce a select list like this:

<select name="search_category"> <option value="Non-Fiction">Non-Fiction</option> <option value="Fiction">Fiction</option> <option value="Childrens">Childrens</option> </select>

But what if instead of having a hard-coded set of options you want to gather the options from the database and have the value returned to your controller when the form is submitted be a record id rather than text? This How-To explains how to make a select field that pulls its options from items in the database.

How

In your controller, first build a list of options:

categoryoptions = [OPTION(cat.name,value=cat.id) for cat in db().select(db.categories.ALL,cache=(cache.ram,3600))]

Then feed that list of options into your form:

form = FORM(TABLE(TR('Search in category', SELECT(*categoryoptions, **dict(name="searchcategory",requires=ISINDB(db,'categories.id')))), TR("",INPUT(type="submit",_value="SEARCH"))))

Note that the * and ** in the arguments to SELECT() are important, don't forget them.

This will return a select field that looks like this:

<select name="search_category"> <option value="1">Non-Fiction</option> <option value="2">Fiction</option> <option value="3">Childrens</option> </select>

So now in your controller you can look up the requested category with:

catid = form.vars.searchcategory chosencategory = db.categories[catid]

© 2008-2010 by Massimo Di Pierro - All rights reserved - Powered by web2py - design derived from a theme by the earlybird
The content of this book is released under the Artistic License 2.0 - Modified content cannot be reproduced.