1

我有一个 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")
4

2 回答 2

1

在表单操作中,您可以引发 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-b​​ehaviour/validation.html#validating-in-action-handlers 。

于 2013-07-05T20:41:59.003 回答
1

在 formlib 中,我使用 set_invariant_error 方法解决了此任务,您可以在以下表单中找到: - https://github.com/PloneGov-IT/rg.prenotazioni/blob/f6008c9bc4bac4baa61045c896ebd3312a51600d/rg/prenotazioni/browser/prenotazione_add.py#L305

我认为它对于 z3c.form 来说是可重用的,几乎没有痛苦

于 2013-07-04T09:36:13.483 回答