views:

332

answers:

2

Hi Stackoverflow!

I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template:

<input type="checkbox" name="Project" value="1">Project 1</input>
<input type="checkbox" name="Project" value="2">Project 2</input>
<input type="checkbox" name="Project" value="3">Project 3</input>
<input type="checkbox" name="Project" value="4">Project 4</input>
<input type="checkbox" name="Project" value="5">Project 5</input>

In my validation schema I had something like this (please forgive any errors - I don't have the exact code infront of me):

Project = formencode.foreach.ForEach(formencode.validators.Int())

I was expecting to get a list back of checked items (sounds reasonable, right?) but instead I got a list with a single item despite having all boxes checked. Am I doing this wrong or is what I want to get back even possible? I have written a hack around it with onclicks for each checkbox item that appends the checked item to an array which is then posted back in JSON format - this is ugly and a pain since I have to repopulate all the fields myself if validation fails.

Anyone have any ideas?

+1  A: 

maybe using formencode.validators.Set:

>>> Set.to_python(None)
[]
>>> Set.to_python('this')
['this']
>>> Set.to_python(('this', 'that'))
['this', 'that']
>>> s = Set(use_set=True)
>>> s.to_python(None)
set([])
>>> s.to_python('this')
set(['this'])
>>> s.to_python(('this',))
set(['this'])
nosklo
A: 

redrockettt,

Have you looked at the docstring to variabledecode? It suggests you use something like:

<input type="checkbox" name="Project-1" value="1">Project 1</input>
<input type="checkbox" name="Project-2" value="2">Project 2</input>
<input type="checkbox" name="Project-3" value="3">Project 3</input>

Check out the text in variabledecode.py, or pasted here.

Seth