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


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="search_category",requires=IS_IN_SET(['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.


In your controller, first build a list of options:

category_options = [OPTION(, 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(*category_options, **dict(_name="search_category",requires=IS_IN_DB(db,'')))), 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:

cat_id = form.vars.search_category chosen_category = db.categories[cat_id]

© 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.