您可以通过在表单的操作处理程序中进行额外的验证来做到这一点,并引发 WidgetActionExecutionError 指定应显示错误的小部件。
这看起来如下(取自http://plone.org/products/dexterity/documentation/manual/schema-driven-forms/customising-form-behaviour /validation ):
from five import grok
from plone.directives import form
from zope.interface import invariant, Invalid
from zope import schema
from z3c.form import button
from z3c.form.interfaces import ActionExecutionError, WidgetActionExecutionError
from Products.CMFCore.interfaces import ISiteRoot
from Products.statusmessages.interfaces import IStatusMessage
from example.dexterityforms.interfaces import MessageFactory as _
...
class OrderForm(form.SchemaForm):
...
@button.buttonAndHandler(_(u'Order'))
def handleApply(self, action):
data, errors = self.extractData()
# Some additional validation
if 'address1' in data and 'address2' in data:
if len(data['address1']) < 2 and len(data['address2']) < 2:
raise ActionExecutionError(Invalid(_(u"Please provide a valid address")))
elif len(data['address1']) < 2 and len(data['address2']) > 10:
raise WidgetActionExecutionError('address2', Invalid(u"Please put the main part of the address in the first field"))
if errors:
self.status = self.formErrorsMessage
return
我认为也有可能从你的不变量中引发 WidgetActionExecutionError ,但是如果在处理 z3c.form 表单时之外的某个时间检查不变量,它可能不会做你想做的事情。