Question

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")
Was it helpful?

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

OTHER TIPS

Within a form action you can raise a WidgetActionExecutionError, passing the field name and an Invalid exception with the message you want to display. z3c.form will then take care of attaching the error to the right widget and rendering it so you don't have to do all the steps yourself.

For your code this would look like this:

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

See http://developer.plone.org/reference_manuals/active/schema-driven-forms/customising-form-behaviour/validation.html#validating-in-action-handlers for another example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top