plonez3c.form

Injecting field errors in z3c.form form action handler


I have a z3c.form where some errors cannot be known before a form action is executed. I'd like to show these errors on the fields, instead of in a global form status message. How any can construct and inject error to widgets in Form.update()?

Example:

@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")

Solution

  • In formlib I solved this task with the set_invariant_error method you can find in this form: - https://github.com/PloneGov-IT/rg.prenotazioni/blob/f6008c9bc4bac4baa61045c896ebd3312a51600d/rg/prenotazioni/browser/prenotazione_add.py#L305

    I think it is reusable with little pain for z3c.form