我正在使用一个表单,我希望在许多字段上显示必填字段错误,具体取决于另一个字段的值。
用例:使用必须在两种运输模式(postale或print)之间进行选择。如果选择了postale但是地址字段尚未填写,我想提出错误。
这是一些代码
class ILivraisonForm(interface.Interface):
livraison = schema.Choice(title=_(u"Mode de livraison"),
vocabulary=vocabulary.livraison)
livraison_civility = schema.Choice(title=_(u"Civility (livraison)"),
vocabulary=userdata.gender_vocabulary,
required=False)
livraison_name = schema.TextLine(title=_(u"Name (livraison)"),
required=False)
livraison_firstname = schema.TextLine(title=_(u"Firstname (livraison)"),
required=False)
livraison_add1 = schema.TextLine(title=_(u"Address line 1 (livraison)"),
required=False)
livraison_add2 = schema.TextLine(title=_(u"Address line 2 (livraison)"),
required=False)
livraison_pc = schema.TextLine(title=_(u"Postal code (livraison)"),
required=False)
livraison_city = schema.TextLine(title=_(u"City (livraison)"),
required=False)
livraison_phone = schema.TextLine(title=_(u"Phone"),
required=False)
accepted = schema.Bool(title=_(u"Accept CGV"),
description=_(u"Click here to read the CGV"),
required=True)
class LivraisonForm(form.Form):
fields = field.Fields(ILivraisonForm)
@button.buttonAndHandler(_(u"Valider"))
def handleApply(self, action):
data, errors = self.extractData()
message = IStatusMessage(self.request)
if errors:
self.status = _(u"Please fix errors")
return
if not data['accepted']:
self.status = _(u'You must accept')
raise WidgetActionExecutionError('accepted',
interface.Invalid(_(u'You must accept')))
if data['livraison'] == 'mail' \
and ( not data['livraison_name'] or not data['livraison_firstname'] \
or not data['livraison_add1'] or not data['livraison_pc'] \
or not data['livraison_city']):
self.status = _(u'You must add your postal address')
raise ???
答案 0 :(得分:1)
你不需要提出任何东西;只需在您所在的位置添加return
而不是raise
。
此外,您可以在动作处理程序中为各个小部件设置错误消息,前提是您创建了zope.schema.ValidationError
子类:
from zope.schema import ValidationError
class AddressMissing(ValidationError):
__doc__ = _(u'error_noaddress', u'Please provide an address')
然后在处理程序中:
from z3c.form.interfaces import IErrorViewSnippet
from zope import component
def handleApply(self, action):
# ....
widget = self.widgets['livraison_add1']
error = component.getMultiAdapter(
(AddressMissing(), self.request, widget, widget.field,
self, self.context), interfaces.IErrorViewSnippet)
error.update()
widget.error = error
您可以为所有受影响的小部件执行此操作。
或者,您可以使用不变量来处理:
from zope.interface import invariant, Invalid
class ILivraisonForm(interface.Interface):
# ....
@invariant
def validatePostalAddress(data):
if data.livraison. != 'mail':
return
for field in ('name', 'firstname', 'add1', 'pc', 'city'):
if not data['livraison_' + field]:
raise Invalid(_(u'error_noaddress', u'Please provide an address'))
并在您致电self.extractData()
时设置错误。