James Gardner: Home > Blog > 2007 > Handling a Checkbox in FormEncode

Handling a Checkbox in FormEncode

Posted:2007-09-19 22:26
Tags:Pylons, Python

Checkboxes are tricky in web applications because often you want a value of either True or False to be associated with a variable and you want to handle that with a checkbox which is either ticked or not but an unticked checkbox doesn't submit a value at all which can be a pain for validation.

FormEncode can handle this situation like this:

>>> import formencode
>>>
>>> class MySchema(formencode.Schema):
...     ticked = formencode.validators.StringBoolean(if_missing=False)

You can then do:

>>> MySchema().to_python({})
{'ticked': False}
>>> MySchema().to_python({'ticked': 'true'})
{'ticked': True}

Both these states are handled fine by HTMLFill too:

>>> import formencode.htmlfill
>>> formencode.htmlfill.render('''<input type="checkbox" name="ticked" />''', {'ticked':False})
'<input type="checkbox" name="ticked" />'
>>> formencode.htmlfill.render('''<input type="checkbox" name="ticked" />''', {'ticked':True})
'<input type="checkbox" name="ticked" checked="checked" />'

Occasionally you run into a situation where if a checkbox is ticked you want to run some extra validation. For this you can use FormEncode's RequireIfMissing or `` RequireIfPresent`` validators documented here.

(view source)

James Gardner: Home > Blog > 2007 > Handling a Checkbox in FormEncode