如何在z3c.form中创建一个布尔字段?

Mar*_*ent 4 forms plone z3c.form

我正在使用z3c.form在Plone 4.1.4中创建一个表单.我需要一个必需的布尔字段:用户必须勾选该框.(就我而言,用户必须同意条款和条件.)

使用required=True该字段不起作用:我可以提交表单而不选中复选框.

这就是我的代码:

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())
Run Code Online (Sandbox Code Playgroud)

表单显示复选框和标签,但没有迹象表明该字段是必需的,实际上并非如此:我可以提交表单而不勾选复选框.

我正在扩展这些已知的好集:

他们将z3c.form固定为2.5.1版本,但我也尝试了2.6.1版本.

我错过了什么?

Gia*_*oli 9

你应该使用这样的约束:

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,
    )
Run Code Online (Sandbox Code Playgroud)

更多信息:

  • 我以为我试过了.一定是犯了错误.谢谢.(唯一的"缺陷"是表示字段未明确标记为必填项.) (2认同)