How to create a boolean field in z3c.form?

I am using z3c.form to create a form in Plone 4.1.4. I need a logical field that is required: the user must check the box. (In my case, the user must agree to the terms and conditions.)

Using required=True for the field does not work: I can submit the form without checking the box.

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 a flag and a label, but there is no indication that this field is necessary, and indeed it is not: I can submit the form without a checkmark.

I am expanding these famous good sets:

They write z3c.form up to version 2.5.1, but I also tried version 2.6.1.

What am I missing?

+4
source share
2 answers

You should use a restriction 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, ) 

Additional Information:

+8
source

to answer the "flaw" you noticed @Mark van Lent - just add:

 description=_(u'Required'), 
0
source

Source: https://habr.com/ru/post/1401026/


All Articles