在z3c.form中注入字段错误表单操作处理程序

时间:2013-07-04 09:08:30

标签: plone z3c.form

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

2 个答案:

答案 0 :(得分:1)

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

我认为它可以重复使用z3c.form

答案 1 :(得分: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-behaviour/validation.html#validating-in-action-handlers