Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a boolean field required in a z3c.form?

I'm using z3c.form to create a form in Plone 4.1.4. I need a boolean field which is required: the user must tick the box. (In my case, the user must agree to the terms and conditions.)

Using required=True for the field doesn't work: I can submit the form without checking the checkbox.

This is what my code looks like:

from five import grok
from plone.directives import form
from zope import schema
from z3c.form import button


from Products.CMFCore.interfaces import ISiteRoot
from Products.statusmessages.interfaces import IStatusMessage


class ITestSchema(form.Schema):
    hasApprovedConditions = schema.Bool(
        title=u'I agree to the Terms and Conditions.',
        required=True,
    )


class TestForm(form.SchemaForm):
    grok.name('test-form')
    grok.require('zope2.View')
    grok.context(ISiteRoot)

    schema = ITestSchema
    ignoreContext = True

    @button.buttonAndHandler(u'Send')
    def handleApply(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        IStatusMessage(self.request).addStatusMessage(u'Thanks', 'info')
        self.request.response.redirect(self.context.absolute_url())

The form shows the checkbox and label, but there is no indication that the field is required and indeed it isn't: I can submit the form without ticking the checkbox.

I'm extending these known good sets:

  • http://dist.plone.org/release/4.1.4/versions.cfg
  • http://good-py.appspot.com/release/dexterity/1.2?plone=4.1.4

They pin z3c.form to version 2.5.1 but I also tried version 2.6.1.

What am I missing?

like image 688
Mark van Lent Avatar asked Jan 17 '23 06:01

Mark van Lent


1 Answers

You should use a constraint like this:

def validateAccept(value):
    if not value == True:
        return False
    return True

class ITestSchema(form.Schema):
    hasApprovedConditions = schema.Bool(
        title=u'I agree to the Terms and Conditions.',
        required=True,
        constraint=validateAccept,
    )

More info:

  • http://plone.org/products/collective.examples.userdata
like image 99
Giacomo Spettoli Avatar answered Jan 30 '23 23:01

Giacomo Spettoli