Checkboxes with pylons
I have been trying to add some check boxes in a pylons mako. However I don't know how to get their values in the controller. It seems that it can only get the first value of the check boxes. I tried using form enc开发者_运维百科ode but i got several errors. Is there an easier way to do this?
Thanks
I'm assuming that "I can only get the first value" means you've got a series of checkboxes with the same value for the 'name' attribute within your form?
Now, if that's the case and you're wanting a list of boolean values based on whether or not the boxes are checked or not, you'll need to do two things:
First, when you define your form elements using form encode on your checkbox, set it up such that a missing value on a checkbox element returns 'False.' This way, as the browser won't send a value over unless a checkbox is "on", you validation coerces the missing value to False.
class Registration(formencode.Schema):
box = formencode.validators.StringBoolean(if_missing=False)
Next, assuming you want a list returned, you'll not be able to name all of your elements the same. Pylons supports a nested structure, though. Look at formencode.variabledecode.NestedVariables. In short, you'll need to define a NestedVariables instance as one of your class attributes and your form 'name' attributes will need to change in order to contain explicit indexes.
Edit.. here's a complete example I did real quick:
import logging
import pprint
import formencode
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.decorators import validate
from testproj.lib.base import BaseController, render
log = logging.getLogger(__name__)
class CheckList(formencode.Schema):
box = formencode.validators.StringBoolean(if_missing=False)
hidden = formencode.validators.String()
class EnclosingForm(formencode.Schema):
pre_validators = [formencode.NestedVariables()]
boxes = formencode.ForEach(CheckList())
class MyformController(BaseController):
def index(self):
schema = EnclosingForm()
v = schema.to_python(dict(request.params))
# Return a rendered template
#return render('/myform.mako')
# or, return a response
response.content_type = 'text/plain'
return pprint.pformat(v)
And then the query string?
boxes-0.box=true&boxes-0.hidden=hidden&boxes-1.box=true& boxes-1.hidden=hidden&boxes-2.hidden=hidden
And lastly, the response:
{'boxes': [{'box': True, 'hidden': u'hidden'}, {'box': True, 'hidden': u'hidden'}, {'box': False, 'hidden': u'hidden'}]}
HTH
精彩评论