我有一个z3c.form,其中一些错误在执行表单操作之前是无法获知的。我希望在字段中显示这些错误,而不是在全局表单状态消息中显示。如何在Form.update()中构造和注入错误到小部件?
示例:
@z3c.form.button.buttonAndHandler(_('Make Report'), name='report')
def report(self, action):
data, errors = self.extractData()
if errors:
self.status = "Please correct errors"
return
# Create sample item which we can consume in the page template
try:
self.output = make_report(self.context, self.request, data, filters=filters)
except zope.interface.Invalid as e:
self.status = e.message
self.errors = True
# How to target the error message to a particular field here
return
self.status = _(u"Report complete")发布于 2013-07-04 17:36:13
在formlib中,我用set_invariant_error方法解决了这个问题,您可以在下面的表单中找到:- https://github.com/PloneGov-IT/rg.prenotazioni/blob/f6008c9bc4bac4baa61045c896ebd3312a51600d/rg/prenotazioni/browser/prenotazione_add.py#L305
我认为对于z3c.form来说,它是可以重用的,不会有太大的麻烦。
发布于 2013-07-06 04:41:59
在表单操作中,您可以引发WidgetActionExecutionError,传递字段名称和包含要显示的消息的无效异常。然后,z3c.form将负责将错误附加到正确的小部件并呈现它,这样您就不必自己执行所有步骤。
对于您的代码,如下所示:
from z3c.form.interfaces import WidgetActionExecutionError
@z3c.form.button.buttonAndHandler(_('Make Report'), name='report')
def report(self, action):
data, errors = self.extractData()
if errors:
self.status = "Please correct errors"
return
# Create sample item which we can consume in the page template
try:
self.output = make_report(self.context, self.request, data, filters=filters)
except zope.interface.Invalid as e:
raise WidgetActionExecutionError('target_field_name', e)
self.status = _(u"Report complete")有关另一个示例,请参阅http://developer.plone.org/reference_manuals/active/schema-driven-forms/customising-form-behaviour/validation.html#validating-in-action-handlers。
https://stackoverflow.com/questions/17466304
复制相似问题