Home Blog CV Projects Patterns Notes Book Colophon Search

Handling a Checkbox in FormEncode

19 Sep, 2007

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.

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.