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

Since Version 1.41 (2008-09-11 09:56:02) web2py supports form widgets.

A form widget is a function that can be used to override the way web2py renders fields in forms.

Example of standard web2py forms

For example, given this model:

db.define_table('person',SQLField('name'),SQLField('gender'))
db.person.gender.requires=IS_IN_SET(['Male','Female','Undeclared'])

and the form:

form=SQLFORM(db.person)

the gender field is rendered by default as a dropbox when the form is inserted in the view {{=form}}.

Defining and using a widget instead

If you do not like this you can use a widget. Let's consider this widget that makes radio boxes instead of the dropbox:

def radioboxes(field,value):
    items=[DIV(name,INPUT(_type='radio',_value=key,_name=field.name,value=value))
           for key,name in field.requires.options()]
    return DIV(*items)

(please refer to the manual for the syntax of the DIV and INPUT helpers).

This widget is general and can be used for any field that ISINSET(...). Here is how to use for the gender field in the example:

db.person.gender.widget=radioboxes

All widgets must take at least two arguments: field and value. When web2py calls the widget for rendering, field is the field object (db.person.gender) and value is the current value of the field.

If create widgets, we suggest you put them in a module for easy reusability, importing them and assign them to the fields in the model file. Widgets can also be assigned in the controller if the same field needs to be represented by different widgets in different actions.

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