1.8.1 Introduction

The web.form module has three modules containg different types of fields. web.form.field.basic provides the standard HTML fields such as input boxes or CheckBoxGroups. web.form.field.typed provides fields which return typed data such as Dates and web.form.field.extra provides fields such as email and URL.

The code below will create an Integer field:

>>> import web.form, web.form.field.basic as field
>>> input = field.Input(name='box', default='Default Text', 
...     description='Input Box:', size=14, maxlength=25)
>>> print input.html()
<input type="text" name="box" size="14" maxlength="25" value="Default Text">

This on its own doesn't seem overly useful but when combined with a web.form.Form it becomes much more useful. Following on from the previous example:

>>> exampleForm = web.form.Form(name='form', action='forms.py', method='get')
>>> exampleForm.addField(input)
>>> exampleForm.addAction('Submit')
>>> print exampleForm.html()
<form name="form" class="lemon" action="forms.py" method="get" enctype="">
<table border="0">
<tr><td><table border="0" cellpadding="3" cellspacing="0">
<tr>
  <td valign="top">Input Box: </td>
  <td>&nbsp;&nbsp;&nbsp;</td>
  <td valign="top"><input type="text" name="input" size="14" maxlength="25" valu
e="Default Text"></td>
  <td valign="top"></td>
</tr>
</table>
</td></tr>

</table>
</form>

In this case a properly formatted form is produced with labels for the fields.

Now in order for this to be useful a mechanism is needed for displaying the form data to the user, validating it, re-displaying it with an error message if it is invalid and then finally accessing the data.

To populate the form with data we use the web.cgi object which acts like a dictionary of submitted CGI variables. If the form is submitted then at least one cgi variable will be avaible so if len(web.cgi)>0 then we know someone is trying to submit form data.

>>> if len(web.cgi) > 0: 
...    exampleForm.populate(web.cgi)

The form will now be populated with the information from the web.cgi object. The values submitted to each field may not be of the appropriate types so in order to make sure the information is valid we call the valid() method of the form to validate each field.

Again, following on from the previous example:

>>> if exampleForm.valid():
...     print "It validated"
...
>>> else:
...     print exampleForm.html()
...

If the information entered into the form is not valid exampleForm.html() will return a form with the error marked on so that the user can change the field and resubmit the form. Once every field in the form is valid then we can go ahead and access the fields varaibles by their names like this:

>>> exampleForm['box']
<Input Class. Name='box'>
>>> exampleForm['box'].value
'Default Text'

If a valid value had been submitted then exampleForm['box'].value would have returned that value rather than the default.